Forum Discussion
How to print PDF file?
For a Java-based workflow, Apache PDFBox is a free library that can send a PDF to a printer. Its printing API lets you control scaling rather than relying on a browser.
Install Java 17, download the pdfbox-app JAR, and save this as PrintPdf.java:
import java.io.File;
import java.awt.print.PrinterJob;
import org.apache.pdfbox.Loader;
import org.apache.pdfbox.printing.PDFPrintable;
import org.apache.pdfbox.printing.Scaling;
class PrintPdf {
public static void main(String[] args) throws Exception {
try (var pdf = Loader.loadPDF(new File("document.pdf"))) {
PrinterJob job = PrinterJob.getPrinterJob();
if (!job.printDialog()) {
return;
}
var pageFormat = job.pageDialog(job.defaultPage());
job.setPrintable(
new PDFPrintable(pdf, Scaling.SHRINK_TO_FIT),
pageFormat
);
job.print();
}
}
}
Run it with your downloaded JAR filename:
java -cp pdfbox-app-3.0.3.jar PrintPdf.java
The program opens printer and page-setup dialogs before printing. SHRINK_TO_FIT reduces oversized pages without enlarging smaller ones. Use ACTUAL_SIZE instead only when you need exact dimensions and the page fits the printer’s printable area.
This example doesn’t arrange two pages on one sheet; use the printer driver’s setting if available. PDFBox is useful for automation, but more setup than necessary for printing an occasional report.