3
votes

I have to print a PDF file using java application. I have tried such approach:

FileInputStream psStream = new FileInputStream("<path to file>");
PrintService service = getPrinterByName("some printer name");
if (service != null) {
    DocPrintJob printJob = service.createPrintJob();
    Doc document = new SimpleDoc(psStream, DocFlavor.INPUT_STREAM.AUTOSENSE, null);
    try {
        printJob.print(document, null);
    } catch (PrintException e) {
        e.printStackTrace();
    }
}

private PrintService[] getPrintersList() {
    DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
    PrintService[] services = PrintServiceLookup.lookupPrintServices(flavor, null);

    return services;
}

private PrintService getPrinterByName(String name) {
    PrintService[] list = getPrintersList();
    if (list.length > 0) {
        for (PrintService service : list) {
            if (service.getName().contains(name)) {
                return service;
            }
        }
    }
    return null;
}

When I tested this on fake printer (I used PDFCreator as a printer) everything was OK, but when I tried to print on physical printer, nothing happend.

Then I used PDFBox. Document was printed, but with strange dots between words, in places where they should not be.

So, maybe someone have experience with printing PDF from java applications and can share this information?

1

1 Answers

1
votes

Sending a PDF file directly to a printer will only work for printers that support the PDF format natively. This will be supported by any virtual PDF printer, but not by most of the hardware printers out-there. If you want to print a PDF file reliably, you need to use a library to render its content into the printer.

Take look then at this question in SO:
Which Java based PDF rendering library should I use for printing?

Update: The link above is broken but there is no replacement for it other that doing a google search. Unfortunately stack-overflow owners decided that questions related to library recommendations are not welcome.