本文将介绍如何在Java应用程序中打印PDF文档。一般有以下三种打印方式:
- 静默打印
- 显示打印对话框打印
- 打印PDF时自定义纸张大小
使用工具:Free Spire.PDF for Java
创建运行环境:
方式 1: 通过官网下载组件,解压后将lib文件夹下的Spire.Pdf.jar手动导入IDEA中。具体步骤可参考下图。
方式 2:通过Maven仓库安装产品及导入相关依赖包。在pom.xml文件中配置Maven仓库路径,及指定Free Spire.PDF for Java的Maven依赖。
com.e-icebluehttp://repo.e-iceblue.cn/repository/maven-public/e-icebluespire.pdf.free2.6.3
配置完成后,在IDEA中,您只需点击"Import Changes"即可导入JAR包;在Eclipse中,则需点击"Save"按钮。
代码示例
- 静默打印
import com.spire.pdf.*;import java.awt.print.*;public class Print { public static void main(String[] args) { //加载文档 PdfDocument pdf = new PdfDocument(); pdf.loadFromFile("C:甥敳獲Test1DesktopSample.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(); } }}
- 显示打印对话框打印PDF文档
import com.spire.pdf.*;import java.awt.print.*;public class Print { public static void main(String[] args) { //加载文档 PdfDocument pdf = new PdfDocument(); pdf.loadFromFile("C:甥敳獲Test1DesktopSample.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("C:甥敳獲Test1DesktopSample.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(); } }}