Mark Stephens Mark has been working with Java and PDF since 1999 and is a big NetBeans fan. He enjoys speaking at conferences. He has an MA in Medieval History and a passion for reading.

Are you a Java Developer working with PDF files?

Find out why you should be using JPedal

How to print PDF files from Java

2 min read

Printing PDF files from Java is something that raises a lot of general questions, so this short article is a general guide to the options available. Java itself contains a built-in print system (JPS). JPS itself does not internally support the PDF file format.

There are 3 ways to print PDF files in Java:-

1. Use a printer that directly supports PDF files and use JPS to send the data directly to it.

All the work is done by the printer, often in hardware so this is a brilliant solution if you can precisely define the printers used but does not provide a generic solution. If you want to try this, here is some generic 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();

2. Print from Java using a non-java application

Java allows you to access non-java code so that you can access Acrobat, Ghostscript, CUPS, or any other solution. You can do this with the Java command

Runtime.getRuntime().exec(“commands”);

Again, this works if you have control of the exact platforms and software available but does not provide a generic solution.

3. Print using JPS

JPS does not include PDF support, but it does have hooks to allow any Java program to print content to any printer. A number of Java PDF libraries offer printing – including ours! They essentially convert the PDF into a rendered page which JPS then prints. This provides a generic solution but the files tend to be larger and it relies on the capabilities of the Java PDF library which vary.

This is the solution we use in our JPedal Java PDF library. There is a detailed 5 step tutorial showing how you can print (which will be relevant to any library using JPS).

All three methods have their pros and cons so try them to find out which one offers the best fit for your requirements.

How to Print in Java using JPedal
Our JPedal Java PDF library implements JPS so here is the code you would use to print a PDF file.

  1. Create a DocPrintJob. In my code I just had to add
    PrintService[] service=PrinterJob.lookupPrintServices(); //list of printers
    
    printJob= service[i].createPrintJob(); //is whichever printer you use
  2. Wrap your Pageable or Printable object inside a doc, specifying which interface to use in the call
    Doc doc=new SimpleDoc(decode_pdf, DocFlavor.SERVICE_FORMATTED.PAGEABLE,null);
  3. Call the print method.
    printJob.print(doc,null);
  4. Finally, you can now add a listener to track what happens.
  5. Here is a simple example of the Listener class
    printJob.addPrintJobListener(new PDFPrintJobListener());
    
    private class PDFPrintJobListener implements PrintJobListener {
    public void printDataTransferCompleted(PrintJobEvent printJobEvent) {
    System.out.println("printDataTransferCompleted="+printJobEvent.toString());
    }
    
    public void printJobCompleted(PrintJobEvent printJobEvent) {
    System.out.println("printJobCompleted="+printJobEvent.toString());
    }
    
    public void printJobFailed(PrintJobEvent printJobEvent) {
    System.out.println("printJobEvent="+printJobEvent.toString());
    }
    
    public void printJobCanceled(PrintJobEvent printJobEvent) {
    System.out.println("printJobFailed="+printJobEvent.toString());
    }
    
    public void printJobNoMoreEvents(PrintJobEvent printJobEvent) {
    System.out.println("printJobNoMoreEvents="+printJobEvent.toString());
    }
    
    public void printJobRequiresAttention(PrintJobEvent printJobEvent) {
    System.out.println("printJobRequiresAttention="+printJobEvent.toString());
    }
    }
    

How do I print directly from a PDF?

  1. Open the PDF in your default reader, access the “Print” option via the file menu.
  2. In the print dialog, select your printer, adjust settings like number of copies, page range, orientation, papersize, and print quality.
  3. Preview the document, then click “Print” to start printing.
  4. Ensure your printer is on, connected, has enough paper and ink, and resolve any printer errors.

How do I print data from PDF?

There are many ways to do that. You can use JPedal, converting PDF to printable format and printing via  printJob.print(doc,null);



Our software libraries allow you to

Convert PDF to HTML in Java
Convert PDF Forms to HTML5 in Java
Convert PDF Documents to an image in Java
Work with PDF Documents in Java
Read and Write AVIF, HEIC, WEBP and other image formats
Mark Stephens Mark has been working with Java and PDF since 1999 and is a big NetBeans fan. He enjoys speaking at conferences. He has an MA in Medieval History and a passion for reading.

