用java写一个打印机程序 | 张恒镭的博客

用java写一个打印机程序

时间:16-06-24 栏目:java编程 作者:longteng 评论:0 点击: 3,027 次

A Basic Printing Program

 

Printer.

 

package test.test;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.print.*;

public class Printer {

   
    public static void main(String[] args) {
        PrinterJob job = PrinterJob.getPrinterJob();
        job.setPrintable(new HelloWorldPrinter());
       
        boolean doPrint = job.printDialog();
        if (doPrint) {
            try {
                job.print();
            } catch (PrinterException e) {
                // The job did not successfully
                // complete
            }
        }
    }
}

class HelloWorldPrinter
    implements Printable {

  public int print(Graphics g, PageFormat pf, int page)
      throws PrinterException {

    // We have only one page, and 'page'
    // is zero-based
    if (page > 0) {
         return NO_SUCH_PAGE;
    }

    // User (0,0) is typically outside the
    // imageable area, so we must translate
    // by the X and Y values in the PageFormat
    // to avoid clipping.
    Graphics2D g2d = (Graphics2D)g;
    g2d.translate(pf.getImageableX(), pf.getImageableY());

    // Now we perform our rendering
    g.drawString("Hello world!", 100, 100);

    // tell the caller that this page is part
    // of the printed document
    return PAGE_EXISTS;
  }
}

 

参考: http://docs.oracle.com/javase/tutorial/2d/printing/printable.html

声明: 本文由( longteng )原创编译,转载请保留链接: 用java写一个打印机程序

用java写一个打印机程序:等您坐沙发呢!

发表评论




------====== 本站公告 ======------
欢迎关注我的博客。

其他