Getting Started With IText PDF API For Java
Getting Started With IText PDF API For Java
To use IText PDF API for Java you must first download the IText JAR file from the IText
website, and include it on your application class path.
Here is a simple code example that generates a very simple PDF document using IText:
import
import
import
import
com.itextpdf.text.Document;
com.itextpdf.text.DocumentException;
com.itextpdf.text.Paragraph;
com.itextpdf.text.pdf.PdfWriter;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
/**
*/
public class HelloWorldExample {
public static void main(String[] args) {
Document document = new Document();
try {
PdfWriter.getInstance(document,
new FileOutputStream("HelloWorld.pdf"));
document.open();
document.add(new Paragraph("A Hello World PDF document."));
document.close(); // no need to close PDFwriter?
} catch (DocumentException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
3. Third, the document is opened by calling document.open(). Now you can add content to
the Document instance.
4. Fourth, content (a Paragraph instance) is added to the Document instance.
5. Fifth, the Document instance is closed, by calling document.close(). It is important to
close the document, to flush all content in the document to the PDFWriter.
That's it.
tutorials.jenkov.com/java-itext/getting-started.html
Java IText: Document
Notice how no PDFWriter is created in this example. If you want to flush the generated
document to an OutputStream (file, network etc.), you must use a PDFWriter. There is an
example of how to use a PDFWriter, in the Getting Started text.
The com.itextpdf.text.Chunk class in IText represents the smallest possible "chunk" of text.
A Chunk can contain as little as a single character, up to several sentences.
Here is a simple code example:
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
public class DocumentExample {
public static void main(String[] args) {
Document document = new Document();
try {
PdfWriter.getInstance(document,
new FileOutputStream("Chunk.pdf"));
document.open();
document.add(new Chunk("This
document.add(new Chunk("This
document.add(new Chunk("This
document.add(new Chunk("This
document.add(new Chunk("This
document.add(new Chunk("This
document.close();
is
is
is
is
is
is
} catch (DocumentException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
sentence
sentence
sentence
sentence
sentence
sentence
1.
2.
3.
4.
5.
6.
"));
"));
"));
"));
"));
"));
The com.itextpdf.text.Phrase class in IText represents a "phrase" of text. The Phrase class
knows how to add spacing between lines.
Here is a simple code example:
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
public class DocumentExample {
public static void main(String[] args) {
Document document = new Document();
try {
PdfWriter.getInstance(document,
new FileOutputStream("Phrase.pdf"));
document.open();
document.add(new
document.add(new
document.add(new
document.add(new
document.add(new
document.add(new
Phrase("This
Phrase("This
Phrase("This
Phrase("This
Phrase("This
Phrase("This
is
is
is
is
is
is
sentence
sentence
sentence
sentence
sentence
sentence
1.
2.
3.
4.
5.
6.
"));
"));
"));
"));
"));
"));
document.close();
} catch (DocumentException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
Line Spacing
Phrase objects knows how to add line spacing if the added phrase exceeds the right edge of the
document. It does not, however, add extra space between paragraphs. For this, you need to use a
Paragraph object.
Line spacing is measured in user units. There are 72 units per inch. The default spacing is 1.5
times the font height. You can change the line spacing by passing spacing as a parameter to the
Phrase constructor, like this:
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
public class DocumentExample {
public static void main(String[] args) {
Document document = new Document();
try {
PdfWriter.getInstance(document,
new FileOutputStream("Phrase2.pdf"));
document.open();
Chunk chunk = new Chunk("This is a sentence ");
Phrase phrase = new Phrase(50);
phrase.add(chunk);
phrase.add(chunk);
phrase.add(chunk);
phrase.add(chunk);
phrase.add(chunk);
phrase.add(chunk);
document.add(phrase);
document.close();
} catch (DocumentException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
Below is a screenshot of what the generated document looks like. Notice the extra line spacing
between the two lines.
Line Spacing
Paragraph objects knows how to add line spacing if the added text exceeds the right edge of the
document. Line spacing is measured in user units. There are 72 units per inch. The default
spacing is 1.5 times the font height. You can change the line spacing by passing spacing as a
parameter to the Paragraph constructor, like this:
Paragraph paragraph = new Paragraph(50);
Alignment
You can set the alignment of the paragraph using the setAlignment() method. This sets what
side of the page the text is aligned to. Here is an example:
paragraph.setAlignment(Element.ALIGN_LEFT);
paragraph.setAlignment(Element.ALIGN_CENTER);
paragraph.setAlignment(Element.ALIGN_RIGHT);
Indentation
You can set the left and right indentation of the paragraph. This moves the paragraph content
further away from the edges of the page. Here is the code to do that:
paragraph.setIndentationLeft(50);
paragraph.setIndentationRight(50);
document.close();
} catch (DocumentException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
You can specify fonts for most text objects (Chunk, Phrase, Paragraph etc.) in IText. Actually,
you can do a lot with fonts in IText. Too much to cover here, so I'll just cover the basics. Get the
book "IText in Action" to get the full story on fonts.
To use a font you must first create the font. Then you pass it to the text object in it's constructor.
Here is a simple code example:
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
public class FontExample {
public static void main(String[] args) {
You can add tables to a PDF document using the com.itextpdf.text.PdfPTable class in IText.
Tables are some of the more complex objects in IText, so this text is a bit larger than the rest of
the texts in this tutorial. Here is a list of the topics covered:
1. Creating a Table
2. Table Width
3. Spacing Before and After Table
4. Column Widths
5. Column Span
6. Cell Text Mode and Composite Mode
7. Default Cell Setting in Text Mode
8. Cell Alignment
9. Cell Indentation
10.Cell Leading
11.Cell Padding
12.Cell Borders and Colors
13.Cell Rotation
14.Tables and Images
15.Nested Tables
Creating a Table
When instantiating a PdfTable you must tell how many columns the table should have. You pass
the number of columns as a parameter to the PdfPTable constructor.
To add cells to the table you call the addCell() method, passing PdfPCell instances, or other
IText objects like Paragraph etc. Keep in mind though, that there is a difference in behaviour
depending on what object you add. See the Cell Text Mode and Composite Mode section for
more info.
Here is a simple code example:
import
import
import
import
com.itextpdf.text.Document;
com.itextpdf.text.Paragraph;
com.itextpdf.text.pdf.PdfPCell;
com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.FileOutputStream;
public class TableExample {
public static void main(String[] args) {
Document document = new Document();
try {
PdfWriter.getInstance(document,
new FileOutputStream("HelloWorld-Table.pdf"));
document.open();
PdfPTable table = new PdfPTable(3); // 3 columns.
PdfPCell cell1 = new PdfPCell(new Paragraph("Cell 1"));
PdfPCell cell2 = new PdfPCell(new Paragraph("Cell 2"));
PdfPCell cell3 = new PdfPCell(new Paragraph("Cell 3"));
table.addCell(cell1);
table.addCell(cell2);
table.addCell(cell3);
document.add(table);
document.close();
} catch(Exception e){
}
}
An IText Table
Table Width
You can set the table width using the setWidthPercentage() metod. This sets the width of the
table as a percentage of the width of the page. The default width is 80%. Here is a code example:
table.setWidthPercentage(100);
Column Widths
You can set the column widths using the setWidths() method, like this:
float[] columnWidths = {2f, 1f, 1f};
table.setWidths(columnWidths);
The column widths in the float array are
Column Span
If you need a cell to span multiple columns you can do so using the setColspan() method, like
this:
cell.setColspan(2);
Content added to the PdfCell's constructor is considered text mode content. Content added via
the PdfCell.addElement() method is considered composite mode content. Here are some
examples:
PdfCell textModeCell = new PdfCell(new Paragraph("Text Mode"));
PdfCell compositeModeCell = new PdfCell();
compositeModeCell.addElement(new Paragraph("Composite Mode"));
table.addCell(new Paragraph("Text Mode"));
Cell Alignment
You can set the cell alignment using the setHorizontalAlignment() and
setVerticalAlignment(), like this:
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
cell.setVerticalAlignment(Element.ALIGN_TOP);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setVerticalAlignment(Element.ALIGN_BOTTOM);
In composite mode you can also set the alignment of each Paragraph
Cell Indentation
You can set the indentation of cell content.
The method setIndent() sets the indentation of the first paragraph in the cell.
The method setFollowingIndent() sets the indentation of the following paragraphs in the cell.
The method setRightIndent() sets the right indentation of the cell content.
Cell Leading
You can set the leading (line spacing) of elements in a cell.
If the cell is in composite mode, just set the leading on the element added, e.g. set the leading of
a Paragraph before adding it to the cell.
In text mode you can set a leading value that is used on the entire cell content. To so do, use the
setLeading() method. This method takes two parameters. A fixed leading and a leading
calculated on font height. Here are two examples:
cell.setLeading(15f, 0f);
cell.setLeading(0f, 1.5f);
The first method call sets the leading to 15 points + 0 x font height.
The second method call sets the leading to 0 points + 1.5 x font height.
Cell Padding
You can set the padding of a cell (distance between cell edge and content) using these methods:
cell.setPadding(5);
cell.setPaddingLeft(8);
cell.setPaddingRight(8);
cell.setPaddingTop(8);
cell.setPaddingBottom(8);
cell.setBorder(Rectangle.NO_BORDER);
// removes border
cell.setBorderWidth
(3f);
cell.setBorderWidthLeft (1f);
cell.setBorderWidthRight (1f);
cell.setBorderWidthTop
(1f);
cell.setBorderWidthBottom(1f);
cell.setBorderColor
(BaseColor.BLUE);
cell.setBorderColorLeft (BaseColor.GREEN);
cell.setBorderColorRight (BaseColor.GREEN);
cell.setBorderColorTop
(BaseColor.GREEN);
cell.setBorderColorBottom(BaseColor.GREEN);
To avoid having the cell border and the content overlap, if you are having thick cell borders, call
the setUserBorderPadding(true), like this:
cell.setUserBorderPadding(true);
Cell Rotation
You can set the rotation of the cell content using the setRotation() method, like this:
cell.setRotation(90);
com.itextpdf.text.Document;
com.itextpdf.text.Paragraph;
com.itextpdf.text.Image;
com.itextpdf.text.pdf.PdfPCell;
com.itextpdf.text.pdf.PdfPTable;
com.itextpdf.text.pdf.PdfWriter;
import java.io.FileOutputStream;
import java.net.URL;
public class Table3Example {
public static void main(String[] args) {
Document document = new Document();
try {
PdfWriter.getInstance(document,
new FileOutputStream("Table3.pdf"));
document.open();
PdfPTable table = new PdfPTable(2); // 3 columns.
Image image = Image.getInstance("jakob-jenkov.jpg");
PdfPCell cell1 = new PdfPCell(new Paragraph("Cell 1"));
PdfPCell cell2 = new PdfPCell(image, false);
table.addCell(cell1);
table.addCell(cell2);
PdfPCell cell3 = new PdfPCell(image, true);
PdfPCell cell4 = new PdfPCell(new Paragraph("Cell 4"));
table.addCell(cell3);
table.addCell(cell4);
document.add(table);
document.close();
} catch(Exception e){
}
Nested Tables
You can add a PdfTable as content inside a PdfCell, thus nesting tables within tables. Here is
an example:
import com.itextpdf.text.Document;
import
import
import
import
com.itextpdf.text.Paragraph;
com.itextpdf.text.pdf.PdfPCell;
com.itextpdf.text.pdf.PdfPTable;
com.itextpdf.text.pdf.PdfWriter;
import java.io.FileOutputStream;
public class Table2Example {
public static void main(String[] args) {
Document document = new Document();
try {
PdfWriter.getInstance(document,
new FileOutputStream("Table2.pdf"));
document.open();
PdfPTable table = new PdfPTable(3); // 3 columns.
PdfPCell cell1 = new PdfPCell(new Paragraph("Cell 1"));
PdfPCell cell2 = new PdfPCell(new Paragraph("Cell 2"));
PdfPCell cell3 = new PdfPCell(new Paragraph("Cell 3"));
PdfPTable nestedTable = new PdfPTable(2);
nestedTable.addCell(new Paragraph("Nested Cell 1"));
nestedTable.addCell(new Paragraph("Nested Cell 2"));
cell3.addElement(nestedTable);
table.addCell(cell1);
table.addCell(cell2);
table.addCell(cell3);
document.add(table);
document.close();
} catch(Exception e){
e.printStackTrace();
}
}
You can do a lot with images in IText, including scaling, rotating, masking, absolute positioning,
borders, alignment etc. I'll only go through the basics here. Get the "IText in Action" book if you
want the full story on images. Here is a list of the topics covered in this text:
1. Creating an Image
2. Absolute Positioning
3. Scaling
4. Rotating
Creating an Image
The com.itextpdf.text.Image is used to add images to IText PDF documents. You can load
images either from file or from a URL, like this:
import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.FileOutputStream;
public class ImageExample {
public static void main(String[] args) {
Document document = new Document();
try {
PdfWriter.getInstance(document,
new FileOutputStream("Image.pdf"));
document.open();
Image image1 = Image.getInstance("watermark.png");
document.add(image1);
String imageUrl = "http://jenkov.com/images/" +
"20081123-20081123-3E1W7902-small-portrait.jpg";
Image image2 = Image.getInstance(new URL(imageUrl));
document.add(image2);
document.close();
} catch(Exception e){
e.printStackTrace();
}
}
Absolute Positioning
You set the absolute position of an image using the setAbsolutePosition() method. Do so
before adding the image to the document. This method takes two parameters: X and Y coordinate
of the lower left corner of the image. Also keep in mind, that the origin coordinate system in a
PDF document is the lower left corner of the document. Not the uppper left corner, like on a
screen.
Here is a code example:
import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.FileOutputStream;
import java.net.URL;
public class Image2Example {
public static void main(String[] args) {
Document document = new Document();
try {
PdfWriter.getInstance(document,
new FileOutputStream("Image2.pdf"));
document.open();
String imageUrl = "http://jenkov.com/images/" +
"20081123-20081123-3E1W7902-small-portrait.jpg";
Image image = Image.getInstance(new URL(imageUrl));
image.setAbsolutePosition(500f, 650f);
document.add(image);
document.close();
} catch(Exception e){
e.printStackTrace();
}
}
Scaling
You can scale images using one of these Image methods:
scaleAbsolute()
scaleAbsoluteWidth()
scaleAbsoluteHeight()
scalePercentage()
scaleToFit()
image.scaleAbsolute(150f, 150f);
document.add(image);
Image image2 = Image.getInstance(new URL(imageUrl));
image2.scalePercent(300f);
document.add(image2);
document.close();
} catch(Exception e){
e.printStackTrace();
}
Rotating
You can rotate images in IText PDF documents too, using these methods:
setRotationDegrees()
setRotation()
document.close();
} catch(Exception e){
e.printStackTrace();
}
You can add chapters and sections to a PDF document using IText. Chapters are represented by
the class com.itextpdf.text.Chapter. Sections are represented by the class
com.itextpdf.text.Section.
Here is a simple code example:
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
public class ChapterSectionExample {
public static void main(String[] args) {
Document document = new Document();
try {
PdfWriter.getInstance(document,
new FileOutputStream("ChapterSection.pdf"));
document.open();
Paragraph paragraph = new Paragraph();
paragraph.add(new Phrase("This is a chapter."));
Notice how the mouse pointer is shaped as a hand. This means that you can now click the text.
Also notice that there is no special style associated with the anchor by default. You will have to
add this yourself.
Internal Links
You can create internal links in your documents too, just like internal links in an HTML page.
Just like in HTML, you need both a link and a target anchor (an anchor with a name). Here is a
code example:
import
import
import
import
import
com.itextpdf.text.Anchor;
com.itextpdf.text.Document;
com.itextpdf.text.DocumentException;
com.itextpdf.text.Paragraph;
com.itextpdf.text.pdf.PdfWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
/**
*/
public class Anchor2Example {
public static void main(String[] args) {
Document document = new Document();
try {
PdfWriter.getInstance(document,
new FileOutputStream("Anchor2.pdf"));
document.open();
Anchor anchor =
new Anchor("Jump down to next paragraph");
anchor.setReference("#linkTarget");
Paragraph paragraph = new Paragraph();
paragraph.add(anchor);
document.add(paragraph);
Anchor anchorTarget =
new Anchor("This is the target of the link above");
anchor.setName("linkTarget");
Paragraph targetParagraph = new Paragraph();
targetParagraph.setSpacingBefore(50);
targetParagraph.add(anchorTarget);
document.add(targetParagraph);
document.close();
} catch (DocumentException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
Here is the resulting document. Notice how the mouse pointer is again shaped as a hand. Since
the target of the link is located just below on the same page, the Adobe Reader would probably
not react when the link is clicked. But, if the target paragraph was located on a different page, the
Adobe Reader would jump to that page.
You can add ordered and unordered lists to a PDF document using IText. List are represented by
the class com.itextpdf.text.List. List items are represented by the class
com.itextpdf.text.ListItem.
Here is a simple code example:
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
public class ListExample {
public static void main(String[] args) {
ZapfDingbatsList
IText has a special list implementation that uses the ZapfDingbats font. It's constructor takes two
parameters: The number of the symbol to use as item bullet, and the indentation of the text after
the bullet (space between bullet and text). Here is a code example:
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
public class List3Example {
public static void main(String[] args) {
Document document = new Document();
try {
PdfWriter.getInstance(document,
new FileOutputStream("List3.pdf"));
document.open();
ZapfDingbatsList zapfDingbatsList1 =
new ZapfDingbatsList(40, 15);
zapfDingbatsList1.add(new ListItem("Item 1"));
zapfDingbatsList1.add(new ListItem("Item 2"));
zapfDingbatsList1.add(new ListItem("Item 3"));
document.add(zapfDingbatsList1);
ZapfDingbatsList zapfDingbatsList2 =
new ZapfDingbatsList(43, 30);
zapfDingbatsList2.add(new ListItem("Item 1"));
zapfDingbatsList2.add(new ListItem("Item 2"));
zapfDingbatsList2.add(new ListItem("Item 3"));
document.add(zapfDingbatsList2);
ZapfDingbatsList zapfDingbatsList3 =
new ZapfDingbatsList(47, 45);
zapfDingbatsList3.add(new ListItem("Item 1"));
zapfDingbatsList3.add(new ListItem("Item 2"));
zapfDingbatsList3.add(new ListItem("Item 3"));
document.add(zapfDingbatsList3);
document.close();
} catch (DocumentException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
You can write text as superscript or subscript using the Chunk class, and it's setTextRise()
method. You use a positive text rise value for superscript, and a negative text rise value for
subscript.
Here is a simple code example:
import
import
import
import
com.itextpdf.text.Chunk;
com.itextpdf.text.Document;
com.itextpdf.text.DocumentException;
com.itextpdf.text.pdf.PdfWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
public class SuperSubScriptExample {
public static void main(String[] args) {
Document document = new Document();
try {
PdfWriter.getInstance(document,
new FileOutputStream("SuperSubScript.pdf"));
document.open();
Chunk normalText =
new Chunk("Normal text at normal y-location. ");
document.add(normalText);
Chunk superScript = new Chunk("Superscript");
superScript.setTextRise(5f);
document.add(superScript);
Chunk moreNormalText =
new Chunk(". More normal y-location text. ");
document.add(moreNormalText);
Chunk subScript = new Chunk("Subscript");
subScript.setTextRise(-5f);
document.add(subScript);
document.close();
} catch (DocumentException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
You can add underline and strikethrough text using the Chunk class, and its setUnderline()
method. You use a negative underline value to get the line lower below the text, and a positive
underline value to get the line to strike through the text.
Here is a simple code example:
import
import
import
import
import
com.itextpdf.text.Chunk;
com.itextpdf.text.Document;
com.itextpdf.text.DocumentException;
com.itextpdf.text.Paragraph;
com.itextpdf.text.pdf.PdfWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
public class UnderlineStrikethroughExample {
public static void main(String[] args) {
Document document = new Document();
try {
PdfWriter.getInstance(document,
new FileOutputStream("UnderlineStrikethrough.pdf"));
document.open();
Chunk underline = new Chunk("Underline. ");
underline.setUnderline(0.1f, -2f); //0.1 thick, -2 y-location
document.add(underline);
document.add(new Paragraph("
"));
document.close();
} catch (DocumentException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}