Java6学习笔记46——JAVA中的打印图片

import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Color;
import java.awt.print.PrinterJob;
import java.awt.print.Printable;
import java.awt.print.PageFormat;
import java.awt.print.PrinterException;

public class PrintDemo3 {
public static void main(String arg[]) {
PrinterJob printerjob = PrinterJob.getPrinterJob();
HelloPrinter printable = new HelloPrinter();
printerjob.setPrintable(printable);
boolean performPrinting = printerjob.printDialog();//弹出打印窗口
if(performPrinting) {
try {
printerjob.print();
System.out.println("print succeeded");
} catch(PrinterException e) {
System.out.println("print failed");
System.out.println(e);
}
} else {
System.out.println("print job cancelled");
}
}
}

class HelloPrinter implements Printable {
public int print(Graphics g,PageFormat pf,int page)
throws PrinterException {
if(page > 0)
return(NO_SUCH_PAGE);//从第0页开始打印

Graphics2D g2 = (Graphics2D)g;
g2.translate(pf.getImageableX(),pf.getImageableY());//设置页面大小

g2.drawString("Hello printer",30,30);
g2.setColor(Color.green);
g2.fillOval(40,40,100,100);
g2.setColor(Color.red);
g2.fillOval(150,150,300,100);

return(PAGE_EXISTS);
}
}

你可能感兴趣的:(java)