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.open();
			document.add(new Paragraph("Hello World, iText"));
			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 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();
	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");

Download Source Code

Java_iText_PDF.zip (1.6 MB)



106 Comments

  • Gaurav Patel 1 April, 2009, 12:12

    Nice post..I will use this in my shopping cart for invoice generation. Is it capable of generate the pdf from html code? I mean I have html formatted document with all the tables and lists and I want same formats in pdf.

  • james 2 April, 2009, 8:48

    I am a newbie. Could you explain in detail how to add .jar files to classpath. I appreciate your help.

  • Viral Patel 2 April, 2009, 11:51

    Hi James,
    CLASSPATH is the environment variable that your JVM uses to find Jar files and load the classes. You can put the jar file in class file by either specifing its path in jvm by -classpath attribute:
    java -classpath c:\lib\ HelloWorld

    Or by setting it in CLASSPATH environment variable.

  • Pankaj Jain 13 April, 2009, 11:16

    Can we convert PDF file to DOC file?

  • Viral Patel 15 April, 2009, 14:08

    Hi Pankaj,
    iText jar provides functionality for creating PDF files only. For generating a DOC file you may want to use Apache POI.
    I am not sure if there is any library available to convert JAR file to DOC. I will update once I come across.
    Thanks.

  • bala 3 May, 2009, 21:44

    Great post and it works good for me .
    Satisfies my need and thanks for the information

  • vishal 16 May, 2009, 9:43

    I am working in android to convert file to pdf conversition can some one give me the solution fo thr cobnversition of the file to pdf conversiton in android.

  • Gerard 2 June, 2009, 22:16

    Thank you so much for this post.

    While i had found itext i was unsure how to make it print out into a local file.

    this guide helped immensly and was so simple Thanks alot :-)

  • Samir Bukkawar 1 July, 2009, 15:17

    Great post .
    I have generated Dynamic PDF file having barcode in IT using IText.
    I have one simple question regarding this.
    In web application if user (client) does not have Accrobat Reader (PDF Reader), then how can we manage this?
    Is there any idea?

    I would appreciate any information.
    Thanks in advance.

  • Viral Patel 1 July, 2009, 17:18

    Hi Samir,
    I am afraid user may not be able to see generated PDFs if she does not have any PDF viewer installed. User must install PDF viewer (Acrobat Reader for eg.) in order to view the PDFs.

  • Samir Bukkawar 3 July, 2009, 10:01

    Thanks lot Virar,

    Thanks for the information…!

    Is there any way that we can set plunging for PDF viewer (Acrobat Reader for e.g.)?
    Because my application is properly working if there is “Acrobat Reader”, but it is not working if there is “Foxit Reader”.
    I can see very a window popping up very short and disappearing again on machine having “Foxit Reader”..
    What is the problem?

    or only way is that should have “Accrobat Rader”…?

    Please reply …

    Thanks,

  • Amol Kawale 3 September, 2009, 22:19

    Excellent Tool for create pdf file.

  • Amol Kawale 3 September, 2009, 22:22

    how to set up pdf document as portrait?

  • Jetti 10 October, 2009, 14:39

    Hi,
    I am working on android application for generating the PDF files by using iText only.
    so,please any one can provide some procedures.?

  • kurt 17 November, 2009, 18:16

    Hi All,

    I’m trying this tool but don’t get far.
    I get an error on the document statement: C:\Integrator\java\jre\bin\java.exe;C:\Integrator\bin\extensions\ibs\eclipse\plugins\IBSExternalPackages\lib\itext-2.0.0.jar

    Anyone has an idee ?

    thanks,
    Kurt

  • mohand 25 November, 2009, 19:13

    Hi
    thanks for your answers;
    i use iText in order ton transform the JSP to PDF.
    I arrive ton print some data of the JSP but i can’t respect the CSS of the JSP ??
    Any one has the solution please?
    It’s urgent.
    thank you

  • Ricardo 16 December, 2009, 20:17

    Hi every one,

    i have a problem creating pdf file from base64 String with iText… and i need some help.

    With my base64 String
    Str64 = “JVBERi0xLjQKJeLjz9MKNCAw . . . Q5NQolJUVPRgo=”;

    I convert to byte[ ]:
    byte[ ] responseByteArray= com.lowagie.text.pdf.codec.Base64.decode(respostaBase64);

    and then to String:
    String ResponseDecodedFinal = new String(responseByteArray);

    but in the end, in file created (ResponseDecodedFinal ) the result is…
    %PDF-1.4
    %âãÏÓ
    4 0 obj
    <<
    /ProcSet [/PDF /ImageC /Text]
    /Font

    Any ideia how to solve this problem??

  • ARUMUGAM 22 December, 2009, 18:27

    Dear Sir,
    I am using NetBeans6.5. I have created a J2EE project. I added iText2.0.0 library. I created a servlet and copied your code in to the IDE generated code. I am getting PDF “File does not begin with %PDF-” error. Please help me.
    The servlet code for your analysis.
    /*
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    */

    import com.lowagie.text.Document;
    import com.lowagie.text.DocumentException;
    import com.lowagie.text.Paragraph;
    import com.lowagie.text.pdf.PdfWriter;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.Date;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    /**
    *
    * @author Administrator
    */
    public class ITextWritePdfFile extends HttpServlet {

    /**
    * Processes requests for both HTTP GET and POST methods.
    * @param request servlet request
    * @param response servlet response
    * @throws ServletException if a servlet-specific error occurs
    * @throws IOException if an I/O error occurs
    */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {

    PrintWriter out = response.getWriter();
    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 (FileNotFoundException e) {
    e.printStackTrace();
    } catch (DocumentException e) {
    e.printStackTrace();
    }
    finally {
    document.close();
    out.close();
    }
    }

    //
    /**
    * Handles the HTTP GET method.
    * @param request servlet request
    * @param response servlet response
    * @throws ServletException if a servlet-specific error occurs
    * @throws IOException if an I/O error occurs
    */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    processRequest(request, response);
    }

    /**
    * Handles the HTTP POST method.
    * @param request servlet request
    * @param response servlet response
    * @throws ServletException if a servlet-specific error occurs
    * @throws IOException if an I/O error occurs
    */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
    processRequest(request, response);
    }

    /**
    * Returns a short description of the servlet.
    * @return a String containing servlet description
    */
    @Override
    public String getServletInfo() {
    return “Short description”;
    }//

    }

    • Viral Patel 26 December, 2009, 1:06

      @ARUMUGAM, I can see a minor mistake in your code. In processRequest() method, you are initializing PrintWriter out = response.getWriter();. Remove that initialization code or replace it with OutputStream out = response.getOutputStream();. Also pass the out object to PdfWriter.getInstance() method: PdfWriter.getInstance(document, out);
      That will solve the error.

  • Semere 11 January, 2010, 16:28

    my source code….

    // OutputStream file = new FileOutputStream(“D:/Documents and Settings/Administrator/Desktop/liferay-portal-5.2.3/tomcat-6.0.18/webapps/file_collection/test.pdf”);

    Document document = new Document();
    PdfWriter.getInstance(document,response.getOutputStream());
    document.open();
    document.add(new Paragraph(“Name: “+request.getParameter(“nam”)));
    document.add(new Paragraph(“Sex: “+request.getParameter(“sex”)));
    document.add(new Paragraph(“Age: “+request.getParameter(“age”)));
    response.setContentType(“application/binary”);
    document.close();
    // file.close();

    i think i do all my best but it creates error…

    %PDF-1.4 %���� 2 0 obj stream x�+�r �26S�00SI�2P�5��1��  �BҸ4�sS���3�4C��* Pj�VX)�b�rLjL�HIG�����f0� endstream endobj 4 0 obj <<>>/MediaBox[0 0 595 842]>> endobj 1 0 obj endobj 3 0 obj endobj 5 0 obj endobj 6 0 obj endobj xref 0 7 0000000000 65535 f 0000000321 00000 n 0000000015 00000 n 0000000409 00000 n 0000000164 00000 n 0000000472 00000 n 0000000517 00000 n trailer <]/Root 5 0 R/Size 7/Info 6 0 R>> startxref 627 %%EOF

    please some body help me…..

  • Semere 11 January, 2010, 16:32

    and also i try to change the content type… to response.setContent(“application/pdf”); and response.setContent(“application/download”); but the same error occur…..

  • Semere 12 January, 2010, 12:23

    Viral Patel, i know u can solve this … pleas help me…

    • Viral Patel 12 January, 2010, 14:25

      @Semere: I am not sure if I know what the error is, but try putting response.setContent(“application/pdf”); as the first line.

      Document document = new Document();
      response.setContentType(“application/pdf”);
      PdfWriter.getInstance(document,response.getOutputStream());
      document.open();
      document.add(new Paragraph(“Name: “+request.getParameter(“nam”)));
      document.add(new Paragraph(“Sex: “+request.getParameter(“sex”)));
      document.add(new Paragraph(“Age: “+request.getParameter(“age”)));
      document.close();

      Not sure if this will solve your problem.

  • Semere 13 January, 2010, 12:39

    Viral .. tanks a lot for your response … my question is, how can i change jsp outputs to pdf without saving the page…. i mean by using “response.getOutputStream()”…..

    when i use the above one… it creates error..
    .
    %PDF-1.4 %���� 2 0 obj stream x�+�r �26S�00SI�2P�5��1��  �BҸ4�sS���3�4C��* Pj�VX)�b�rLjL�HIG�����f0� endstream endobj 4 0 obj <>/MediaBox[0 0 595 842]>> endobj 1 0 obj endobj 3 0 obj endobj 5 0 obj endobj 6 0 obj endobj xref 0 7 0000000000 65535 f 0000000321 00000 n 0000000015 00000 n 0000000409 00000 n 0000000164 00000 n 0000000472 00000 n 0000000517 00000 n trailer > startxref 627 %%EOF

    my source code ………………….

    Name:

    Sex: mf

    Age:

    location.href=’/file_collection/test.pdf’;

    tanks alot, brother Viral Patel for your help… i know u can solve this….

  • Semere 13 January, 2010, 12:46

    my source code…………………….
    //////////////////////////////////////

    OutputStream file = new FileOutputStream(“D:/Documents and Settings/Administrator/Desktop/liferay-portal-5.2.3/tomcat-6.0.18/webapps/file_collection/test.pdf”);

    Document document = new Document();
    PdfWriter.getInstance(document, file);
    document.open();
    document.add(new Paragraph(“Name: “+request.getParameter(“nam”)));
    document.add(new Paragraph(“Sex: “+request.getParameter(“sex”)));
    document.add(new Paragraph(“Age: “+request.getParameter(“age”)));

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

    ///////////////////////////////////

  • Semere 14 January, 2010, 22:17

    Viral Patel, tanxs brother i get the answer…..

  • aro1982 15 January, 2010, 15:20

    Can somebody help me with my problem? I create PDF using PDF Template for PDF AcroForm. I fill all fields like:

    form.setField(”field1″, “value”); (etc.).

    And everything it’s OK. But I also want to set text (in TextField) which size is greater than this TextField size. How can I dynamically resize TextField (after/before setField) to fit text? (I want to do this without changing text font size. I tried with something like Mutli-line but when there was more text to fit then font size was smaller.)

  • aro1982 15 January, 2010, 15:24

    And maybe you know how to get PdfTable with cells content from PDF (maybe from tagged PDF).

  • bpinkowski 21 January, 2010, 2:50

    I would like to use itext to generate a pdf document from an html file (using string template). I have read that this can be done but cannot find any useful examples. Any help or directions to examples would be greatly appreciated.

  • Alfred 24 January, 2010, 17:01

    Hello Semere, I have the same problem, what is the solution?
    Thanks

    My error
    %PDF-1.4
    %����
    1 0 obj
    <>stream
    x���1��� ��g
    ��������������������x0�Q�d
    endstream
    endobj
    2 0 obj

    Alfred

  • ARUMUGAM 25 January, 2010, 20:00

    Dear Sir,

    Please help me in
    How to store the dynamically servlet created pdf file in the server and then to serve client.

    Thanks and Regards.

  • Gerry 26 January, 2010, 17:39

    Hi! First I would like to say that I appreciate your work a lot! I have read and learnt a lot. But I have one problem that I can’t figure out (probably beacause I am a newbie in itext). I want to merge two pdf-files. No problem. But, I want the order to be specific when merging the two documents. In this case I would like it to be:

    page 1, doc A
    page 1, doc B
    page 2, doc A
    page 2, doc B
    etc etc

    Could you please help me? I really need the helping hand of an expert.

    BR
    /Gerry

  • Sumeet 12 February, 2010, 17:45

    hi viral
    i want to ask to viral patel is it possible to generate pie charts and bar graph using itext.
    and what are the jar files required.
    Give some example also.
    thanks……………..

  • Montek 11 March, 2010, 17:03

    Hi,

    We presently use an in-house report engine (based on Apache FOP) to generate reports from web applications.

    We are considering switching our application to use iText.

    After reading through over the internet, I understand that iText doesn’t use XSL-FO instead it uses something called iText-xml.

    We use report templates to generate reports in PDF and XLS format.

    I have few questions:

    1. Though iText is used to generate PDF reports, is it possible to generate reports in XLS (excel) format?

    2. Instead of generating reports using code, can we use template (xml files) like feature (possibly containing FO tags) to generate PDF using iText?

    Information regarding XML2PDF and templates will be helpful.

    Thanks in advance.

  • Karthik 30 March, 2010, 20:24

    Hi,
    I am looking for a code using iText to generate pdf files from an java application.
    It looks like a application form. When a user fills the details and saves it in the database, I need to generate a pdf file to print that data.
    Can you please help me regarding this issue.

    Thanks,
    Karthik.

  • prasandh 2 April, 2010, 17:15

    nice solution . can it be possible to generate pdf in new browser or window.

  • abhinav 22 April, 2010, 21:23

    Getting this error:File does not begin with “%PDF-”
    Code:

    //Please help…
    asap

  • Srividya 30 April, 2010, 9:20

    How to get the data form an editable pdf that is opened in a web browser . The data has to be collected and saved as an pdf file .

  • mj 6 May, 2010, 11:45

    I am creating a PDF document using itext.jar and showing it in a new browser window.
    Problem:
    ————–
    On the click of a button I call an action that creates the PDF document and then show it in browser window.The title of browser window is coming as the url of action called.
    I want to change the title, but not able to do it with the help of javascript….

    do anybody have idea abt it how can i change the browser properties like title at run time.??

  • Divya 17 May, 2010, 15:11

    Hello Guys,
    I have url containing PDF file and i want to show this PDF file to user on button click. Please let me know how to do this? Can anybody help me?
    Thanks.

  • Akhilesh 12 June, 2010, 11:00

    Hi Viral,

    I’m strugglimg with page numbers. Suppose that i have 5 records and the first record contain 2 pages and the rest of the records contain 1 page each. So, my requirenment is i have to reset the page numbers i.e, for the first record the page number should be 1/2 and 2/2 and the following records should have page numbers 1/1 and 1/1… and so on.

    can you help me out for this problem???

    regards,
    Akhilesh

  • Akhilesh 12 June, 2010, 11:02

    I’m using it in generating pdf in a Web Application.
    I’m using eclipse.

    Akhilesh

  • satya 16 June, 2010, 17:42

    how can i make a scanned pdf file to searchable pdf file using java or any programming language.
    please help me………..

  • Rammi 7 July, 2010, 16:33

    Hi ,i am wrking on java.In our project e are adding some utiliy related to pdf generation.Can anybody send the details regarding generation of pdf dynamically using java.Please don’t say s above. If possiable please send the code to xxxx@gmail.com.

  • Ashish 18 August, 2010, 10:15

    @Viral

    Hi, thanks for all the content. i am getting an exception by this code. i want to know where you are closing “pResponse.getOutputStream()”. because in this way it says illegal state exception and getOutputStream() is already called for this request.

    Ref: PdfWriter.getInstance(document, pResponse.getOutputStream() );

    Thanks in advance

  • misha asha 7 October, 2010, 8:00

    Hello every one…………………

    That’s a a very important subject that i think will be very useful for document generation
    using JAVA.

    If you are looking for a document generation system on Java, take a look at this [Java document generation] site. It has basic info on all the vendors. It makes for a great starting point

  • Laxman 13 October, 2010, 16:03

    Hi Viral very nice article thank you very much. can you update how to create a web service using EJB 3 and also web service client using IBM RAD 7.5

  • Vikas 20 October, 2010, 11:56

    Hello Viral
    I want to convert my HTML site into JAVA jar file or Mobile Applet, can u suggest where i can get converter or Plz help me from ur side

    ThanX
    Vikas

  • Mohammad Amir 25 October, 2010, 23:29

    I am using itext.2.0.0 and trying to print pdf report using the above code but nothing is being displayed on the browser. I am using IE8. I am not getting any exception raised. The program just quietly executes without giving any error. Can someone help me out…Thanks. My code is as follows:

    public class Form0949 extends PdfPageEventHelper {
    
    
    private static Log log = LogFactory.getLog(gov.bop.smu.report.Form0949.class.getName());
    	
    	public Form0949(){		
    	}
    	
    	public void getReport(){
    		log.debug("begin of getReport...");		
    		FacesContext context = FacesContext.getCurrentInstance();
    		HttpServletResponse response = (HttpServletResponse)context.getExternalContext().getResponse();
    	log.debug("Method getReport: response object = "+response.toString());
    	Document document = new Document();
            
            try{
            	response.setContentType("application/pdf");
            	PdfWriter.getInstance(document, response.getOutputStream());
            	document.open();
            	document.add(new Paragraph("Hello World"));
            	document.add(new Paragraph(new Date().toString()));
            
            	
            }
            catch(Exception e) {
                e.printStackTrace();	
            }
            finally{
            	document.close();
            }
            
            
    	}
    
    }
    
  • stephen 18 November, 2010, 10:34

    how to include the multiple properties in asingle cell using itext?

  • siddarth dey 22 November, 2010, 16:37

    How to create multiple tables with different columns & rows in a pdf using iText

  • nitin Patil 14 December, 2010, 12:28

    How to create PDF template that can set by java on the fly itext report

Leave a Reply

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

Note

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]