You are on page 1of 7

Tutorials (https://www.vogella.com/tutorials/) Training (https://www.vogella.

com/training/)
Search
(https://www.vogella.com/)

Creating PDF with Java


Consulting (https://www.vogella.com/consulting/) Company (https://www.vogella.com/company/)
We use cookies GET MORE...
Read Premium Content ...

and iText - Tutorial


Contact We use cookies and other tracking technologies to improve your browsing experience
us (https://www.vogella.com/contact.html)
(https://learn.vogella.com)
on our website, to show you personalized content and targeted ads, to analyze our
Book Onsite or Virtual Training
website traffic,and to understand where our visitors are coming from.
(https://twitter.com/vogella)Lars Vogel (c) 2008 - 2020 vogella GmbH By browsing our
(https://www.vogella.com/training/onsite/
 – Version
website, you consent to0.6, 26.09.2016
our use of cookies and other tracking technologies. Consulting
(https://www.vogella.com/consulting/)
I agree TABLE
Change myOF CONTENTS
preferences
1. Overview TRAINING EVENTS
2. Installation Now offering virtual, onsite and
online training
3. Create a PDF
(https://www.vogella.com/training/)
4. Formatting your output

5. Read an existing pdf

6. Links and Literature 

Java and PDF with iText. This article demonstrate how to


create PDF les with Java and the iText library. In this
tutorial iText version 5.0.x is used

1. Overview
iText is a Java library originally created by Bruno Lowagie which allows
to create PDF, read PDF and manipulate them. The following tutorial
will show how to create PDF files with iText. This tutorial assumes that
you have basis Java
(https://www.vogella.com/tutorials/JavaIntroduction/article.html) and Eclipse
(https://www.vogella.com/tutorials/Eclipse/article.html) knowledge.

iText has a hierarchical structure. The smallest text unit is a "Chunk"


which is a String with a pre-defined font. A "Phrase" combines several
Chunks and allows to define line spacing. "Paragraph" is a subclass of
"Phrase" and allows to define more layout attributes, e.g. margins. The
class "Anchor" is a subclass of "Paragraph" and serves as the basis for
hyperlinks in the generated PDF.

2. Installation
Download the iText core binary from the webpage
http://sourceforge.net/projects/itext/. The download contains one jar
which is required if you want to use iText.

3. Create a PDF
Create a new Java project "de.vogella.itext.write" with the package
Tutorials (https://www.vogella.com/tutorials/)
"de.vogella.itext.write". CreateTraining and put the iTextSearch
(https://www.vogella.com/training/)
a folder "lib" library (jar
(https://www.vogella.com/)file) into this folder. Add the jar to your classpath
(https://www.vogella.com/tutorials/Eclipse/article.html#classpath)
Consulting (https://www.vogella.com/consulting/) .
Company (https://www.vogella.com/company/)
We use cookies GET MORE...
Create the following class "FirstPdf.java" . I assume that the code is Premium Content ...
Read
Contact We use cookies andmuch
pretty other tracking technologies
self-explaining.
us (https://www.vogella.com/contact.html) I tried to addto improve
lots yourto
of comments browsing
make it experience
(https://learn.vogella.com)
on our website, easier to understand.
to show For more complex
you personalized content examples have a look
and targeted ads,atto
theanalyze our
Book Onsite or Virtual Training
iText Homepage (http://www.lowagie.com/iText/).
website traffic, and to understand where our visitors are coming from. By browsing our
(https://www.vogella.com/training/onsite/
website, you consent to our use of cookies and other tracking technologies. Consulting
(https://www.vogella.com/consulting/)
I agree Change my preferences
TRAINING EVENTS
Now offering virtual, onsite and
online training
(https://www.vogella.com/training/)
JAVA
package de.vogella.itext.write;
Tutorials (https://www.vogella.com/tutorials/) Training (https://www.vogella.com/training/)
Search
(https://www.vogella.com/) import java.io.FileOutputStream;
import java.util.Date;
Consulting (https://www.vogella.com/consulting/) Company (https://www.vogella.com/company/)
We use cookies
import com.itextpdf.text.Anchor;
GET MORE...
import com.itextpdf.text.BadElementException;
Read Premium Content ...
Contact We use cookiesimport
and other tracking technologies to improve your browsing experience
com.itextpdf.text.BaseColor;
us (https://www.vogella.com/contact.html)
import com.itextpdf.text.Chapter; (https://learn.vogella.com)
on our website, import
to show you personalized content
com.itextpdf.text.Document; and targeted ads, to analyze our
Book Onsite or Virtual Training
import com.itextpdf.text.DocumentException;
website traffic, and to understand where our visitors are coming from. By browsing our
(https://www.vogella.com/training/onsite/
import com.itextpdf.text.Element;
website, you consent to our use of cookies and other tracking technologies.
import com.itextpdf.text.Font; Consulting
import com.itextpdf.text.List;
import com.itextpdf.text.ListItem; (https://www.vogella.com/consulting/)
I agree Change
importmy preferences
com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase; TRAINING EVENTS
import com.itextpdf.text.Section;
import com.itextpdf.text.pdf.PdfPCell; Now offering virtual, onsite and
import com.itextpdf.text.pdf.PdfPTable;
online training
import com.itextpdf.text.pdf.PdfWriter;
(https://www.vogella.com/training/)

public class FirstPdf {


private static String FILE = "c:/temp/FirstPdf.pdf";
private static Font catFont = new
Font(Font.FontFamily.TIMES_ROMAN, 18,
Font.BOLD);
private static Font redFont = new
Font(Font.FontFamily.TIMES_ROMAN, 12,
Font.NORMAL, BaseColor.RED);
private static Font subFont = new
Font(Font.FontFamily.TIMES_ROMAN, 16,
Font.BOLD);
private static Font smallBold = new
Font(Font.FontFamily.TIMES_ROMAN, 12,
Font.BOLD);

public static void main(String[] args) {


try {
Document document = new Document();
PdfWriter.getInstance(document, new
FileOutputStream(FILE));
document.open();
addMetaData(document);
addTitlePage(document);
addContent(document);
document.close();
} catch (Exception e) {
e.printStackTrace();
}
}

// iText allows to add metadata to the PDF which can be viewed


in your Adobe
// Reader
// under File -> Properties
private static void addMetaData(Document document) {
document.addTitle("My first PDF");
document.addSubject("Using iText");
document.addKeywords("Java, PDF, iText");
document.addAuthor("Lars Vogel");
document.addCreator("Lars Vogel");
}

private static void addTitlePage(Document document)


throws DocumentException {
Paragraph preface = new Paragraph();
// We add one emptyTraining
Tutorials (https://www.vogella.com/tutorials/) line Search
(https://www.vogella.com/training/)
addEmptyLine(preface, 1);
(https://www.vogella.com/) // Lets write a big header
preface.add(new Paragraph("Title of the document",
Consulting (https://www.vogella.com/consulting/) Company (https://www.vogella.com/company/)
We use cookies catFont)); GET MORE...
addEmptyLine(preface, 1); Read Premium Content ...
Contact We use cookies and other tracking
create: technologies
us (https://www.vogella.com/contact.html)
// Will toby:
Report generated improve
_name, your
_date browsing experience
(https://learn.vogella.com)
preface.add(new Paragraph(
on our website, to show you personalized content and targeted ads, to analyze our
"Report generated by: " + Book Onsite or Virtual Training
website traffic, and to understand where our+ visitors
System.getProperty("user.name") are
", " + new coming
Date(), from. By browsing our
//$NON-NLS-1$
(https://www.vogella.com/training/onsite/
//$NON-NLS-2$ //$NON-NLS-3$
website, you consent to our use of cookies and other tracking technologies.
smallBold)); Consulting
addEmptyLine(preface, 3);
(https://www.vogella.com/consulting/)
I agree Change mypreface.add(new
preferences Paragraph(
"This document describes something which is very
important ", TRAINING EVENTS
smallBold));
Now offering virtual, onsite and
addEmptyLine(preface, 8); online training
preface.add(new Paragraph( (https://www.vogella.com/training/)
"This document is a preliminary version and not
subject to your license agreement or any other agreement with
vogella.com ;-).",
redFont));

document.add(preface);
// Start a new page
document.newPage();
}

private static void addContent(Document document) throws


DocumentException {
Anchor anchor = new Anchor("First Chapter", catFont);
anchor.setName("First Chapter");

// Second parameter is the number of the chapter


Chapter catPart = new Chapter(new Paragraph(anchor), 1);

Paragraph subPara = new Paragraph("Subcategory 1",


subFont);
Section subCatPart = catPart.addSection(subPara);
subCatPart.add(new Paragraph("Hello"));

subPara = new Paragraph("Subcategory 2", subFont);


subCatPart = catPart.addSection(subPara);
subCatPart.add(new Paragraph("Paragraph 1"));
subCatPart.add(new Paragraph("Paragraph 2"));
subCatPart.add(new Paragraph("Paragraph 3"));

// add a list
createList(subCatPart);
Paragraph paragraph = new Paragraph();
addEmptyLine(paragraph, 5);
subCatPart.add(paragraph);

// add a table
createTable(subCatPart);

// now add all this to the document


document.add(catPart);

// Next section
anchor = new Anchor("Second Chapter", catFont);
anchor.setName("Second Chapter");
// Second parameter is the number of the chapter
catPart = new Chapter(new
Tutorials (https://www.vogella.com/tutorials/) Paragraph(anchor),
Training 1); Search
(https://www.vogella.com/training/)

(https://www.vogella.com/) subPara = new Paragraph("Subcategory", subFont);


subCatPart = catPart.addSection(subPara);
Consulting (https://www.vogella.com/consulting/) Company (https://www.vogella.com/company/)
We use cookies GET MORE...
subCatPart.add(new Paragraph("This is a very important
message"));
Read Premium Content ...
Contact We use cookies and other tracking
us (https://www.vogella.com/contact.html)
// now technologies
add all this to improve your browsing experience
to the document
(https://learn.vogella.com)
document.add(catPart);
on our website, to show you personalized content and targeted ads,Book to analyze our
Onsite or Virtual Training
website traffic, and }to understand where our visitors are coming from. By browsing our
(https://www.vogella.com/training/onsite/
website, you consent to our
private usevoid
static of cookies and other subCatPart)
createTable(Section tracking technologies.
Consulting
throws BadElementException {
(https://www.vogella.com/consulting/)
PdfPTable table = new PdfPTable(3);
I agree Change my preferences
// t.setBorderColor(BaseColor.GRAY); TRAINING EVENTS
// t.setPadding(4);
// t.setSpacing(4); Now offering virtual, onsite and
// t.setBorderWidth(1); online training
(https://www.vogella.com/training/)
PdfPCell c1 = new PdfPCell(new Phrase("Table Header 1"));
c1.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(c1);

c1 = new PdfPCell(new Phrase("Table Header 2"));


c1.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(c1);

c1 = new PdfPCell(new Phrase("Table Header 3"));


c1.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(c1);
table.setHeaderRows(1);

table.addCell("1.0");
table.addCell("1.1");
table.addCell("1.2");
table.addCell("2.1");
table.addCell("2.2");
table.addCell("2.3");

subCatPart.add(table);

private static void createList(Section subCatPart) {


List list = new List(true, false, 10);
list.add(new ListItem("First point"));
list.add(new ListItem("Second point"));
list.add(new ListItem("Third point"));
subCatPart.add(list);
}

private static void addEmptyLine(Paragraph paragraph, int


number) {
for (int i = 0; i < number; i++) {
paragraph.add(new Paragraph(" "));
}
}
}

The resulting pdf should look like the following.


Tutorials (https://www.vogella.com/tutorials/) Training (https://www.vogella.com/training/)
Search
(https://www.vogella.com/)
4. Formatting your output
Consulting (https://www.vogella.com/consulting/)
Company (https://www.vogella.com/company/)
We use cookies GET MORE...
Paragraph allows to set the alignment and the indentation. For this
example create project "de.vogella.itext.position" similar to the Read Premium Content ...
Contact We use cookies and other tracking technologies to improve your browsing experience
us (https://www.vogella.com/contact.html)
previously created ones. Create the following class "PositionPdf.java".
(https://learn.vogella.com)
on our website, to show you personalized content and targeted ads,Bookto analyze our
Onsite or Virtual Training
website traffic, and to understand where our visitors are coming from.
package de.vogella.itext.position;
By browsing our
JAVA
(https://www.vogella.com/training/onsite/
website, you consent to our use of cookies and other tracking technologies.
Consulting
import java.io.FileOutputStream;
(https://www.vogella.com/consulting/)
I agree Change
importmy preferences
com.itextpdf.text.Document;
import com.itextpdf.text.Element;
TRAINING EVENTS
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter; Now offering virtual, onsite and
public class PositionPdf { online training
private static String FILE = "PositionPdf.pdf"; (https://www.vogella.com/training/)

public static void main(String[] args) {


try {
Document document = new Document();
PdfWriter.getInstance(document, new
FileOutputStream(FILE));
document.open();
// Left
Paragraph paragraph = new Paragraph("This is right
aligned text");
paragraph.setAlignment(Element.ALIGN_RIGHT);
document.add(paragraph);
// Centered
paragraph = new Paragraph("This is centered text");
paragraph.setAlignment(Element.ALIGN_CENTER);
document.add(paragraph);
// Left
paragraph = new Paragraph("This is left aligned
text");
paragraph.setAlignment(Element.ALIGN_LEFT);
document.add(paragraph);
// Left with indentation
paragraph = new Paragraph(
"This is left aligned text with indentation");
paragraph.setAlignment(Element.ALIGN_LEFT);
paragraph.setIndentationLeft(50);
document.add(paragraph);

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

5. Read an existing pdf


iText allows to read existing pdf’s and include them into your own pdf.
The following example will create page 2 of the previous example and
create a new document with this page.
Create a new Java project "de.vogella.itext.readpdf" with the package
Tutorials (https://www.vogella.com/tutorials/)
"de.vogella.itext.read". CreateTraining and put the iText Search
(https://www.vogella.com/training/)
a folder "lib" library (jar
(https://www.vogella.com/)file) into this folder. Add the jar to your classpath
(https://www.vogella.com/tutorials/Eclipse/article.html#classpath)
Consulting (https://www.vogella.com/consulting/) . Create the
Company (https://www.vogella.com/company/)
We use cookies
following class "ReadAndUsePdf.java". GET MORE...
Read Premium Content ...
Contact We use cookiespackage
and other tracking
us (https://www.vogella.com/contact.html)technologies
de.vogella.itext.read;
to improve your browsing
JAVA experience
(https://learn.vogella.com)
on our website, to show you personalized content and targeted ads, to analyze our
import java.io.FileOutputStream;
Book Onsite or Virtual Training
website traffic, and to java.io.IOException;
import understand where our visitors are coming from. By browsing our
(https://www.vogella.com/training/onsite/
website, you consent to our use of cookies and other tracking technologies.
Consulting
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException; (https://www.vogella.com/consulting/)
I agree Change
importmy preferences
com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
TRAINING EVENTS
import com.itextpdf.text.pdf.PdfWriter; Now offering virtual, onsite and
public class ReadAndUsePdf { online training
private static String INPUTFILE = "c:/temp/FirstPdf.pdf";(https://www.vogella.com/training/)
private static String OUTPUTFILE = "c:/temp/ReadPdf.pdf";

public static void main(String[] args) throws


DocumentException,
IOException {
Document document = new Document();

PdfWriter writer = PdfWriter.getInstance(document,


new FileOutputStream(OUTPUTFILE));
document.open();
PdfReader reader = new PdfReader(INPUTFILE);
int n = reader.getNumberOfPages();
PdfImportedPage page;
// Go through all pages
for (int i = 1; i <= n; i++) {
// only page number 2 will be included
if (i == 2) {
page = writer.getImportedPage(reader, i);
Image instance = Image.getInstance(page);
document.add(instance);
}
}
document.close();

6. Links and Literature


6.1. iText Resources
iText Homepage (http://www.lowagie.com/iText)

http://itextdocs.lowagie.com/tutorial/ Tutorial from iText homepage,


lots of specific examples

Last updated 15:07 24. Jul 2020


Change your Cookies Preferences

You might also like