以下内容归纳了通过Java程序打印PDF文档时的3种情形。即:
- 静默打印
- 显示打印对话框打印
- 打印PDF时自定义纸张大小
使用工具:Spire.PDF for Java
Jar导入:
方法1:通过官网下载jar包。
方法2:通过maven库导入。参考导入方法。
Java代码示例
【示例1】静默打印
即通过使用默认打印机直接打印PDF文档。打印时,我们可以设置打印份数,设置纸张打印页边距等。
import com.spire.pdf.*; import java.awt.print.*; public class Print { public static void main(String[] args) { //加载文档 PdfDocument pdf = new PdfDocument(); pdf.loadFromFile("Sample.pdf"); PrinterJob loPrinterJob = PrinterJob.getPrinterJob(); PageFormat loPageFormat = loPrinterJob.defaultPage(); Paper loPaper = loPageFormat.getPaper(); //删除默认页边距 loPaper.setImageableArea(0,0,loPageFormat.getWidth(),loPageFormat.getHeight()); //设置打印份数 loPrinterJob.setCopies(2); loPageFormat.setPaper(loPaper); loPrinterJob.setPrintable(pdf,loPageFormat); try { loPrinterJob.print(); } catch (PrinterException e) { e.printStackTrace(); } } }
【示例2】显示打印对话框打印PDF文档
import com.spire.pdf.*; import java.awt.print.*; public class Print { public static void main(String[] args) { //加载文档 PdfDocument pdf = new PdfDocument(); pdf.loadFromFile("Sample.pdf"); PrinterJob loPrinterJob = PrinterJob.getPrinterJob(); PageFormat loPageFormat = loPrinterJob.defaultPage(); Paper loPaper = loPageFormat.getPaper(); //删除默认页边距 loPaper.setImageableArea(0,0,loPageFormat.getWidth(),loPageFormat.getHeight()); loPageFormat.setPaper(loPaper); loPrinterJob.setPrintable(pdf,loPageFormat); //显示打印对话框 if (loPrinterJob.printDialog()) { try { loPrinterJob.print(); } catch (PrinterException e) { e.printStackTrace(); } } } }
【示例3】打印时自定义纸张大小
import com.spire.pdf.*; import java.awt.print.*; public class Print { public static void main(String[] args) { //加载文档 PdfDocument pdf = new PdfDocument(); pdf.loadFromFile("Sample.pdf"); PrinterJob loPrinterJob = PrinterJob.getPrinterJob(); PageFormat loPageFormat = loPrinterJob.defaultPage(); //设置打印纸张大小 Paper loPaper = loPageFormat.getPaper(); loPaper.setSize(500,600); loPageFormat.setPaper(loPaper); loPrinterJob.setPrintable(pdf,loPageFormat); try { loPrinterJob.print(); } catch (PrinterException e) { e.printStackTrace(); } } }
如果需要更详细的打印设置,可以在PrinterJob下设置相应的参数,可参考:https://www.programcreek.com/java-api-examples/java.awt.print.PrinterJob
扩展:C# 打印PDF文档的10种方法,请参阅这篇文章。(注:使用Spire.PDF for .NET)
(本文完)