PDF Generation in Java using iText JAR
- By Kiran Hegde on April 1, 2009
Generating 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:
- Serve PDF to a browser
- Generate dynamic documents from XML files or databases
- Use PDF’s many interactive features
- Add bookmarks, page numbers, watermarks, etc.
- Split, concatenate, and manipulate PDF pages
- Automate filling out of PDF forms
- 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
Get our Articles via Email. Enter your email address.
i am a newbie, i have updated the classpath… still i get
package com.lowagie.txt does not exist error
please help me proceed
@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.
use eclipse add external jar file and try this it will come.
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
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.
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.
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…
plz anyone help me with source code and procedure to generate PDF file in JSP page using JSP with netbeans… its urgent plz plz..
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; iAnd 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
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
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
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
no Sheetal More no it is not possible
dont try to do R&D
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?
Cool, it’s I like, to be I come in handy
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………..
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
this code is running perfectly but i will require the formating the text and show the image also.Please help me.it urgent
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.
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.
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..!!!
i use above code in jsp page,but browser show encode result,please give me some solution that problem
good
Any body send me code of pdf file create on runtime in dynamic web page development.
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
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.
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?
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….
Can u suggest me pdf library for android…………???????
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
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.
Hi Tushar, Have a look at this tutorial: Password Protect PDF files using iText. I think this is exactly what you looking for.
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 !
hello , pls provide full code. i already tried this one, but i cant get result, thanks in advance . hiren patel
please tell me how generate pdf in new window using iText
i want—>when i click button(export pdf ) in browser window then pop-up window will come for open,save file
open the pdf in new tab or new browser window, not the same tab where the application is running,please reply urgent
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
nice example
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?
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 ?
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);