PDF Generation in Java using iText JAR

java-pdf-logoGenerating PDF files in today’s enterprise applications is quite common. Doing this with Java is not an easy task as Java does not gives default api’s to handle PDF files. No worries, iText jar is for you.

iText is a free Java-PDF library that allows you to generate PDF files on the fly (dynamically). iText is an ideal library for developers looking to enhance web- and other applications with dynamic PDF document generation and/or manipulation. iText is not an end-user tool. Typically you won’t use it on your Desktop as you would use Acrobat or any other PDF application. Rather, you’ll build iText into your own applications so that you can automate the PDF creation and manipulation process.

iText (Java-PDF Library) can be used to:

  1. Serve PDF to a browser
  2. Generate dynamic documents from XML files or databases
  3. Use PDF’s many interactive features
  4. Add bookmarks, page numbers, watermarks, etc.
  5. Split, concatenate, and manipulate PDF pages
  6. Automate filling out of PDF forms
  7. Add digital signatures to a PDF file

Technical Requirements to use iText

You should have JDK 1.4 or later to integrate iText PDF generation in your application.

Getting iText

Download iText jar from its home page http://www.lowagie.com/iText/download.html

iText core: iText-2.1.5.jar

Generate simple PDF in Java using free Java-PDF library

It is very easy to generate a simple PDF file in Java using iText. All you have to do is to put itext.jar in your class path and paste following code in GeneratePDF.java class and compile and execute it. After you execute this, a file Test.pdf will be created in C: drive (If you are using Linux, you may want to have /usr/test.pdf as path).

import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.Date;

import com.lowagie.text.Document;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfWriter;

public class GeneratePDF {

    public static void main(String[] args) {
        try {
            OutputStream file = new FileOutputStream(new File("C:\\Test.pdf"));

            Document document = new Document();
            PdfWriter.getInstance(document, file);
            document.open();
            document.add(new Paragraph("Hello Kiran"));
            document.add(new Paragraph(new Date().toString()));

            document.close();
            file.close();

        } catch (Exception e) {

            e.printStackTrace();
        }
    }
}

In above code snippet we have created Document object which represents our PDF document. Also, by supplying OutputStream object to getInstance() method sends the output to OutputStream. Thus in our case we have created a output file and sent output to it.

Generate PDF as Output Stream in HTTP request

Sometime we may want to add the PDF generation functionality to a web application, where user on clicking some link or button is served with PDF output. Hence the PDF should be generated on fly and sent to client browser.

Consider following simple action class for Struts which uses this mechanism to generate a dummy PDF and sent the output to browser.

package net.viralpatel.struts.helloworld.action;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.lowagie.text.Document;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfWriter;

/**
 * @author KiranRavi_Hegde
 *
 */
public class PdfHelloWorldAction extends Action{

	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

	Document document = new Document();
	try{
		response.setContentType("application/pdf");
		PdfWriter.getInstance(document, response.getOutputStream());
		document.open();
		document.add(new Paragraph("Hello Kiran"));
		document.add(new Paragraph(new Date().toString()));
	}catch(Exception e){
		e.printStackTrace();
	}
	document.close();
	return null;

	}
}

If you notice in above code, we have passed response.getOutputStream() object to getInstance() method. Thus the output generated by iText will be sent directly to the response. Also don’t forget to set the content type of the response to application/pdf.

Setting attributes of PDF using free Java-PDF library

While you generate a PDF, you may want to set its different attribute like: author name, title, file description etc. iText jar can help you to set different attributes of a PDF file. Document object provide different methods to add various attributes to a PDF file.

document.addAuthor("Kiran Hegde");
document.addCreationDate();
document.addCreator("iText library");
document.addTitle("Hello World PDF");


78 Comments

  • praveen wrote on 24 December, 2010, 20:20

    i am a newbie, i have updated the classpath… still i get
    package com.lowagie.txt does not exist error
    please help me proceed

    • Viral Patel wrote on 24 December, 2010, 21:58

      @Praveen – Check if you have included the required itext jar file in your classpath and do you have the right version of it.. which contains that package.

    • Anitha wrote on 22 December, 2011, 19:49

      use eclipse add external jar file and try this it will come.

  • Rahul wrote on 10 January, 2011, 22:31

    This is a great example for generating pdf with struts. if anyone is having example of pdf generation with spring then it would be more helpful

  • bonthala wrote on 12 January, 2011, 15:11

    this is the error i am getting

    pls help me

    D:\Java Notes>java GeneratePDF
    Exception in thread “main” java.lang.NoClassDefFoundError: GeneratePDF
    Caused by: java.lang.ClassNotFoundException: GeneratePDF
    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)
    Could not find the main class: GeneratePDF. Program will exit.

  • Arianne wrote on 14 February, 2011, 20:18

    Hi,
    A very nice article for the starters.
    I have one question though. Does iText provide/support any kind of styling sheet.
    What I mean is like, in Apache FOP, the data is represented in the XML and the formatting is recorded in the XSL and then we need to pass the XML and XSL to the FOP engine which in turn converts the data in XML using the formatting psecified in the XSL to create a PDF.
    Does iText support something like this or we have to program the whole formatting in the Java code itself, meaning specifying the table/cell(its dimensions etc.), paragraph(its font, color etc.)?
    Any comment is appreciated.

  • Arulselvi wrote on 26 February, 2011, 13:17

    hello sir!!! ‘m doing new to JSP. But its rule that i should do project in JSP oly. Its urgent to execute PDF file in my JSP page with net beans 6.0. Plz guide me the proceudre with source and necessary things to implement the PDF generation. It will be very useful for me. send details to my mail sir.. My Id is ma……….@gmail.com. Its urgent sir so can do reply soon…

  • selvi wrote on 27 February, 2011, 7:17

    plz anyone help me with source code and procedure to generate PDF file in JSP page using JSP with netbeans… its urgent plz plz..

  • selvi wrote on 27 February, 2011, 8:31

    i am using net beans to execute JSP page. i added itext-5.0.6.jar in apache tomcat library to execute PDF file. i added following code in new JSP page..

    < %
    response.setContentType("application/pdf");
    Document document = new Document();
    try{
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    PdfWriter.getInstance(document, buffer);
    document.open();
    
    PdfPTable table = new PdfPTable(2);
    table.addCell("1");
    table.addCell("2");
    table.addCell("3");
    table.addCell("4");
    table.addCell("5");
    table.addCell("6");
    
    document.add(table);
    document.close();
    
    DataOutput dataOutput = new DataOutputStream(response.getOutputStream());
    byte[] bytes = buffer.toByteArray();
    response.setContentLength(bytes.length);
    for(int i = 0; i
    

    And i got the following error.

    compile-jsps:
    Compiling 1 source file to C:\Documents and Settings\Administrator\My Documents\NetBeansProjects\WebApplication1\build\generated\classes
    C:\Documents and Settings\Administrator\My Documents\NetBeansProjects\WebApplication1\build\generated\src\org\apache\jsp\index_jsp.java:6: package java.servlet does not exist
    import java.servlet.*;
    C:\Documents and Settings\Administrator\My Documents\NetBeansProjects\WebApplication1\build\generated\src\org\apache\jsp\index_jsp.java:10: package com.lowagie.text.pdf does not exist
    import com.lowagie.text.pdf.*;
    C:\Documents and Settings\Administrator\My Documents\NetBeansProjects\WebApplication1\build\generated\src\org\apache\jsp\index_jsp.java:11: package com.lowagie.text does not exist
    import com.lowagie.text.*;
    C:\Documents and Settings\Administrator\My Documents\NetBeansProjects\WebApplication1\build\generated\src\org\apache\jsp\index_jsp.java:75: cannot find symbol
    symbol : class Document
    location: class org.apache.jsp.index_jsp
    Document document = new Document();
    ^
    C:\Documents and Settings\Administrator\My Documents\NetBeansProjects\WebApplication1\build\generated\src\org\apache\jsp\index_jsp.java:82: cannot find symbol
    symbol : class PdfPTable
    location: class org.apache.jsp.index_jsp
    PdfPTable table = new PdfPTable(2);
    ^
    C:\Documents and Settings\Administrator\My Documents\NetBeansProjects\WebApplication1\build\generated\src\org\apache\jsp\index_jsp.java:102: cannot find symbol
    symbol : class DocumentException
    location: class org.apache.jsp.index_jsp
    }catch(DocumentException e){
    ^
    9 errors
    C:\Documents and Settings\Administrator\My Documents\NetBeansProjects\WebApplication1\nbproject\build-impl.xml:409: The following error occurred while executing this line:
    C:\Documents and Settings\Administrator\My Documents\NetBeansProjects\WebApplication1\nbproject\build-impl.xml:167: Compile failed; see the compiler error output for details.
    BUILD FAILED (total time: 0 seconds)

    Please anyone help me out... need the details ve soon. cz i need to submit to heigher offficials.

    pls anyone help me soon..
    thank you

  • Indra Patel wrote on 31 March, 2011, 11:23

    I want to generate pdf file from java. the pdf file is created successfully. but the problem is that
    i am creating that pdf file with gujarati font(indian) type. so the the meaning of the word is changes. and it is created with another meaning of gujarati word. i am using itext for creating pdf file and the java platform. i had also try ireport tool for the same condition but it is gives the same problem. so pls guide or give me suggestion.

    thanks in advance

  • Sheetal More wrote on 21 April, 2011, 16:56

    Hey hi…i tried that code but i want to create pdf file in android application. do you hav code for that if yes plz send me urgently…..becoz its urgent…
    Thank you in anticipation

    • noob wrote on 17 May, 2011, 10:30

      yes adityo
      u can
      u jst have to give new target window
      if u nt gave thn it will be in curent tab only
      for more go w3school

  • noob wrote on 9 May, 2011, 16:55

    no Sheetal More no it is not possible
    dont try to do R&D

  • adityo wrote on 13 May, 2011, 9:50

    Hi.
    i generate the pdf in java and success to show it on browser using ByteArrayOutputStream
    my question is, can it appear in the different tab of browser instead of in my current tab?

  • didsGitle wrote on 28 May, 2011, 9:58

    Cool, it’s I like, to be I come in handy

  • AJ wrote on 2 June, 2011, 16:27

    Hi All,

    I tried the above code for “Generate simple PDF in Java using free Java-PDF library”;
    I have downloaded itext-5.1.0 and added in ma jar files but its still giving me error at “The import com.lowagie cannot be resolved” and as solution it is asking me for “create ‘Document’ in package ‘com.lowagie.text’ “…
    Please provide the solution asap… I need it urgently….
    Thanks in advance………..

  • Andy wrote on 17 August, 2011, 13:59

    AJ – if you are using the most recent version of the iText jar then the base package have been renamed from ‘lowagie’ to ‘itextpdf’

    i.e. change your imports like so:

    import com.itextpdf.text.Document;

    Cheers, Andy

  • ankush wrote on 5 November, 2011, 16:00

    this code is running perfectly but i will require the formating the text and show the image also.Please help me.it urgent

  • Khoyendra wrote on 5 November, 2011, 16:52

    I want to add an image in PDF.
    I tried to add image by Image class and also tried by File class too but its not supporting.
    Is it possible to add Image in PDF by iText jar.

    • ankush wrote on 9 November, 2011, 17:03

      import this class
      com.lowagie.text.Image;
      and get the instance of image by :
      com.lowagie.text.Image image = com.lowagie.text.Image.getInstance(“imagePath”);
      document.add(image);

      Your image wil be show then.

  • Ajay wrote on 24 November, 2011, 16:14

    Hi

    i have created pdf document using iText API, Its a bill with logo and images. now i wand a option which give me option to print this doc in black and white or color print. How can i do..!!!

  • Himanshu wrote on 24 November, 2011, 18:16

    i use above code in jsp page,but browser show encode result,please give me some solution that problem

  • pranesh wrote on 9 December, 2011, 17:16

    good

  • vignesh wrote on 13 January, 2012, 19:19

    Any body send me code of pdf file create on runtime in dynamic web page development.

  • vasu wrote on 23 January, 2012, 16:02

    Hi,

    I have developed applet that takes input pdf and generates output-signed pdf( accessing from e-token)

    but i want to develop
    1) a web based application , there we have print option in form . if the user clicks on print button it should generate pdf with user’s signature (accessing from local system )
    2) i have seen lic payment : if the user click on print receipt –> that will generate with LIC-guys signature —> tell me how it can be implemented

Leave a Reply

Your email address will not be published. Required fields are marked *

*

Copyright © 2012 ViralPatel.net. All rights reserved.