Skip to content
Advertisement

PDF stuck in “printing” state using Java PDFBox 2.0.21

I am trying to setup a printer class in Java that can print PDF files using PDFBox. My printPdf method successfully adds the .pdf file in the printer’s queue but it does not print at all (it gets stuck in the “printing…” state).

It only happens to some specific PDF files. For some pdf files it will work perfectly, for some the issue will happen.

Here is the code I used to print the pdf files:

File file = new File("C:/Users/user/Desktop/Java Printing.pdf");
FilePrinter.printPdf(file, "Printer name");

FilePrinter.printPdf method:

public static void printPdf(File pdfFile, String laserName)
{
    PDDocument document = null;
    try {
        PrintRequestAttributeSet attr = new HashPrintRequestAttributeSet();
        attr.add(MediaSizeName.ISO_A4);
        attr.add(Sides.DUPLEX);
        document = PDDocument.load(pdfFile);

        PrintService[] printServices = PrintServiceLookup.lookupPrintServices(null, null);
        PrintService myPrintService = PrintServiceLookup.lookupDefaultPrintService();

        for (PrintService printer : printServices) {
            if (printer.getName().equals(laserName))
                myPrintService = printer;
        }

        PrinterJob job = PrinterJob.getPrinterJob();

        job.setPageable(new PDFPageable(document));
        job.setPrintService(myPrintService);

        job.print(attr);

    }
    catch(Exception e)
    {
        e.printStackTrace();
    }
    finally{
        if(document != null) {
            try {
                document.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

The pdf file I’m trying to print has 2 pages (It’s not corrupted I can open it in any web browser), but in the file properties in the printer queue, it shows that the file size is 0 and has 0 page (cf next picture)

File properties inside the printer’s queue

Printer’s queue status when I try to print the PDF

Is this issue related to PDFBox? To my printer? If I try printing it from my web browser it works like a charm but I really can’t print it with java.

Advertisement

Answer

Fixed after fully uninstalling and reinstalling the printer’s drivers. Windows was wrong when it was telling me they were up to date !

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement