Sie sind auf Seite 1von 38

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();
}
}
}

Here is what happens in the code example:


1. First a Document instance is created. This Document instance represents the PDF
document. To add content to the PDF document, you call methods on the Document
instance.
2. Second, a PDFWriter is created, passing the Document instance and an OutputStream to
its constructor. The Document instance is the document we are currently adding content
to. The OutputStream is where the generated PDF document is written to. In this
example the PDF document is written to a file, using a FileOutputStream.

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

The com.itextpdf.text.Document class in IText represents a PDF document. It is one of the


core classes in IText. If you need to generate a PDF document from scratch, you will use the
Document class.
First you must create a Document instance. Then you must open it. After that you add content to
the document. Finally you close the Document instance.
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 {
document.open();
document.add(new Paragraph("A Hello World PDF document."));
document.close(); // no need to close PDFwriter?
} catch (DocumentException e) {
e.printStackTrace();
}
}
}

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.

Java IText: Chunk

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();
}
}
}

Here is what the generated document looks like:

sentence
sentence
sentence
sentence
sentence
sentence

1.
2.
3.
4.
5.
6.

"));
"));
"));
"));
"));
"));

An IText Chunk example


Notice how sentence 1 and sentence 6 are printed ontop of each other. The IText Chunk object
does not add line breaks, paragraph spacing or any other kind of spacing. It just adds the raw text
at the next available location, left to right. When it reaches the right edge of the document, it
restarts from the left edge, at the same Y location (same height).

Java IText: Phrase

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();
}
}

Here is what the generated document looks like:

An IText Phrase example

Notice how sentence 6 is nicely located on its own line.

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.

An IText Phrase example with custom line spacing

Java IText: Paragraph


The com.itextpdf.text.Paragraph class in IText represents a "paragraph" of text. In a
paragraph you can set the paragraph alignment, indentation and spacing before and after the
paragraph.
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("Paragraph.pdf"));
document.open();
Paragraph paragraph = new Paragraph();
for(int i=0; i<10; i++){
Chunk chunk = new Chunk(
"This is a sentence which is long " + i + ". ");
paragraph.add(chunk);
}
document.add(paragraph);
document.close();
} catch (DocumentException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}

Here is what the generated document looks like:

An IText Paragraph example

Notice how sentence 6 is nicely located on its own line.

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);

Spacing Before and After Paragraph


You can also set the spacing before and after a paragraph. Here is how you do that in code:
paragraph.setSpacingAfter(50);
paragraph.setSpacingBefore(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);

A Larger Paragraph Example


Here is a somewhat larger paragraph example which adds two parapraphs to a document. The
first paragraph uses the default left alignment, and indentation. The second paragraph is centeraligned, and uses 50 user units as both left and right indentation.
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
/**
*/
public class Paragraph2Example {
public static void main(String[] args) {
Document document = new Document();
try {
PdfWriter.getInstance(document,
new FileOutputStream("Paragraph2.pdf"));
document.open();
Paragraph paragraph1 = new Paragraph();
Paragraph paragraph2 = new Paragraph();
paragraph2.setSpacingAfter(25);
paragraph2.setSpacingBefore(25);
paragraph2.setAlignment(Element.ALIGN_CENTER);
paragraph2.setIndentationLeft(50);
paragraph2.setIndentationRight(50);
for(int i=0; i<10; i++){
Chunk chunk = new Chunk(
"This is a sentence which is long " + i + ". ");
paragraph1.add(chunk);
paragraph2.add(chunk);
}
document.add(paragraph1);
document.add(paragraph2);

document.close();
} catch (DocumentException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}

Here is how the resulting document looks:

A larger IText Paragraph example


Java IText: Font

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) {

Document document = new Document();


try {
PdfWriter.getInstance(document,
new FileOutputStream("Font.pdf"));
Font font1 = new Font(Font.FontFamily.HELVETICA , 25, Font.BOLD);
Font font2 = new Font(Font.FontFamily.COURIER
, 18,
Font.ITALIC | Font.UNDERLINE);
Font font3 = new Font(Font.FontFamily.TIMES_ROMAN, 27);
document.open();
document.add(new Chunk(
"This is sentence 1. ", font1));
document.add(new Phrase(
"This is sentence 2. ", font2));
document.add(new Paragraph("This is sentence 3. ", font3));
document.close();
} catch (DocumentException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}

Here is what the generated document looks like:

An IText Font example


Java IText: Table

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){
}
}

