Print a PDF file using PrinterJob in Java
Asked Answered
D

6

19

I have an issue when trying to print a PDF file using Java. Here is my code:

PdfReader readFtp = new PdfReader();    // This class is used for reading a PDF file
PDDocument document = readFtp.readFTPFile(documentID);

printRequestAttributeSet.add(new PageRanges(1, 10));

job.setPageable(document);
job.print(printRequestAttributeSet);    // calling for print

document.close()


I use document.silentPrint(job); and job.print(printRequestAttributeSet); - it works fine. If I use document.silentPrint(job); - I can't set the PrintRequestAttributeSet.

Can anyone tell me how to set the PrintRequestAttributeSet?

Defunct answered 30/4, 2013 at 6:46 Comment(0)
L
38

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;
    }
}
Little answered 8/7, 2016 at 18:38 Comment(3)
it's better to close the PDDocument, hence you would need a try catch and a finally, but overall ok!Gaucherie
@Little were you able to get the print status automatically with this method?Grove
@Grove I did not use the print status back then. Just fire and forget.Little
I
21

This worked for me to print a PDF with a plain JRE:

public static void main(String[] args) throws PrintException, IOException {
    DocFlavor flavor = DocFlavor.SERVICE_FORMATTED.PAGEABLE;
    PrintRequestAttributeSet patts = new HashPrintRequestAttributeSet();
    patts.add(Sides.DUPLEX);
    PrintService[] ps = PrintServiceLookup.lookupPrintServices(flavor, patts);
    if (ps.length == 0) {
        throw new IllegalStateException("No Printer found");
    }
    System.out.println("Available printers: " + Arrays.asList(ps));

    PrintService myService = null;
    for (PrintService printService : ps) {
        if (printService.getName().equals("Your printer name")) {
            myService = printService;
            break;
        }
    }

    if (myService == null) {
        throw new IllegalStateException("Printer not found");
    }

    FileInputStream fis = new FileInputStream("C:/Users/John Doe/Desktop/SamplePDF.pdf");
    Doc pdfDoc = new SimpleDoc(fis, DocFlavor.INPUT_STREAM.AUTOSENSE, null);
    DocPrintJob printJob = myService.createPrintJob();
    printJob.print(pdfDoc, new HashPrintRequestAttributeSet());
    fis.close();        
}
Integrate answered 23/9, 2013 at 14:45 Comment(4)
This only works on Linux, right? I believe on Windows there is no PDF renderer in Java, correct?Mitosis
@Mirko Seifert This code won't work, my printer prints only unreadable characters instead my PDF doc.Tinny
The code only works with printers which are capable of interpreting the PDF on their own. I found some printers which do so (e.g., some HP LaserJet models), but I also experienced that some printers print the raw content of the PDF file (as text). In such a case you'll need to convert the PDF to an image (e.g., using Ghostview).Integrate
Although posted many years ago, this response still works today and saved me hours of development effort. Thank you, sir. Wherever you may be today, thank you!Arithmetic
A
3

The following worked for me to print multiple PDF document with a print dialog:

public void printPDF()
{
    PrinterJob printerJob = PrinterJob.getPrinterJob();

    PrintService printService;
    if(printerJob.printDialog())
    {
        printService = printerJob.getPrintService();
    }
    DocFlavor docType = DocFlavor.INPUT_STREAM.AUTOSENSE;

    for (//fetch documents to be printed)
    {
        DocPrintJob printJob = printService.createPrintJob();
        final byte[] byteStream = // fetch content in byte array;
            Doc documentToBePrinted = new SimpleDoc(new ByteArrayInputStream(byteStream), docType, null);
        printJob.print(documentToBePrinted, null);
    }
}
Afghani answered 24/5, 2016 at 9:9 Comment(0)
W
0

Try this code:

FileInputStream fis = new FileInputStream(“C:/mypdf.pdf”);
Doc pdfDoc = new SimpleDoc(fis, null, null);
DocPrintJob printJob = printService.createPrintJob();
printJob.print(pdfDoc, new HashPrintRequestAttributeSet());
fis.close();

You can also follow these steps

Whiplash answered 30/4, 2013 at 6:50 Comment(1)
How he can print PDF without a DocFlavor?Tinny
P
0
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 Main {

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

        String filename = "Path for PDF File"; 
        PDDocument document = PDDocument.load(new File (filename));

        //takes standard printer defined by OS
        PrintService myPrintService = PrintServiceLookup.lookupDefaultPrintService();
        myPrintService = findPrintService("Your 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;
    }

Use version 2.0.4 of Apache PDFBox. If using Maven Project, include the following in the XML file.

<dependency>
    <groupId>org.apache.pdfbox</groupId>
    <artifactId>pdfbox</artifactId>
    <version>2.0.4</version>
</dependency>
Pahl answered 31/5, 2021 at 14:21 Comment(2)
2.0.4 is outdatedBroglie
@Pahl were you able to get the print status automatically with this method?Grove
F
-1

Pageable implementation of PDDocument is deprecated, use PDPageable adapter class instead and try setPrintable instead of setPageable:

job.setPrintable(new PDPageable(document));
Foregone answered 28/3, 2014 at 13:31 Comment(2)
hello new user! a better example that shows how to set the PageRanges with your example would be nice as well as a reference to the javadoc apis and versionClearstory
PDFPageable is not a valid parameter for the PrintJob.setPrintable method.Windbroken

© 2022 - 2024 — McMap. All rights reserved.