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 our JPedal PDF library which add PDF support print support to JPS.
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.
- 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);
The JPedal PDF library allows you to solve these problems in Java
Viewer viewer = new Viewer();
viewer.setupViewer();
viewer.executeCommand(ViewerCommands.OPENFILE, "pdfFile.pdf");
//Convenience static method (see class for additional options)
ExtractClippedImages.writeAllClippedImagesToDir("inputFileOrDirectory", "outputDir", "outputImageFormat", new String[] {"imageHeightAsFloat", "subDirectoryForHeight"});
//Convenience static method (see class for additional options)
ExtractTextAsWordList.writeAllWordlistsToDir("inputFileOrDirectory", "outputDir", -1);
//Convenience static method (see class for additional options)
ArrayList resultsForPages = FindTextInRectangle.findTextOnAllPages("/path/to/file.pdf", "textToFind");
PrintPdfPages print = new PrintPdfPages("C:/pdfs/mypdf.pdf");
if (print.openPDFFile()) {
print.printAllPages("Printer Name");
}
//Convenience static method (see class for additional options)
ExtractClippedImages.writeAllClippedImagesToDir("inputFileOrDirectory", "outputDir", "outputImageFormat", new String[] {"imageHeightAsFloat", "subDirectoryForHeight"});
Why do developers choose JPedal over alternatives?
- Actively developed commercial library with full support and no third party dependencies.
- Simple licensing options and source code access for OEM users.
- Process PDF files up to 3x faster than alternative Java PDF libraries.
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
You will need to check with the manufacturer what support they actually have.
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
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?
They are all standard Java classes so you should just need to add imports (I use fix imports in Netbeans)
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.
You can print silently from Java without a dialog.
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
Do you have any local printers on the Linux machine?
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
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.
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.
I would recommend using the full solution – http://javadoc.idrsolutions.com/org/jpedal/examples/printing/PrintPdfPages.html