如下內容概括了經過Java程序打印PDF文檔時的3種情形。即:html
使用工具:Spire.PDF for Javajava
Jar導入:api
方法1:經過官網下載jar包。maven
方法2:經過maven庫導入。參考導入方法。工具
即經過使用默認打印機直接打印PDF文檔。打印時,咱們能夠設置打印份數,設置紙張打印頁邊距等。spa
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
擴展:C# 打印PDF文檔的10種方法,請參閱這篇文章。(注:使用Spire.PDF for .NET)code
(本文完)orm