Friday, November 9, 2007

Creating PDF Documents Dynamically in J2EE, Java Applications

In today's enterprise applications their is a big requirement for dynamic generation of PDF documents. These applications range from telecom companies generating phone bills, airlines producing e-tickets, banks generating customer statements for e-mail delivery to readers, book sellers selling books in pdf format.

What is PDF:
The Portable Document Format (PDF) is the file format created by Adobe Systems in 1993 for document exchange. PDF is used for representing two-dimensional documents in a device-independent and display resolution-independent fixed-layout document format. Each PDF file encapsulates a complete description of a 2-D document (and, with Acrobat 3-D, embedded 3-D documents) that includes the text, fonts, images, and 2-D vector graphics that compose the document.

Why PDF:
PDF is an open standard, unlike Microsoft Word, supported by all operating systems, ie; as long as you have an adobe reader you can read a pdf file on any system like Linux, Mac, Solaris, Windows. On virus front, it’s very hard that a PDF file will have some virus. It is is now being prepared for submission as an ISO standard.

Dynamic PDF Generation in Enterprise Application Development :
As mentioned above, in digital age everything is digitized so that end user can access it from anywhere, anytime. As a result new enterprise applications are generating lot of data in pdf formant which can be used by end user.
In Enterprise (Java or J2EE, JEE) application development generating pdf documents on the fly (dynamically) has become a trivial thing, courtesy of lot of third party tools, APIs available. The list of these tools/API's is endless. In this article, we will use the iText Java library to generate PDF documents by merging GIF files. I'll go through an example to show how this is done.

iText :
iText is an open-source Java library that provides API to generate PDF files on the fly. It also supports the generation of HTML, RTF, and XML documents, in addition to generating PDFs. It's available for free under a multiple license: MPL and LGPL.

iText API :

The com.lowagie.text.Document is the main class for PDF document generation. This is the first class to be instantiated. Once the document is created, we would require a writer to write into it. The com.lowagie.text.pdf.PdfWriter is a PDF writer. Other classes which are often used:

  • com.lowagie.text.Paragraph - represents an indented paragraph.
  • com.lowagie.text.Chapter - represents a chapter in the PDF document. It is created using a Paragraph as title and an int as chapter number.
  • com.lowagie.text.Font - contains all specifications of a font, such as family of font, size, style, and color. Various fonts are declared as static constants in this class.
  • com.lowagie.text.List - represents a list, which, in turn, contains a number of ListItems.
  • com.lowagie.text.Table - represents a table that contains cells, ordered in a matrix.

Example of converting multiple GIF files into PDF :

Pre-requisites :
Download iText and include itext-version.jar into your application or yr classpath.

Code Snippet :
The following code snippet demonstrates how to convert an array (collection) of gif files into a single pdf,

FileOutputStream fos = null;

