How To Create A Basic Itext PDF Document
How To Create A Basic Itext PDF Document
In the more technical part of this article I show you how to add text, links, images and generated
graphics to your PDF document. So the end result will hopefully be that you get a good grasp of the
iText API and will be able to start thinking about your future projects of generating PDFs as a part of
your web service.
Although I will try to make my code as clear as poossible you would probably help your self greatly
by knowing at least a little bit about Java.
3. iText library - http://itextpdf.com/download.php (click on the "Download iText" when you get
there)
The most basic reason though is to produce documents that would look the same on all computers
that can open a PDF document, which is not possible even today if you're using HTML. Also iText is
very fast, has an unprecedented free support, (that some say is even better than paid support) with
very active mailing list.
And in general the creation of iText is in my opinion an epic story in itself which deserves a separate
reading session. Luckily Bruno Lowagie, the creator of iText, has been very active with creation,
support and marketing of his great tool, so you'll be able to find a lot of information ranging from his
biography, interviews, funny support related answers and of course much more.
Bruno Lowagie is one of those rare people that can be a open source pogrammer,
entrepreneur, marketer and all the while remain true to himself. I'm greatly
inspired by his story.
2. Add a Title
3. Add a Subtitle
8. Helper Functions
1 Set Up a Document
Calling setUpDocument(Document doc) from createPdf() method
The first six lines add meta data to the PDF document which can be seen from the File > Properties
from inside the Acrobat Reader. The last three lines are related to the size and margins of the
document. It is worth noting that the A4 standard of sheet size is equivalent to 210 millimeters by
297 millimeters which translates to about 605 by 855 points. This information will be important later
on in this application and is generally good to know if you often word with PDF documents.
2 Add a Title
Calling addText( titleS, document, TITLE_FONT, 2 ) from createPdf() method
Here is a pretty simple function that adds a string of text to a document. The first line creates a
paragraph using a string and a previously defined TITLE_FONT object. The second line calls a
helper function that will add two new lines to the title object. And finally third line will add the title
object to a doc object.
3 Add a Subtitle
Calling addText( titleS, document, TITLE_FONT, 2 ) from createPdf() method
A very similar scenario to the step above with the exception of the font object. By passing a different
font object I changed the appearance of the subtitle string.
3 Add a Subtitle Code Snippet
1 Paragraph paragraph = new Paragraph( text, font );
2 addEmptyLine( paragraph, newLines );
3 doc.add( paragraph );
Again the code reuse in action shows that we only change parameters to the same function. Again
the only thing that changes is the font.
In this function we are faced with a slightly different situation. We are essentially adding a text that is
hyperlinked to a URL. First I create an instance of Chunk object using its constructor. Then the
Chunk c is assigned an action on line 2 (this is where the url is "built into" the text), and gets a
decoration attribute added to it on line 3. And finally the Chunk c is added to the Document doc. The
setUnderline takes two parameters of type float: line width and line y position.
I will take a closer look at addTextAtXY() in the last step titled Helper Functions, as for right now the
function does what the name suggests, it adds a string of text at the specified absolute location
inside a document. addImageAtXY() has couple of extra wrinkles to make the image fit in nicely with
the rest of the PDF document. iText PDF Library allows to scale and manipulate an image in
different ways, which is very handy. On line 1 I am creating an Image instance called img, then I
resize the image to 150 by 150 pixels or points (Note that I know the dimensions of the imported
image before hand so I knew this would look ok, but if your image is not a square it might look
malformed). Then I position the image on line 4 (Note that in iText the coordinate system's [0,0]
coordinate is at the lower left corner of the page and, in case of A4 sized document, [605,855] is at
the upper right corner!). I create an annotation on line 5 and on line 6 is where I add a link to an
image by setting an annotation. Line 7 is where image is added to the document.
Again we'll take a closer at addTextAtXY in the next step, as for the addPieChart() this function is
shamelessly simple. Basic idea is to use arcs to create equally sized pie segments.
First you'll see that I plan to update this function so it does all the things I've outlined in the TODO
list.
Then on line 9 I set the width of line to be 3.2 points, right after on line 10 I set the color of the line to
white. Line 12 is where the fill color is defined to a bright green. Then on line 13 there is a hint I've
left for myself, which reads like this: lower left x, lower left y, upper right x, upper right y, starting
angle in degrees, the extent of the arc segment in degrees. With that knowledge it is easier to
understand line 14: we're drawing an arc bounded by the rectangle (I've made it a square) with lower
left coordinates at 200,100 and upper right coordinates at 400,300 and that begins at angle 0 and
extends for 120 degrees. Next line, 15, I'm drawing a line from where the arc method stopped
drawing to the center of the future pie chart. At line 16, a method closePathFillStroke does two
things at once: a line is drawn from the center of the pie chart to the beginning of the arc and then
the pie piece is filled with predefined (line 12) color.
The rest of this function is just a repetition of lines 12 to 16. It most definitely not a way to create a
pie, but for the purposes of understanding how iText draws simple shapes it is simpler to grasp.
On line 1 the Basefont object is created. Line 2, signaling a beginning of text generatoin on the
current canvas (PdfContentByte cb). Line 3, setting the fill color, which sets the text color using of
the predefined constants. Line 4, setting the font (font name [it is possible to use a font that you've
downloaded to your system], encoding -> http://en.wikipedia.org/wiki/Windows-1252, and if its
embedded or not, which means that if you use a font you've downloaded from somewhere iText can
embed it in a PDF document; than the font looks the same on other machines even if they don't have
it installed) and its size. Line 5 is where the absolute position of the text is set. Line 6 makes the text
visible on the canvas, and line 7 indicates the end of text operations on canvas.
Line 1 is the start of a for loop which runs for as many times as specified by the howMany
parameter. Line 2, adding an empty Paragraph to a Paragraph par.