PDFBox: How to print pdf with specified printer?

Firzen picture Firzen · Sep 5, 2013 · Viewed 31k times · Source

I want to use PDFBox for printing PDF files created by iText. I have tried this successfully with PDDocument class and its method print(). You can find documentation here: http://pdfbox.apache.org/apidocs/.

(I am using this code:)

public static void printPDF(String fileName)
        throws IOException, PrinterException {
    PDDocument doc = PDDocument.load(fileName);
    doc.print();
}

The method print() works great, but there is one problem: When I need to print multiple files, the method asks me to select printer for each one of documents..

Is there any way how to set printer only once?

For printer selection I can use this code for example:

public static PrintService choosePrinter() {
    PrinterJob printJob = PrinterJob.getPrinterJob();
    if(printJob.printDialog()) {
        return printJob.getPrintService();          
    }
    else {
        return null;
    }
}

Thanks in advance


Solution:

public static PrintService choosePrinter() {
    PrinterJob printJob = PrinterJob.getPrinterJob();
    if(printJob.printDialog()) {
        return printJob.getPrintService();          
    }
    else {
        return null;
    }
}

public static void printPDF(String fileName, PrintService printer)
        throws IOException, PrinterException {
    PrinterJob job = PrinterJob.getPrinterJob();
    job.setPrintService(printer);
    PDDocument doc = PDDocument.load(fileName);
    doc.silentPrint(job);
}

Answer

mkl picture mkl · Sep 8, 2013

PDDocument also offers other print methods than the parameterless print():

public void print(PrinterJob printJob) throws PrinterException;
public void silentPrint() throws PrinterException;
public void silentPrint(PrinterJob printJob) throws PrinterException;

The silentPrint methods don't show the dialog.

You may get what you want by first selecting a printer and then call silentPrint with PrinterJob instances initialized accordingly.