Print a PDF file using PrinterJob in Java

My Printer did not support native PDF printing.

I used the open source library Apache PDFBox https://pdfbox.apache.org to print the PDF. The printing itself is still handeled by the PrinterJob of Java.

import java.awt.print.PrinterJob;
import java.io.File;

import javax.print.PrintService;
import javax.print.PrintServiceLookup;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.printing.PDFPageable;

public class PrintingExample {

    public static void main(String args[]) throws Exception {

        PDDocument document = PDDocument.load(new File("C:/temp/example.pdf"));

        PrintService myPrintService = findPrintService("My Windows printer Name");

        PrinterJob job = PrinterJob.getPrinterJob();
        job.setPageable(new PDFPageable(document));
        job.setPrintService(myPrintService);
        job.print();

    }       

    private static PrintService findPrintService(String printerName) {
        PrintService[] printServices = PrintServiceLookup.lookupPrintServices(null, null);
        for (PrintService printService : printServices) {
            if (printService.getName().trim().equals(printerName)) {
                return printService;
            }
        }
        return null;
    }
}

Leave a Comment