Here is what the generated document looks like:

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);

Spacing Before and After Table


You can set the spacing before and after the table like this:
table.setSpacingBefore(10f);
table.setSpacingAfter(10f);

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

relative widths. In the example above the first column


is twice the width of each of the following columns. You can use any numbers in the width array,
and they will be interpreted as relative values. For instance, you could have written 100, 50, 50 if
you needed a finer grained control over the column sizes.

Column Span
If you need a cell to span multiple columns you can do so using the setColspan() method, like
this:
cell.setColspan(2);

Cell Text Mode and Composite Mode


Cells can be added in either text mode or composite mode.
In text mode the settings of the added element (Phrase, Paragraph etc.) is ignored. Only the
settings of the cell is applied.
In composite mode the settings of the added element is respected. Settings like leading (line
spacing), margins etc. is thus respected.

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"));

Default Cell Settings in Text Mode


You can set the default cell settings of new cells added, using the table.addCell() methods,
like this:
PdfCell defaultCell = table.getDefaultCell();
defaultCell.setBorder(PdfCell.NO_BORDER);
//set more default settings.
//add cells with default settings:
table.addCell(new Paragraph("default text mode cell");
table.addCell(new Phrase("default text mode cell");

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

individually, by setting the

paragraph alignment on the Paragraph object.

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 Borders and Colors


You can set the cell border and color using these methods:
cell.setBackgroundColor(BaseColor.YELLOW);

//sets BG color to yellow.

cell.setBorder(Rectangle.NO_BORDER);

// removes border

cell.setBorderWidth
(3f);
cell.setBorderWidthLeft (1f);
cell.setBorderWidthRight (1f);
cell.setBorderWidthTop
(1f);
cell.setBorderWidthBottom(1f);

// sets border width to 3 units

cell.setBorderColor

(BaseColor.BLUE);

// sets blue border

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);

Tables and Images


You can add images to a table cell, and have either the cell fit the size of the image, or the image
fit the size of the cell. You do so by passing the image to the PdfPCell constructor, along with a
boolean saying whether the image should fit the cell (true), or the cell should fit the image
(false). Here is how:
import
import
import
import
import
import

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){
}

Here is what the generated document looks like:

An IText Table with Image

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();
}
}

Here is what the generated document looks like:

An IText nested Table


Java IText: Image

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();
}
}

Here is what the generated document looks like:

An IText Image example

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();
}
}

Here is what the resulting document looks like:

An IText Image at an absolute position

Scaling
You can scale images using one of these Image methods:
scaleAbsolute()
scaleAbsoluteWidth()
scaleAbsoluteHeight()
scalePercentage()
scaleToFit()

