Find » Technology » How to Create a Simple PDF Document...

How to Create a Simple PDF Document from Java Using iText

By smglo2006, published Dec 05, 2007
Published Content: 32  Total Views: 11,420  Favorited By: 0 CPs
Embed:  
Rating: 2.9 of 5
You've been using Java for a while now to create some simple, yet dynamic web pages. Your boss approaches you and starts asking if you could create a PDF file of the report you just designed. Being the every faithful programmer that you are, your reply is simple: "Sure I can". As your boss walks away though, you start to ask yourself if you really can do it and you head to the Internet to find out how. Your search of the web reveals many options, some that you have to pay for and some that you don't.

One of the simplest and cheapest utilities that I found was a package called iText. This utility allows you to create PDF documents on the fly or in batch mode. It's simple to use, yet can handle some of the most complex tasks that you will ask it to do. Even better, the price to use it: FREE!

The first step in creating a PDF from Java is to download and import the itext.jar file from www.lowagie.com/iText

into your Java project. Once iText becomes available to you in your project, the fun can begin.

The next step is to tell Java to create the initial PDF document, using the following initialization:

Document document = new Document();

Now that the document variable is initialized, its available for us to start adding information to. We need to initialize a Writer to write the information to the document. This can be accomplished with the following line of code:

PdfWriter pdfWriter = PdfWriter.getInstance(document, new FileOutputStream("test.pdf"));

For our example, we're using "test.pdf" as the file name. However, you can use any valid file name (including file path information) here and you can use a variable to pass the information here. In a production application, I pass a variable that is based on information contained in a work file that is being read.

Now that we have a pdfWriter and our document, we need to open the document in order to write to it.This is another one line statement: document.open(); This tells the code to open the document and allow us to actually write to it.

Now let's write a simple, one line paragraph to the document. document.add(new Paragraph("Hello, this is an example of how to use iText."));

How to Create a Simple PDF Document from Java Using iText

Screen shot of a simple iText project to create a one line PDF file.

Credit: smglo2006

Copyright: smglo2006

Comments
Type in Your Comments Below - (1000 characters left)
Your name:

Submit your own content on this or any topic. Get started »
Most Commented On