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). This does not internally support the PDF file format. We will print PDF using Java with JPedal (JPedal is our PDF library for Java) to Convert, Print, View PDF files).
What is JPS
Java Print System is built into all versions of Java. It renders a page for printing and can plug into the existing Windows or Unix/Linux/Mac printing system. 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. It does not support all formats but does include callbacks to allow these to be implemented.
We have added PDF support for JPS to 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).
How to Print PDF in Java
Our JPedal Java PDF library implements JPS so here is the minimal code you would use to print a PDF file.
- 1. Create a DocPrintJob
- Wrap your Pageable or Printable object inside a doc, specifying which interface to use in the call
- Add a listener to track what happens.
- Call the print method
and the Java code to print PDF…
PrintService[] service = PrinterJob.lookupPrintServices(); //list of printers
printJob = service[i].createPrintJob(); //is whichever printer you use
Doc doc = new SimpleDoc(decode_pdf, DocFlavor.SERVICE_FORMATTED.PAGEABLE, null);
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());
}
}
printJob.print(doc, null);
Top comments (0)