class="MsoNormal">以下内容归纳了通过Java程序打印PDF文档时的3种情形。即:
?
?
使用工具:Spire.PDF for Java
Jar导入:
方法1:通过官网下载jar包。
方法2:通过maven库导入。参考导入方法。
?
?
即通过使用默认打印机直接打印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(); } } }
?
?
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(); } } } }
?
?
?
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
?
(本文完)
?
?
?