Here is a simple 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 Image3Example {
public static void main(String[] args) {
Document document = new Document();
try {
PdfWriter.getInstance(document,
new FileOutputStream("Image3.pdf"));
document.open();
String imageUrl = "http://jenkov.com/images/" +
"20081123-20081123-3E1W7902-small-portrait.jpg";
Image image = Image.getInstance(new URL(imageUrl));

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();
}

Here is what the resulting document looks like:

Two IText Image's scaled

Rotating
You can rotate images in IText PDF documents too, using these methods:
setRotationDegrees()
setRotation()

Here is a simple 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 Image4Example {
public static void main(String[] args) {
Document document = new Document();
try {
PdfWriter.getInstance(document,
new FileOutputStream("Image4.pdf"));
document.open();
String imageUrl = "http://jenkov.com/images/" +
"20081123-20081123-3E1W7902-small-portrait.jpg";
Image image = Image.getInstance(new URL(imageUrl));
image.setRotationDegrees(45f);
document.add(image);

document.close();
} catch(Exception e){
e.printStackTrace();
}

Here is what the resulting document looks like:

An IText Image rotated


Java IText: Chapter + Section

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."));

Chapter chapter = new Chapter(paragraph, 1);


Section section1 = chapter.addSection("This is section 1", 2);
Section section2 = chapter.addSection("This is section 2", 2);
document.add(chapter);
document.close();
} catch (DocumentException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}

Here is what the generated document looks like:

An IText Chapter and Section example


Java IText: Anchor (link)

The com.itextpdf.text.Anchor class in IText represents an link, either to an external website,


or internally in the document. The anchor (link) can be clicked just like a link in a web page.
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 AnchorExample {

public static void main(String[] args) {


Document document = new Document();
try {
PdfWriter.getInstance(document,
new FileOutputStream("Anchor.pdf"));
document.open();
Paragraph paragraph = new Paragraph();
paragraph.add(new Phrase("You can find the IText tutorial at "));
Anchor anchor = new Anchor(
"http://tutorials.jenkov.com/java-itext/index.html");
anchor.setReference(
"http://tutorials.jenkov.com/java-itext/index.html");
paragraph.add(anchor);
document.add(paragraph);
document.close();
} catch (DocumentException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}

Here is what the generated document looks like:

An IText Anchor example

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.

An IText internal Anchor example


Java IText: List

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) {

Document document = new Document();


try {
PdfWriter.getInstance(document,
new FileOutputStream("List.pdf"));
document.open();
List orderedList = new List(List.ORDERED);
orderedList.add(new ListItem("Item 1"));
orderedList.add(new ListItem("Item 2"));
orderedList.add(new ListItem("Item 3"));
document.add(orderedList);
List unorderedList = new List(List.UNORDERED);
unorderedList.add(new ListItem("Item 1"));
unorderedList.add(new ListItem("Item 2"));
unorderedList.add(new ListItem("Item 3"));
document.add(unorderedList);
document.close();
} catch (DocumentException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}

Here is what the generated document looks like:

An IText List and ListItem example

Roman and Greek Numerals


You can create lists with roman and greek numerals too. To do this, use the
com.itextpdf.text.RomanList and com.itextpdf.text.GreekList classes. Here is an
example:
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.PdfWriter;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
public class List2Example {
public static void main(String[] args) {
Document document = new Document();
try {
PdfWriter.getInstance(document,
new FileOutputStream("List2.pdf"));
document.open();
RomanList romanList = new RomanList();
romanList.add(new ListItem("Item 1"));
romanList.add(new ListItem("Item 2"));
romanList.add(new ListItem("Item 3"));
document.add(romanList);
GreekList greekList = new GreekList();
greekList.add(new ListItem("Item 1"));
greekList.add(new ListItem("Item 2"));
greekList.add(new ListItem("Item 3"));
document.add(greekList);
document.close();
} catch (DocumentException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}

Here is what the generated document looks like:

An IText RomanList and GreekList example

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();
}
}

Here is what the generated document looks like:

An IText ZapfDingbats example


Java IText: Superscript + Subscript

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();
}
}
}

Here is what the generated document looks like:

IText Chunk's with superscript and subscript


Java IText: Underline + Strikethrough

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("

"));

Chunk strikethrough = new Chunk("Strikethrough.");


strikethrough.setUnderline(0.1f, 3f); //0.1 thick, 2 y-location
document.add(strikethrough);

document.close();
} catch (DocumentException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}

Here is what the generated document looks like:

IText Chunk's with underline and strikethrough