0

I found a Java printing example here.

Unfortunately, trying to execute I got a exception

Exception in thread "main" sun.print.PrintJobFlavorException: invalid flavor
at sun.print.Win32PrintJob.print(Unknown Source)
at application.UsePrintingServiceInJava.main(UsePrintingServiceInJava.java:55)

I also tried to print a png using DocFlavor.INPUT_STREAM.PNG flavor instead of the pdf, this works fine. May there be a problem with the printer itself or do I have to change the code?

Moreover, if you have got a better solution to print a PDF file in Java, let me know.

Prodoxon
  • 11
  • 1
  • 2
  • Check this [answer](http://stackoverflow.com/a/18962278/34088) – Gatusko Jan 03 '17 at 12:54
  • @Gatusko - The solution shown in the [answer](http://stackoverflow.com/questions/16293859/print-a-pdf-file-using-printerjob-in-java/18962278#18962278) seems to be correct, it sends a printjob to the printer (as I can see in the "printjob" window of Windows). Problem is that after a while the print job dissapears without effect: The document isn't printed. – Prodoxon Jan 03 '17 at 17:06

1 Answers1

1

Finally, the Apache PDFBox solved my problem. I downloaded pdfbox-app-2.0.4.jar and added it to the build path. Now executing the following code prints the desired .pdf file:

public class Main {

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

        String filename = "C:/Users/Prodoxon/Documents/test.pdf"; 
        PDDocument document = PDDocument.load(new File (filename));

        //takes standard printer defined by OS
        PrintService myPrintService = PrintServiceLookup.lookupDefaultPrintService();

        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;
    }   

}

Even if it shows no print dialog, I think it is a good solution if you just want to print a file.

Prodoxon
  • 11
  • 1
  • 2