13 Replies to “How to print PDF files from Java”

  1. Dear Jpedal supports:
    Nice to know you and your product, as i read an article from your pdfblog about
    there are 3 ways to print pdf files

    1. Use a printer which directly supports PDF files and use JPS to send the data directly to it.

    All the work is done by the printer, often in hardware so this is a brilliant solution if you can precisely define the printers used but does not provide a generic solution. If you want to try this, here is some generic 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();

    fist question:
    we have an oce brand cutsheet printer , i think it can directly support pdf printing because this printer has PostScript License and PCL license, and i can use windows lpr command to send a postScript to this printer to print so is this mean this printer directly support pdf printing? if no how i can make sure my printer directly support pdf print.

    second question:
    if my printer directly support pdf printing is that mean i can use this script to print pdf?

    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();

    if yes, i write a small script to send pdf to my printer as fellows:

    File file=new File(“D:\\t22.pdf”);
    PrintRequestAttributeSet pras = new HashPrintRequestAttributeSet();
    DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE;
    InputStream in= new FileInputStream(file);
    PrintService printService1[]= PrintServiceLookup.lookupPrintServices(flavor, pras);
    PrintService defaultService = PrintServiceLookup.lookupDefaultPrintService();
    PrintService service = ServiceUI.printDialog(null, 200, 200,printService1, defaultService, flavor, pras);

    pras.add(new Copies(3));
    pras.add(PrintQuality.HIGH);
    pras.add(Sides.DUPLEX);
    pras.add(new JobName(“E2”,null));
    Doc doc1=new SimpleDoc(in,flavor,null);
    pj.print(doc1, pras);
    in.close();

    i can send the pdf to the printer and print out , but the PrintRequestAttribute seems not work, i set 3 copies but just print 1 copy and i set duplex but always simplex but the printer can get the JobName “E2”, so i don’t know why, what’s maybe the reason?

    third question:
    as said from your blog “Use a printer which directly supports PDF files and use JPS to send the data directly to it. All the work is done by the printer” say “all work” , what work is done by the printer?
    ————————————————
    4 question:
    i installed the oce printer driver to send files, but in oce printer driver all print job are need give a mediaName for example “t3” , and in the printer there are 4 trays,and for example the first tray are assigned mediaName “t1” and second tray are assigned mediaName “t2”
    the thrid tray are assigned mediaName “t3” the fourth tray is assigned mediaName “t4” , so if i send a file with printer driver and give mediaName “t3”, the job will print with tray 3, as i found “javax.print.attribute.standard.MediaName” can this class
    meet this requirement?

    hope you can give me some help. it would be better if you can reply to my email address

    Best Regards
    Eric

    1. Dear mark Stephens:
      First thanks your reply.
      from your reply said i need check with printer manufacturer right?
      And is it means that even thougth i do the DocAttribute , printJobAttribute, and printRequestAttribute settings like the copies , mediaName , mediaSize , all these methods maybe not valid for some brand printer drivers right?
      Thanks
      Eric

  2. Hello whenever I run this code this is the error that I get:

    Exception in thread “main” java.lang.Error: Unresolved compilation problems:
    Doc cannot be resolved to a type
    SimpleDoc cannot be resolved to a type
    DocPrintJob cannot be resolved to a type
    printService cannot be resolved
    HashPrintRequestAttributeSet cannot be resolved to a type

    at printable.Main.main(Main.java:16)

    Now I can only assume that this is because I am missing some of the code. What seems to be the problem?

  3. Hi,

    I have problem. Angular JS based UI, hits a SOA layer to retrieve static PDF files. Need to print the PDF. I have used java.print.PrintService to print but it’s not opening the printer popup as it’s deployed in a unix box with no printer configured. I am facing challenges in implementing the print function which pops up a printer dialog configured in the machine where the web application is invoked. Thanks in advance.

  4. Hi,

    I have tried this code to print pdf using java API. It is working fine in windows machine but not giving output on Linux machine.
    PrintService[] ps = PrintServiceLookup.lookupPrintServices(null, null);//deleted patts and flavor
    if (ps.length == 0) {
    throw new IllegalStateException(“No Printer found”);
    }
    PrintService myService = null;
    for (PrintService printService : ps) {
    if (printService.getName().equals(printer)) {
    myService = printService;
    break;
    }
    }
    if (myService == null) {
    throw new IllegalStateException(“Printer not found”);
    }

    FileInputStream fis = new FileInputStream(pdfFile);
    if(fis==null){
    status=”false”;
    return status;
    }
    Doc pdfDoc = new SimpleDoc(fis, DocFlavor.INPUT_STREAM.AUTOSENSE, null);
    DocPrintJob printJob = myService.createPrintJob();
    printJob.print(pdfDoc, new HashPrintRequestAttributeSet());
    fis.close();
    status = “true”;
    }
    return status;

    please reply

  5. Hi, i work on a project in wich i need an application that manages printing on windows (like in a library or cybercafe the client click on print and the document goes to the admin PC and the admin allows it or not to go to the printer). I have two strategies the first one is to develop an application with java (i dont know if i can interact with windows spooler (printing) using JAVA and what is the level of difficulty), the second one is to find an open source application to integrate in my project. Any ideas or suggestions are welcome, thanks

    1. As we suggest in the article you can use something like Ghostscript. Java abstracts printing to the JPS so yo would need to hack the print queue directly from Java if you want to make use of that.

  6. I am trying the 5 step tutorial. the printing tutorial mentions
    “PdfBook” but it does not exist from what I see.

    PdfBook pdfBook = new PdfBook(decodePdf, printingDevice, attributeSet);
    SimpleDoc doc = new SimpleDoc(pdfBook, DocFlavor.SERVICE_FORMATTED.PAGEABLE, null);

    Any ideas? Feel free to email me please.

Comments are closed.