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)

Get our Articles via Email. Enter your email address.

You may also like...

135 Comments

  1. Gaurav Patel says:

    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.

  2. james says:

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

  3. Viral Patel says:

    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.

  4. Pankaj Jain says:

    Can we convert PDF file to DOC file?

  5. Viral Patel says:

    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.

  6. bala says:

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

  7. vishal says:

    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.

  8. Gerard says:

    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 :-)

  9. Samir Bukkawar says:

    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.

  10. Viral Patel says:

    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.

  11. Samir Bukkawar says:

    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,

  12. Amol Kawale says:

    Excellent Tool for create pdf file.

  13. Amol Kawale says:

    how to set up pdf document as portrait?

  14. Jetti says:

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

  15. kurt says:

    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

  16. mohand says:

    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

  17. Ricardo says:

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

  18. ARUMUGAM says:

    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 says:

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

  19. Semere says:

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

  20. Semere says:

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

  21. Semere says:

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

    • Viral Patel says:

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

  22. Semere says:

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

  23. Semere says:

    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();

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

  24. Semere says:

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

  25. aro1982 says:

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

  26. aro1982 says:

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

  27. bpinkowski says:

    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.

  28. Alfred says:

    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

  29. ARUMUGAM says:

    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.

  30. Gerry says:

    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

  31. Sumeet says:

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

  32. Montek says:

    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.

  33. Karthik says:

    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.

  34. prasandh says:

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

  35. abhinav says:

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

    //Please help…
    asap

  36. Srividya says:

    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 .

  37. mj says:

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

  38. Divya says:

    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.

  39. Akhilesh says:

    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

  40. Akhilesh says:

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

    Akhilesh

  41. satya says:

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

  42. Ashish says:

    @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

  43. misha asha says:

    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

  44. Laxman says:

    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

  45. Vikas says:

    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

  46. Mohammad Amir says:

    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();
            }
            
            
    	}
    
    }
    
  47. stephen says:

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

  48. siddarth dey says:

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

  49. nitin Patil says:

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

  50. praveen says:

    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 says:

      @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 says:

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

  51. Rahul says:

    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

  52. bonthala says:

    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 says:

      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
      thanks
      asif aftab

  53. Arianne says:

    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.

  54. Arulselvi says:

    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…

  55. selvi says:

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

  56. selvi says:

    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

  57. Indra Patel says:

    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

  58. Sheetal More says:

    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 says:

      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

  59. noob says:

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

  60. adityo says:

    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?

  61. didsGitle says:

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

  62. AJ says:

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

  63. Andy says:

    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

  64. ankush says:

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

  65. Khoyendra says:

    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 says:

      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.

  66. Ajay says:

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

  67. Himanshu says:

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

  68. pranesh says:

    good

  69. vignesh says:

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

  70. vasu says:

    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

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

  72. purna says:

    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?

  73. parthiban says:

    hi,

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

  74. Ashish says:

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

  75. Kislay says:

    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

  76. Tushar says:

    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.

  77. Madhuri Kankurte says:

    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 !

  78. hiren patel says:

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

  79. Vishwajeet says:

    please tell me how generate pdf in new window using iText

  80. Vishwajeet says:

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

  81. Vishwajeet says:

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

  82. Naveen says:

    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

  83. venkat says:

    nice example

  84. prabha says:

    Hi,

    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?

  85. Priyanka S says:

    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 ?

  86. Mukesh Makhijani says:

    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);

  87. Rohit More says:

    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 says:

      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.

  88. sam says:

    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

  89. sam says:

    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

  90. 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 [email protected] !

  91. Mahesh Jaiswal says:

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

  92. Mahesh Jaiswal says:

    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.

  93. Mahendra says:

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

  94. Nitish says:

    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?

  95. Prakash says:

    Thanks bro for sharing useful data your blogs

  96. Abhijit Chowdhury says:

    Hi virul,

    Thanks for PDF generation code.
    But I need display the PDF contents with jsp code without using any PDF reader.
    Can I display a PDF Image generated by itext.jar on html div.

    Please provide some reply for this requirement. Very urgent.

    Thank u.

  97. Amit says:

    Hi Viral,
    In my project i am using JFree and Jasper Reports. The problem is, Jfree supports itext 2.0 and Jasper required itext 2.1.7. How can i manage both jars should execute respect to report type.

  98. Om says:

    @Viral, I need your help man. While generating PDF from HTML, I am facing an issue. It’s like there are some bulletpoints in the HTML at different-different locations. Generated HTML is like below:
    In regard to a "zero lot line" situation, extreme care should be exercised in connection with:

    <ul>
      <li> the right of legal access to and from the property. 
      <li>the possible existence of encroachments of the sides of the buildings or 
        structures upon the common areas.</li>
    </ul>
    <p>In regard to a "zero lot line" situation, extreme care should be 
      exercised in connection with:</p>
    <ul>
      <li> the right of legal access to and from the property. 
      <li>the possible existence of encroachments of the sides of the buildings or 
        structures upon the common areas.</li>
    </ul>
    

    If you see the tag is two times. So I tried using JSOUP and did a doc.select(“ul li”), and I am able to generate the Bullets in PDF. But it happens only one time. I mean if the bullets are at multiple locations in the HTML and I do a document.add(list). It doesn’t generate the complete PDF.
    Please lemme know if I’m missing anything

  99. Chetan says:

    Hi Viral,

    Thanks for sharing this article it is very helpful but I have a question, I have already downloaded itext-1.1.4.jar, i have updated the classpath… still i get
    package com.lowagie.txt does not exist error.
    please help me.
    kindly let me know direct link for downloading iText-5.2.1.jar.

    Thanks in advance..

  100. balu says:

    Hi ,

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

  101. vamsi says:

    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();
    
    	}
    }
    
  102. vamsi says:

    nice tutorial thanq very much @viralpatel

  103. Michael says:

    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

  104. Pedrola says:

    It was really useful for me, Thank you so much

    • Yogesh says:

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

  105. Yogesh says:

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

  106. zerox says:

    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();

  107. Meeravali says:

    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

  108. Bhadresh Shha says:

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

  109. Hamza says:

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

  110. kram says:

    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)

  111. SoRoom says:

    Thanks a lot

  112. Ram says:

    Hi Viral,
    Thanks a lot for itext. It simplifies my great issues

    Thanks Buddy…

  113. Pankaj Jain says:

    Is there a way to customize or change the message that gets displayed in the document open Password dialog box while trying to open a password protected PDF file.

    Default message – “filename.pdf is protected. please enter a Document Open Password.”

  114. anil says:

    i want to use this code in struts 1.2
    can u help me…..

  115. Abhishek says:

    when i copy past this code and add jar file and when run this code i got this exception.
    please help me to solve this.

    javax.servlet.ServletException: Error instantiating servlet class CreatePdf
    java.lang.NoClassDefFoundError: com/itextpdf/text/Element

  116. karthik says:

    how to make bullet style in pdf using java?

    • karthik says:

      Take your text

  117. Mahendra says:

    Can I generate Hindi in pdf

    Please help

  118. yasaswini says:

    i have to get values from db and display it in pdf how?

  119. Snt says:

    Good job

  120. Snt says:

    thanks a lot.. it helped to solve my problem….

  121. Moses says:

    Hello, how would I create a pdf report by using iText on server and display it using the client in jdbc?

  122. Sadique says:

    Hello Sir,

    I am having the output from database tables, and want to call them webpage where i need option to generate report either in html format or pdf.
    How can i do that, Kindly help.

    Regards,

Leave a Reply

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