Pure Java Print PDF Open Source API

PDF became widely used file format to exchange documents. There are a quite a few open source API available to create PDF document from Java application. Almost there is no good open source API available to view and print the PDF content from Java application. Fortunately sun released a open source API to fill this gap.

It is called “PDF Renderer” API.  Since the name says renderer many of you might think that it may not be suitable for printing. But it is possible to print PDF document using this API. The code is fairly simple, you can download from the below link. You need JDK1.5 to run this code. You can enhance the code to set more printer configurations based on your need.

Resource: PrintPdf.java

Reference: https://pdf-renderer.dev.java.net/

add to del.icio.us :: Add to Blinkslist :: add to furl :: Digg it :: add to ma.gnolia :: Stumble It! :: add to simpy :: seed the vine :: :: :: TailRank :: post to facebook

47 Responses to “Pure Java Print PDF Open Source API”

  1. Vikram Says:

    Hey this is a great resource venkat. I have been looking for something that will allow only restricted printing of a document from the web without making the pdf available to freely distribute.

  2. Neo Says:

    Perfect for me. Thanks for documenting your findings!

  3. LuisQ Says:

    Thanks for your post. Very useful. It saved us a lot of work.

  4. Wagner Pequeno Says:

    Venkat,

    Using the code to print a PDF file i’ve a problem in print service: During the job a message: java.nio.BufferUnderflowException occurs and the page was blank. I’m using Windows XP and a HP LaserJet 1010 printer. Do you know anything about this problem?

    Thanks!

    Wagner Pequeno

  5. Venkat Says:

    Sorry, I haven’t faced such issue. It could be specific to your printer settings.

  6. Balazs Says:

    Hi Venkat !

    Thanks for distributing your experience.
    Do you know how I can set the chars coding of PDF to “UTF-8″ ? I have problems with some non-ascii characters.

    Regards,
    Balazs

  7. Praveen Says:

    Hi Venkat,
    Thanks for the PrintPDF , we are looking to print PDF files from AS400 box, will be appericated if you have any sample code for AS400. Also, can we configure the printPDF to print other than default printer.

    Thanks
    Praveen

  8. Venkat Says:

    If you have JRE1.5 in your AS400 box the code will run.

    Use the below method to set different printers.
    /**
    * Sets the printer service to be used for printing
    *
    * @param argPrintServiceName
    * @throws PrinterException
    */
    public void setPrintService(String argPrintServiceName) throws PrinterException {
    PrintService[] printServices = PrinterJob.lookupPrintServices();
    int i;
    for (i = 0; i < printServices.length; i++) {
    if (printServices[i].getName().equalsIgnoreCase(argPrintServiceName)) {
    printerJob.setPrintService(printServices[i]);
    break;
    }
    }
    if (i == printServices.length) {
    throw new PrinterException(“Invalid print service name: ” + argPrintServiceName);
    }
    }

  9. Jayne Says:

    Thanks for your post. It worked perfectly for me and saved me a lot of work.

  10. rags Says:

    Hi,
    We used this API and seem to have worked for most of the stuff except it doesnt support multilingual PDF. Do you know a way to resolve it?

  11. Venkat Says:

    I don’t know. You can post your questions into java.net forum.
    https://pdf-renderer.dev.java.net/servlets/ProjectMailingListList

  12. Far Says:

    Great find, I’m wondering how this can be adapted to print on a client side printer in a web application? I’m using JSF, and I’m at a loss as to how to proceed.

  13. Venkat Says:

    Do you mean from browser? You can do if you have applet code.

    btw, the better solution is generate PDF in server side and display in the browser, user can click print button in the acrobat reader.

  14. Far Says:

    Thanks for the reply, I’m currently trying for a silent print function for my web application, so I’m avoiding streaming the pdf to the browser.

    I’m reading the file from a location on a server thru the applet, but I’m getting an error: “This may not be a PDF File”

    The only changes to the code I made were:

    public PrintPdf(URL url)
    {
    try{

    PrintPdf printPDFFile = new PrintPdf
    (url.openStream(), “WEB PDF”);
    printPDFFile.print();
    }
    catch(Exception e) {
    e.printStackTrace();
    }
    }

    instead of having the main in the class.

    The file at the URL is a valid pdf. When line 74 in initialize is called,

    PDFFile pdfFile = new PDFFile(bb);

    the error occurs. I am unsure what’s causing the error as the error message is quite vague.

    I know this might not be the place, but I’ve been doing a heap of looking on my own and came back here since the origin of this little snippet is you. I would really appreciate any ideas you might have. Thanks in advance.

  15. Venkat Says:

    Try converting URL content into ByteArrayInputStream and use it inside PrintPDF.

    The below method might help you to convert:
    public static InputStream getAsByteArray(URL url) throws IOException {
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    InputStream inputStream = url.openStream();
    int length = 0;
    byte content[] = null;
    do {
    content = new byte[1024];
    length = inputStream.read(content);
    if (length > 0) {
    outputStream.write(content, 0, length);
    }
    } while (length > 0);
    return new ByteArrayInputStream(outputStream.toByteArray());
    }

  16. Jeff Says:

    Hi there,

    I have tried what you posted here and it works great. The print job size is a on the big side 1.1MB for a 3 page PDF document. Just wondering if you have any idea on how to reduce the job size?

    cheers!

  17. Jeff Says:

    Also..I am getting some strange characters at the end of the lines characters which looks like this: l”

    Any ideas how how to stop those characters from being printed?

    cheers!

  18. Gaurav Says:

    Hi Venkat,

    Thanks for the printPDF. Am trying to print a pdf but am getting below exception.

    Exception in thread “main” java.lang.SecurityException: class “com.sun.pdfview.PDFParseException”’s signer information does not match signer information of other classes in the same package
    at java.lang.ClassLoader.checkCerts(Unknown Source)
    at java.lang.ClassLoader.preDefineClass(Unknown Source)
    at java.lang.ClassLoader.defineClass(Unknown Source)
    at java.security.SecureClassLoader.defineClass(Unknown Source)
    at java.net.URLClassLoader.defineClass(Unknown Source)
    at java.net.URLClassLoader.access$100(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClassInternal(Unknown Source)
    at com.oracle.printutilities.PrintPdf.initialize(PrintPdf.java:79)
    at com.oracle.printutilities.PrintPdf.(PrintPdf.java:51)
    at com.oracle.printutilities.PrintPdf.main(PrintPdf.java:35)

  19. Logongas Says:

    Hello Venkat,
    Thanks for the code, but my PDF has some values in Fields that I can’t get to print, I mean, these fields are blank when I try to print.
    Does PDF Renderer allow render fields values?
    Thanks.
    Lorenzo

  20. dudu Says:

    Logongas, I have the same problem. I can’t print the euro symbol. It’s replaced by blank fields. Have you find a solution ?

    Thanks

  21. Logongas Says:

    Hi dudu,
    yes, using Foxit Reader.

    Sorry.

  22. Iqui Says:

    Hi Venkat, im having some problems when i try to print pdf files, some of them print fine, but some i generate with Crystal Reports print only images, and strange characters where text should be, any ideas. Thanks in Advance.

    Iqui.

  23. Venkat Says:

    Sorry, I don’t know.
    Please post your question in PDF Renderer discussion forum.
    https://pdf-renderer.dev.java.net/servlets/ProjectForumView

  24. Lammer Says:

    Hi Venkat, im having some problems when I try to print pdf files with pdf version 1.1 generated by Oracle Reports 6i. PDFRenderer does not recognize fonts used in pdf document. Adobe Reader runs well.

  25. Venkat Says:

    I have no idea about this problem. However I knew that this open source will not support on different version. You can try one of the prop root proprietary version.

  26. Wayne Says:

    Hi Venkat, I would like to download your example, PrintPdf.java, but it’s asking for username and password.

  27. Thalacinus Says:

    Dear Venkat,

    Bar code not appear correctly. How to “install” these fonts ?
    How to “install” other fonts ?

  28. gayathri Says:

    Hi Venkat,

    Thnks a lot…
    I am getting the following exception when i try to print the PDF doc
    java.runtime exception : invalid character encountered.
    Using PDF renderer is it possible to print PDF files which contain scanned images.. Please advice

  29. LD Says:

    Hi Venkat,
    PDFRenderer works greatly but one very strange problem is there. It prints the pdf in very small size than the actual pdf size. My printed page is not same as in the original pdf.
    Can you please give some hint ?
    Thank you.

  30. shymaa Says:

    when i run printPdf.java on iseries ,i got null pinter exception at line
    PrinterJob pjob = PrinterJob.getPrinterJob();

    it seems that iseries cannot locate the default printer and create a job

    does any one know the solution for this problem

    thanks in advance

  31. shymaa Says:

    when i run printPdf.java on iseries ,i got null pinter exception at line
    PrinterJob pjob = PrinterJob.getPrinterJob();

    it seems that iseries cannot locate the default printer and create a job

    does any one know the solution for this problem

    thanks in advance

  32. DanielNZ Says:

    Hi Shymaa,
    I have the same problem you having, basically calling
    PrintService [] ps = PrinterJob.lookupPrintServices()
    returns null, and hence the crash.
    I wonder if Venkat or any other guru can shed some light on how to get working on the bloody AS/400 platform!

    Daniel

  33. DanileNZ Says:

    Nothing seems to be working regarding printing PDF – even from Windows platform.
    It depends on the PDF file size and contents, I get a series of Exceptions, like:
    1- OutOfMemoryError if the document is more than 20 pages
    2- NullPointerException if the documnet contains images
    3- PDFParseException: Short stream in ASCIIHex decode

    I tried it on a one page text only document, it printed the document without exception but with some distorted letters like all the “l”s , “i”s, “f”s and “r”s .

    I don’t think it is there yet and lots need to be done. I posted a problem on their developer and issues mailing list, but it doesn’t look to be attended.

    Will have to hunt again.. back to square one.

    Daniel

  34. sagar Says:

    i am facing a strange issue using PDF Renderer with respect to font setting, the all document which get’s printed using this, the text font style are geting changed to italic even thought its not, can any one help to solve this issue

  35. lokesh Says:

    Hi ,
    i am wondering, if there is a way to print PDF files to one of available physical printers or an only printer while blocking the virtual printers to the list using java

  36. Venkat Says:

    I don’t know :-)

  37. PDF Server Software Guy Says:

    Great Post!

    So does this work like printing to pdf? You select print and choose the pdf as your server or is this an automated feature?

    Thanks,

    Jason

  38. Francis Says:

    Has anyone tried printing(or even rendering in a panel) a PDF file with a (image) signature? Mine keeps coming out with the color reversed:

    -File has black signature against white background.

    -Output is a white signature against a black box (the size of the signature image).

    Any ideas? Thanks!

  39. Rajashekar Says:

    Hi All,

    I could see many posts which says it WORKS (printing PDF through java) but its unfortunate am not able to connect to the site https://pdf-renderer.dev.java.net/ as it always shows TIMED OUT message.

    Can anybody help me in getting the open source code from any other sites? Or it will be great if anybody can mail the jar file….

    Any suggestions are much appreciated….waiting for reply

    Thanks

    Waiting for

  40. Rajashekar Says:

    Hi Venkat,

    Could you please help me in getting the PDFRenderer source zip file?

    i tried these 2 sites:

    https://pdf-renderer.dev.java.net/

    and

    http://swinglabs.java.sun.com/downloads.jsp

    but am not able to download the source files or even the binary files….

    please help me in getting the src zip file as early as possible…since i need it very badly….

    Thanks in Advance

  41. Rajashekar Says:

    Hi Venkat,

    Thanks for sharing the jar file….but i do have a problem.

    I copied the same PrintPdf.java that you have provided and i added the pdf.jar to my library and configured in PlugIn.xml file also.

    am not able to clear the errors that is being shown in the the import statements that are present in the PrintPdf.java.

    import com.sun.pdfview.PDFFile;
    import com.sun.pdfview.PDFPage;
    import com.sun.pdfview.PDFRenderer;

    The files PDFFile.java, PDFPage.java and PDFRenderer.java are not visible.
    Even the sub-packages that are present in the pdfview package like: action, colospace are visible but again the classess inside these sub-packages are also not visible, an not able to import those java files too.

    am struck as to where is the problem…..please guide me in resolving these errors…..

    looking forward for you reply at the earliest….

    Thanks in Advance….

  42. Venkat Says:

    the pdf.jar contains java classes not .class files. Hope this info helps you.

  43. Rajashekar Says:

    Wow! thanks a lot venkat…..

    That was really my bad…anyways thanks for the much needed help…

  44. Marlon Alves Says:

    Great post!!!!!!!!!!

    Thanks…

  45. Adam Says:

    I can’t get it to print correctly. Whether my in my own program or in the example program, printing portrait stuff always shrinks the page and prints it in the top left corner (its like 45% the size.) Regardless of the PDF I print (datasheets or ones I created with PDFlatex or itext) results are the same. same results on linux and XP as well.

    The code is exactly from the example program (the example program does the same thing as mentioned above.)
    Any help would be appreciated.

  46. Madhavi Says:

    Hii Venkat,

    Thanks for sharing your work..I have taken your files and tried in Java 1.5 and PDF 6..
    I m getting the following error:

    com.sun.pdfview.PDFParseException: Expected ‘xref’ at start of table
    at com.sun.pdfview.PDFFile.readTrailer(PDFFile.java:974)
    at com.sun.pdfview.PDFFile.parseFile(PDFFile.java:1175)
    at com.sun.pdfview.PDFFile.(PDFFile.java:126)
    at com.sun.pdfview.PDFFile.(PDFFile.java:102)

    Can u please help me in solving this issue?

    Thanks in advance

  47. Venkat Says:

    Sorry guys, I have no clue about this error. Try posting the issue into https://pdf-renderer.dev.java.net/ if you don’t get response there my advice is look for commercial software.

    I am planning to buy a commercial API for printing PDF because PDF spec and format will keep change expecting a open source to serve Adobe spec is not feasible.


Leave a Reply