try {

fos = new FileOutputStream (new File(pDestinationFolder + File.separator + pTargetFileNamePrefix + ".pdf"));

/* Create a document which is the container for all the elements of a PDF document.*/
Document doc = new Document();

/* Line -1 */
PdfWriter writer = PdfWriter.getInstance(doc, fos);;

for (File aFile : gifFiles) {

Image image = Image.getInstance(aFile.getAbsolutePath());

/* Line -2 */
image.scaleToFit(doc.getPageSize().getWidth(), doc.getPageSize().getHeight());

/* Line -3 */

catch (Exception ex) {
finally {

if (fos != null) {
try {
catch (Exception ex) {

Code Demystified :
  • Line - 1 is important to create an instance of PdfWriter that associates a document object with the output stream. For our code snippet, we choose com.lowagie.text.pdf.PdfWriter. Other writers are HtmlWriter, RtfWriter, XmlWriter, and several others for obvious reasons.
  • Line - 2 is very useful methods that will scale the current image to fit the width and height specified. Gif images can vary in sizes and this allows the method to scale down to the default size of the PDF page.
  • Line-3 is to align the image so that it is located at the center of the page.

Other opensource libraries for generating pdf documents are :
  • FOP
  • Gnujpdf
  • JFreeReport
  • JPedal
  • jPod
  • PDF Box
  • PDFjet
  • PJX


maxblacks said...

I have used both iText and FOP in past - and I personally think FOP is much better than iText.


BL said...

I have used both an umbrella and a parasol in the past - and I personally think an umbrella is much better than a parasol.

That is: when it rains. When the sun shines I like a parasol better.

My point: people saying one thing is better over another without saying anything about the context should either clarify or remain silent.

Can FOP add a digital signature to a PDF? It can't! Can FOP encrypt a PDF? It can't! Does FOP support OCG? It doesn't!
Is iText good at converting XML to PDF? Not really. Does iText support FO? Of course not!
Now you tell me: which of both is the better product? They're different. That's all.

Abava said...

See also AcroForm taglib here

Patrick said...


you might also try out Flying Saucer, which takes XHTML/CSS 2.1 (or XML/CSS 2.1) and can output to different formats, including PDF, images, and Swing panels. For PDF output, Flying Saucer relies on the iText library; it just lets you write documents in XHTML or XML and get away from working with the iText library directly. See


Surya Suravarapu said...

iText has an excellent API. Although your end goal is to create a PDF -- FOP and iText take two different approaches. Hence at some level you may not want to compare both of them.

I'd prefer to go with iText for following reasons:
1. For PDF with large number of pages, stream based is always faster than a transformation based approach.

2. Even if you lose some amount of flexibility when compared with template based approach -- if you use SAX events (and probably using something like Digester) you're still not losing out too much. There are tons of examples in Lowagie's iText book for creating pdf from XML.

3. Project's wise FOP is progressing very slowly. There doesn't seem to be much activity going on there. For years, it hasn't yet reached a release version 1.0.

4. There are excellent resources on the web (lots of forums) and an excellent book by Bruno Lowagie for iText. Any question you may have they are already answered in one of those places.

5. iText can manipulate an existing PDF quite nicely, like stamping, merging multiple files, etc.

uiyui said...

Joy in warcraft leveling living comes wow lvl from having wow lvl fine emotions,wow power level trusting them,power leveling giving them power leveling the freedom of wrath of the lich king power leveling a bird in the open.wlk power leveling Joy in living can age of conan gold never be assumed as a pose,or put on from guildwars gold the outside as a mask. People who have this joy don not need maple story mesos to talk about it; they radiate it. wow gold They just live out their joy and let wow power leveling it splash its sunlight and glow into other lives as naturally as bird sings.

xxmy said...

Weekends to peopleig2tmean that they can have a two-day wowgold4europe good rest. For example, people gameusdcan go out to enjoy themselves or get meinwowgoldtogether with relatives and friends to talk with each storeingameother or watch interesting video tapes with the speebiewhole family.
Everyone spends agamegoldweekends in his ownmmoflyway. Within two days,some people can relax themselves by listening to music, reading novels,or watchingogeworld films. Others perhaps are more active by playing basketball,wimming ormmorpgvipdancing. Different people have different gamesavorrelaxations.
I often spend weekends withoggsalemy family or my friends. Sometimes my parents take me on a visit to their old friends. Sometimesgamersell I go to the library to study or borrow some books tommovirtexgain much knowledge. I also go to see various exhibition to broadenrpg tradermy vision. An excursion to seashore or mountain resorts is my favorite way of spending weekends. Weekends are always enjoyable for me.
igxe swagvaultoforu wowgold-usaignmax wowgoldlivebrogame thsaleGoldRockUbrogameswagvaultgoldsoonoforuigxethsale

dreaz said...

I am grateful to you for this great content.aöf thanks radyo dinle cool hikaye very nice sskonlycinsellik very nice ehliyet turhoq home free kadın last go korku jomax med olsaoy hikaye lesto go müzik dinle free only film izle love aşk 09sas mp3 indir

dfous said...

Bon marche de Dofus Kamas.achat de dofus.le prix moins cher.nous vendons dofus,or de Wakfu. 24/7 appui-en-ligne et livraison rapide.Wakfu Kamas
china: chinaserving

milf said...

dessicant air dryer pediatric asthma asthma specialist

carpet cleaning dallas tx carpet cleaners dallas carpet cleaning dallas

beach vacations your beach vacations
bob hairstyle

bob haircuts bob layered pob hairstyle

bobbed classic bob Care for Curly Hair

Tips for Curly Hair curly hair 12r 22.5 best price

tires truck bus tires 12r 22.5 washington new house

new house Houston new house san Antonio new house ventura

sealy air beds portable portables air beds

antique doorknobs drying desiccant

air drying desiccantlipitor allergic reactionsApple prodam iphone prahaflorida headache clinic

cheap beach vacationsnight vision binoculars bargains

milf said...

new houston house houston house tx stains removal dye

stains removal clothes stains removal teeth whitening

teeth whiteningbright teeth jennifer grey nose

jennifer nose jobs calebrities nose jobs Women with Big Noses

Women hairstyles Big Nose Women, hairstylesdvd player troubleshootingtroubleshooting with the dvd player

lixiang said...

I like your blog, it's very good!
By the way, do you like spyder down jackets, I think they are very fashionable and chic, especially the spyder ski jackets, I love them so much. In my spare time, I also like playing tennis rackets, it can keep healthy, what do you like to do?
kids north face jackets
polo vest
polo jacket
abercrombie fitch mens shirts
polo jackets for men
polo jackets for women
burberry shirts for men
polo hoodies for women
columbia jackets women
polo sweatshirts for women
north face jackets on sale
polo shirts for women
polo shirts wholesale
spyder jackets
ralph lauren polo shirt
polo pants for men
abercrombie fitch shirt
wholesale abercrombie fitch shirts
polo vests
polo jackets
polo hoodies for men
burberry shirts for women
burberry shirts on sale
polo shirts for men
north face jackets cheap
north face jackets for women
north face jackets for men
polo sweatshirts for men
columbia jackets for men
columbia jackets discount
spyder jackets for men
discount spyder jackets
cheap spyder jackets
spyder jacket
spyder jackets for women
tennis rackets
cheap tennis rackets
discount tennis rackets
tennis rackets on sale
prince tennis racquets
head tennis racquets
wilson tennis racquets
babolat tennis racquets

lady said...

I like the side of the article, and very like your blog, to write well and hope to continue their efforts, we can see more of your articles. ed hardy clothes. After reading this article has strong feelings, the future will be ed hardy womens longsleeve.ed hardy longsleeve
ed hardy hoodies
ed hardy jeans
ed hardy
ed hardy clothing
ed hardy t-shirts
cheap ed hardy clothing
ed hardy shirts
wholesale ed hardy clothing
ed hardy outerwear
ed hardy mens outerwear
ed hardy womens outerwear
ed hardy clothes
ed hardy boots
ed hardy outerwear
ed hardy hoodies
ed hardy Jeans
ed hardy hoodies
ed hardy jackets
ed hardy womens jackets
ed hardy mens jackets
ed hardy bags
ed hardy trousers
ed hardy shoes
ed hardy longsleeve
ed hardy mens longsleeve
ed hardy womens longsleeve
ed hardy jackets
ed hardy suits
ed hardy clothing
ed hardy shoes
ed hardy jeans
ed hardy boots
ed hardy mens sweater
ed hardy womens cotton
ed hardy womens boots
ed hardy
ed hardy womens clothing

nike said...

Nike shoes
puma shoes
Cheap nike shoes
NIKE’s headquartered in Beaverton, Oregon.Nike may be one of the youngest of the major brands, but it is the dominant brand around the world.In 1963-1964 when University of Portland track coach, Bill Bowerman, and Phil Knight, a mid-distance runner joined forces to import and provide low-cost, high tech running shoes from Japan in order to provide alternatives to the German-dominated athletic shoe market.
Discount nike shoes
Wholesale nike shoes
Nike shox r4
Operating under the name Blue Ribbon Sports, Bowerman and Knight began to sell the Japanese Onitsuke Tiger (Nike SB) running shoes. Jeff Johnson, a former rival of Knight, joins the company in 1965 as their first full-time salesperson and sells shoes from the back of his van at local and regional track meets until opening Blue Ribbon Sports’ first retail outlet at 3107 Pico Blvd, Santa Monica California.
nike shox shoes
nike air max
nike running shoes
The Superstar is one of the first designs the Adidas manufactured.The tongue is leather on the outside and cloth of the inside and is thick enough to feel padded, but thin enough to not feel like an obstruction. The heel of the shoe holds up well the curve of the front is great for any kind of feet.
cheap puma shoes
discount puma shoes
nike air max tn
Therefore, Adidas is a collection of trust and respect. Product and marketing initiatives at Adidas primarily focus on five global priorities: football, running, training, basketball and Adidas Originals sneakers. Adidas sports the recognizable logo of three slanted parallel bars of ascending height.
puma mens shoes
puma running shoes
wholesale puma shoes
Everybody like beauty, which is quite commen, especailly womens. Welcom to our store which is focused on sellingghd hair straighteners mk4and hair straightners. For women, especially the young girls, this ghd iv styler hair straightener is the best choice. ghd hair straightners is famouse for the pretty outlook and the top quality. The price of this cheap ghd hair straighteners is acceptable and rational. Ed Hardy Jeans, Ed Hardy Hoodies ed hardy shirts ed hardy clothes ed hardy clothing
ed hardy trousers

liuhua said...

After read your blog, I think you are a wonderful person, for your blog is the best one I have ever seen. If you do not mind, I would like to know do you like fashion? Have you ever heard of polo shirts, which are very chic, especially the polo t shirts, I love them very much. I also like playing tennis rackets, it can keep healthy, what do you like to do? I consider it as my great pleasure to introduce myself as the outlet of polo t shirts women
polo t shirts on sale
and the warmly welcomed
polo t shirts for women
Now. I'd like to introduce our masterpieces, such as
polo shirts on sale
polo shirts men
men's polo shirt
men polo shirt
mens polo shirts
mens polo shirt
besides we also sell
cheap polo shirts
discount polo shirts
men's polo shirts
women's polo shirts
Which are popular with fashinable people. We are also the outlet of
cheap tennis racket
discount tennis racket
in this sporty season, we recommend
prince tennis racquet
head tennis rackets
wilson tennis racket
babolat tennis racquet
There more new products in our store online, we are expecting you to come. We can say that you must find your satisfied things in our store. said...

Dofus Kamas|Prix Moins Cher Dofus Kamas|Kamas par allopass|Dofus kamas audiotel|Dofus kamas par telephone sur

Meilleur prix dofus kamas stock de dofus kamas

Prix moins cher dofus kamas vente dofus kamas sur dofus kamas vente

Nicole C said...

buy viagra
viagra online
generic viagra

kimberly said...

When I bought my computer and I didn´t know how to use java graphics, so I decided looking for information in a webside and I found an useful information that helped me a lot.. Now I am interested in to do the best investment and I found a webside very useful and interesting called costa rica investment opportunities , I think it´s a very wonderful site.

King Bayern Munich said...

We supply many styles of sofas,such as living-room-sofa, Modern leather sofa . soft sofa. Lounge-sofa .
e supply all kinds of stone product,such as china tombstones, Modern-stone-sculpture, paving-stone Glazed-Vitrified-Tiles

rscredits said...

If a job is worth doing it is worth doing well.What runescape gold you share here just prove this saying, i like your thought here, rs gold which is special and informative.

This topic is pretty good and the writer's views are buy runescape gold unique and not so hard to understand.I like it very much, and by the cheap rs gold way I want to share some interesting and very useful websites to! Iam sure you can find out funny things there.

Learn Chinese language on hanbridgemandarin said...

The best place to learn Chinese online is in China. However, we understand that it isn't always possible to move here to study Chinese language. The next best thing is to study with our experienced teachers in a virtual classroom. Online students enjoy the same excellent way of Mandarin Online Course and custom designed courseware that we provide for our face to face clients.

Data İstanbul said...

Orjinal Lipo Magnet Resmi Satış Sitesi Online Sipariş Sayfası için en doğru ve en sağlıklı adres