The following content summarizes three situations when printing PDF documents through Java programs. Namely:
- Silent printing
- Display Print dialog print
- Custom paper size when printing PDF
Using tool: Spire.PDF for Java
Jar import:
Method 1: Pass Download official website jar bag.
Method 2: import through maven library. Reference resources Import method.
Java code example
[example 1] silent printing
The PDF document is printed directly by using the default printer. When printing, we can set the number of copies to be printed, set the margin of the paper to be printed, etc.
import com.spire.pdf.*; import java.awt.print.*; public class Print { public static void main(String[] args) { //Loading documents PdfDocument pdf = new PdfDocument(); pdf.loadFromFile("Sample.pdf"); PrinterJob loPrinterJob = PrinterJob.getPrinterJob(); PageFormat loPageFormat = loPrinterJob.defaultPage(); Paper loPaper = loPageFormat.getPaper(); //Delete default margins loPaper.setImageableArea(0,0,loPageFormat.getWidth(),loPageFormat.getHeight()); //Set the number of copies to be printed loPrinterJob.setCopies(2); loPageFormat.setPaper(loPaper); loPrinterJob.setPrintable(pdf,loPageFormat); try { loPrinterJob.print(); } catch (PrinterException e) { e.printStackTrace(); } } }
[example 2] display printing dialog box to print PDF document
import com.spire.pdf.*; import java.awt.print.*; public class Print { public static void main(String[] args) { //Loading documents PdfDocument pdf = new PdfDocument(); pdf.loadFromFile("Sample.pdf"); PrinterJob loPrinterJob = PrinterJob.getPrinterJob(); PageFormat loPageFormat = loPrinterJob.defaultPage(); Paper loPaper = loPageFormat.getPaper(); //Delete default margins loPaper.setImageableArea(0,0,loPageFormat.getWidth(),loPageFormat.getHeight()); loPageFormat.setPaper(loPaper); loPrinterJob.setPrintable(pdf,loPageFormat); //Show print dialog if (loPrinterJob.printDialog()) { try { loPrinterJob.print(); } catch (PrinterException e) { e.printStackTrace(); } } } }
[example 3] custom paper size when printing
import com.spire.pdf.*; import java.awt.print.*; public class Print { public static void main(String[] args) { //Loading documents PdfDocument pdf = new PdfDocument(); pdf.loadFromFile("Sample.pdf"); PrinterJob loPrinterJob = PrinterJob.getPrinterJob(); PageFormat loPageFormat = loPrinterJob.defaultPage(); //Set print paper size Paper loPaper = loPageFormat.getPaper(); loPaper.setSize(500,600); loPageFormat.setPaper(loPaper); loPrinterJob.setPrintable(pdf,loPageFormat); try { loPrinterJob.print(); } catch (PrinterException e) { e.printStackTrace(); } } }
If you need more detailed print settings, you can set the corresponding parameters under PrinterJob. Please refer to: https://www.programcreek.com/java-api-examples/java.awt.print.PrinterJob
Extension: there are 10 ways to print PDF documents, please refer to This article . (Note: use Spire.PDF for .NET)
(end of this paper)