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)



123 Comments

  • balu 21 May, 2014, 19:12

    Hi ,

    Nice Article, I am new to JAVA. Can please explain how to run this example in tomcat … very very urgent….

  • vamsi 15 June, 2014, 23:05

    you can write the above example in servlet also.

    package com.vamsi;
    
    import java.io.IOException;
    import java.util.Date;
    
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import com.itextpdf.text.Document;
    import com.itextpdf.text.Paragraph;
    import com.itextpdf.text.pdf.PdfWriter;
    
    public class PdfServlet extends HttpServlet 
    {
    	private static final long serialVersionUID = 1L;
        public PdfServlet() 
        {
            super();
        }
    
    	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException 
    	{
    		Document document= new Document();
    		try
    		{
    			response.setContentType("application/pdf");
    			PdfWriter.getInstance(document, response.getOutputStream());
    			document.open();
    			document.add(new Paragraph("Hello vamsi"));
    			document.add(new Paragraph(new Date().toString()));
    		}
    		catch(Exception e)
    		{
    			System.out.println(e);
    		}
    		document.close();
    
    	}
    }
    
  • vamsi 15 June, 2014, 23:07

    nice tutorial thanq very much @viralpatel

  • Michael 24 July, 2014, 15:16

    Great article. I am wondering what code is required to embed ttf font using itext for android. I have been told this is possible?

    Thanks

  • Pedrola 30 July, 2014, 15:54

    It was really useful for me, Thank you so much

    • Yogesh 8 August, 2014, 9:46

      Please provide sample code of ur application.
      JSP+Controller+Service

  • Yogesh 8 August, 2014, 9:45

    Hi,
    Could you please provide the code for spring mvc application.
    It has ajax call with RequestBody

  • zerox 21 August, 2014, 3:56

    I have a question, in my windows pc i can generate a pdf with itext, i am working with jsp pages without servlets. But when i upload the new code to the linux server (redhat) i got problems, i think itext.jar must be in a specific folder of linux
    In webINF/libs of my projects i have itext.jar

    The error code throws tomcat is:

    org.apache.jasper.JasperException: No se puede compilar la clase para JSP:

    Ha tenido lugar un error en la línea: 1.245 en el archivo jsp: /GenerarPedido.jsp
    Document cannot be resolved to a type
    1242:
    1243:
    1244: response.setContentType(“application/pdf”);
    1245: Document documento = new Document();
    1246:
    1247: try{
    1248:

    Ha tenido lugar un error en la línea: 1.245 en el archivo jsp: /GenerarPedido.jsp
    Document cannot be resolved to a type
    1242:
    1243:
    1244: response.setContentType(“application/pdf”);
    1245: Document documento = new Document();
    1246:
    1247: try{
    1248:

    Ha tenido lugar un error en la línea: 1.249 en el archivo jsp: /GenerarPedido.jsp
    PdfWriter cannot be resolved
    1246:
    1247: try{
    1248:
    1249: PdfWriter.getInstance(documento, response.getOutputStream());
    1250:
    1251: documento.open();

  • Meeravali 1 September, 2014, 15:51

    Please tell me how should i configure the struts.xml file… and more over execute class returns string ryt?? but in your code its like ActionForward, i am new to the struts and java please give explain me

  • Bhadresh Shha 24 September, 2014, 16:17

    How to put hindi text properly in pdf file using itext java api

  • Hamza 29 September, 2014, 16:02

    what if I want to print output for a jsp file. For Example, I have view.jsp which imports two css files and 3 js files. It also connected to db which shows db results. I just want to pass location/path of this view.jsp(/html/view.jsp) to generate output of this file… Can anybody Help!!!!

  • kram 1 October, 2014, 21:04

    why when i try to copy paste this code i follow everything but when i run it says this??

    java.io.FileNotFoundException: c:\test.pdf (The system cannot find the path specified)

  • SoRoom 11 November, 2014, 15:31

    Thanks a lot

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]

Current ye@r *