Skip to content

Instantly share code, notes, and snippets.

@gexiangdong
Last active March 31, 2019 01:06
Show Gist options
  • Save gexiangdong/fe70fa62555adacf619d8c89e2d2aebe to your computer and use it in GitHub Desktop.
Save gexiangdong/fe70fa62555adacf619d8c89e2d2aebe to your computer and use it in GitHub Desktop.
Java打印方式汇总

实现Java打印功能有3种方式

javax.print.PrintService

使用javax.print包下的类来打印,可以打印文档,PDF等等文档

Doc doc = new SimpleDoc(new FileInputStream("tobeprint.pdf"), DocFlavor.BYTE_ARRAY.PDF, null);
PrintService ps = PrintServiceLookup.lookupDefaultPrintService();
DocPrintJob job = ps.createPrintJob();
job.print(doc, null);

java.awt.PrinterJob

awt的实现,可以通过Printable 打印 Graphics,自己程序绘制要打印的内容。 例子: https://gist.github.com/gexiangdong/af18ff74b77e9529e4e8fb5c1dac4d1c

javafx.print.PrinterJob

这是javafx的实现,可以打印Canvas,类似awt的功能

final Canvas canvas = new Canvas(250,250);
GraphicsContext gc = canvas.getGraphicsContext2D();
gc.fillText("hello, world.", 10, 10);
PrinterJob printerJob = PrinterJob.createPrinterJob();
printerJob.printPage(canvas);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment