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-5.2.1.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).

package net.viralpatel.pdf;

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

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

public class GeneratePDF {

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

			Document document = new Document();
			PdfWriter.getInstance(document, file);

			document.add(new Paragraph("Hello World, iText"));
			document.add(new Paragraph(new Date().toString()));


		} catch (Exception e) {


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 Struts Action class 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.itextpdf.text.Document;
import com.itextpdf.text.Paragraph;
import com.itextpdf.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();
		PdfWriter.getInstance(document, response.getOutputStream());
		document.add(new Paragraph("Hello Kiran"));
		document.add(new Paragraph(new Date().toString()));
	}catch(Exception e){
	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.addCreator("iText library");
document.addTitle("Hello World PDF");

Download Source Code

Java_iText_PDF.zip (1.6 MB)


  • praveen 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 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 22 December, 2011, 19:49

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

  • Rahul 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 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.

    • asif aftab 21 November, 2013, 0:03

      I also got same error then I just remove package code from my code and compile the program and that error was gone. Try it may be helpful for you
      asif aftab

  • Arianne 14 February, 2011, 20:18

    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 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 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 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..

    < % 
    Document document = new Document();
    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    PdfWriter.getInstance(document, buffer);
    PdfPTable table = new PdfPTable(2);
    DataOutput dataOutput = new DataOutputStream(response.getOutputStream());
    byte[] bytes = buffer.toByteArray();
    for(int i = 0; i 

    And i got the following error.

    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 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 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 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 9 May, 2011, 16:55

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

  • adityo 13 May, 2011, 9:50

    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 28 May, 2011, 9:58

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

  • AJ 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 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 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 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 9 November, 2011, 17:03

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

      Your image wil be show then.

  • Ajay 24 November, 2011, 16:14


    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 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 9 December, 2011, 17:16


  • vignesh 13 January, 2012, 19:19

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

  • vasu 23 January, 2012, 16:02


    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

  • Garry Vleminckx 18 February, 2012, 19:20

    Please note that iText is not FREE and never has been. Also the ling for the download in this article is referring to the website where a community version can be downloaded of iText 5.x but this is a AGPL license, iText 2.x was released as a LGPL license, iText has never been FREE !
    contact iText Software if you have questions about these licenses.

  • purna 20 February, 2012, 15:10

    HI, we are using google app engine sdk platform, google app engine doesn’t proved outPutStream(), to read a file, to prevent this, what would be best way?

  • parthiban 24 February, 2012, 10:53


    I was pretty well in generating PDF. But now i have a scenario of generating PDF dynamically by the values coming as input. so i used two documents for generating. Ikept the 1st document as static and whenever my condition changes, i ll close my 1st document and i opened a new document and populate it with remaining rows… everything is proper.. no exceptions, no errors.. i triple checked whether both the documents are closed.. But then when i am trying to open the documents created, its saying that, this PDF is alredy used by an application(my eclipse) and i am not able to open it…
    Please suggest any solution for this problem.. This makes me to itch my head….

  • Ashish 18 April, 2012, 19:18

    Can u suggest me pdf library for android…………???????

  • Kislay 24 April, 2012, 10:28

    Can you help me with some example in which a html page containing images is being converted into a pdf file……?????
    Or just an idea regarding that will be helpful….
    Thanks in advance

  • Tushar 2 June, 2012, 16:51

    Hi ,Viral Thanks for this example ,I am looking for program which set password to pdf means creating secure pdf can you post related to creating secure pdf.

  • Madhuri Kankurte 28 August, 2012, 11:56

    Hi Viral..
    Thanks for this tutorial..
    However.. my application needs to write the html code onto a pdf file.
    With the shared jars by you..the html code is directly written as source code.
    Where we need the replica of html page onto pdf.
    Please insist here !

  • hiren patel 29 October, 2012, 17:40

    hello , pls provide full code. i already tried this one, but i cant get result, thanks in advance . hiren patel

  • Vishwajeet 26 December, 2012, 9:21

    please tell me how generate pdf in new window using iText

  • Vishwajeet 26 December, 2012, 9:31

    i want—>when i click button(export pdf ) in browser window then pop-up window will come for open,save file

  • Vishwajeet 26 December, 2012, 10:05

    open the pdf in new tab or new browser window, not the same tab where the application is running,please reply urgent

  • Naveen 22 January, 2013, 2:52

    Error loading Agent Class: JavaAgent
    java.lang.ClassNotFoundException: JavaAgent
    at lotus.domino.AgentLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:609)
    at lotus.domino.AgentLoader.runAgent(Unknown Source)
    I got this error msg, plz help me

  • venkat 2 February, 2013, 17:27

    nice example

  • prabha 5 March, 2013, 12:19


    Thanks for this great tutoroal but i got http-404 error that requested resource my project name(report1) is not available…why iam getting this…and iam running this project in eclipse with itextpdf-5.2.1jar file included and i created dynamic web project and taken a class and paste this code…is it write way?

  • Priyanka S 12 March, 2013, 11:45

    Hi Viral.. Thanks for this great code !!! my requirement is to standarise the header and footer in all PDF. can you please suggest what need to be added for that ?

  • Mukesh Makhijani 15 May, 2013, 6:48

    How to resolve the below error Please let me know .

    C:\Documents and Settings\MakhijM\Desktop\extract_work>javac ReadPDFFile.java
    ReadPDFFile.java:10: error: package com.itextpdf.text.pdf does not exist
    import com.itextpdf.text.pdf.PdfReader;
    ReadPDFFile.java:11: error: package com.itextpdf.text.pdf.parser does not exist
    import com.itextpdf.text.pdf.parser.PdfTextExtractor;
    ReadPDFFile.java:16: error: cannot find symbol
    private static PdfReader reader;
    symbol: class PdfReader
    location: class ReadPDFFile
    ReadPDFFile.java:42: error: cannot find symbol
    reader = new PdfReader(fineName);

  • Rohit More 3 June, 2013, 12:25

    Hello Sir,
    I am tried your code for “English Data”. Its working great.
    but when i used to try for “Hindi or Marathi Lang”. Pdf is generated but didnt get desired output.
    O/p. text in Pdf : “??????? ???? ???”

    • Chitra 29 July, 2013, 13:03

      Hello Rohit, m also facing the same problem of retreiving Hindi data from databse in iText. Did u got any solution,if yes please share.

  • sam 15 June, 2013, 12:09

    Hi Viral.. Thanks for sharing this code…
    I have one issue can you please suggest me?? I have one button on jsp page which opens pdf in new window, In servlet i am using PdfReader to read and PdfStamper to modify that pdf (PdfStamper stamper = new PdfStamper(reader, outputStream); now my problem is when i click on another button its reloads the pdf in another window.
    so my question is any suggestion to modify pdf without reloading always in new window
    i request you to suggest me ASAP,
    Thanks in advance

  • sam 15 June, 2013, 14:46

    Hi Viral..
    Thanks for sharing this code…
    I have one issue can you please suggest me?? I have one button on jsp page which opens pdf in new window, In servlet i am using PdfReader to read and PdfStamper to modify that pdf (PdfStamper stamper = new PdfStamper(reader, outputStream); now my problem is when i click on another button its reloads the pdf in another window.
    so my question is any suggestion to modify pdf without reloading always in new window
    please i request you to suggest me ASAP,
    Thanks in advance

  • Felice Gaddis 9 August, 2013, 0:48

    Many thanks a whole lot for publishing this write-up! I have been hunting all over the interwebs right up until I finally discovered ‘PDF Generation in Java using iText JAR | Generate PDF from Java applications dynamically | Free Java-PDF Library’ ! If any individual has added info on this specific matter, you should hit me up on Ritzel189@hotmail.com !

  • Mahesh Jaiswal 18 September, 2013, 17:13

    how can we add html tags into an document class
    and how can we set dynamic data into document class

  • Mahesh Jaiswal 18 September, 2013, 17:50

    Sir, the code that you have given to generate pdf works, but the problem is that when I have downloaded that documents, documents have been saved but it is saved in do file format.

  • Mahendra 12 November, 2013, 9:25

    Send me code using mvc strcture in java for Eclipse..

  • Nitish 23 January, 2014, 13:35

    nice example..thnks.
    But I also want to open generated pdf onButton Click in android.How to open pdf without showing any intent means default pdf viewers(like polaris viewr,Adobe reader etc.) which are installed on device.
    I want to open pdf directly. How to do this?

  • Prakash 2 April, 2014, 10:36

    Thanks bro for sharing useful data your blogs

Leave a Reply

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


To post source code in comment, use [code language] [/code] tag, for example:

  • [code java] Java source code here [/code]
  • [code html] HTML here [/code]