Vous êtes sur la page 1sur 15

Read and generate pdf in Java- iText

Tutorial
By Lokesh Gupta | Filed Under: Java Libraries

In this iText tutorial, I am writing various code examples read a pdf


file and generate PDF file. iText library helps to generate pdf files from java
applications dynamically.

These code examples are categorized into multiple sections based on the work
they do OR functionality they achieve. With each java pdf example, I have
attached a snapshot of PDF file so that you can visualize what exactly code is
writing in PDF file. You may extend these examples to get text from database or
some API response in json and write to pdf.

I have tried to put as many examples as I found useful to put here to help you
all while you work on pdf files in Java. Through given examples use simple java
programs, you can reuse this code in web applications.

Table of Contents

1. Overview of iText library


2. Commonly used iText classes
3. iText hello world example
4. Setting file attributes to PDF
5. Adding images to PDF
6. Creating tables in PDF
7. Creating lists in PDFs
8. Styling and formatting PDF output
9. Create password protected PDF files
10. Create PDF with limited permissions
11. Read and modify an existing PDF
12. Write PDF as Output Stream in HTTP response

Download Sourcecode of iText Examples

Let’s start the tutorial with an introduction to iText library.

1. Overview of iText library


On brighter side, iText is an open source API. Note that though iText is open
source, you still need to purchase a commercial license if you want to use it for
commercial purposes. iText is a freely available Java library
from http://itextpdf.com. The iText library is powerful and supports the
generation of HTML, RTF, and XML documents, in addition to generating PDFs.
You can choose from a variety of fonts to be used in the document. Also, the
structure of iText allows you to generate any of the above-mentioned types of
documents with the same code. Isn’t it great feature, right?

The iText library contains classes to generate PDF text in various fonts, generate
tables in PDF document, add watermarks to pages, and so on. There are many
more features available with iText which I will leave on you to explore.

To add iText into your application, include following maven repository into
your pom.xml file.

pom.xml
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13</version>
</dependency>

Or you can download the latest jar files from maven repository.

2. Commonly used iText classes


Let’s list down and get familiar with important classes which we are going to use
in this application.

 com.itextpdf.text.Document : This is the most important class in iText


library and represent PDF document instance. 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.
 com.itextpdf.text.Paragraph : This class represents a indented
“paragraph” of text. In a paragraph you can set the paragraph alignment,
indentation and spacing before and after the paragraph.
 com.itextpdf.text.Chapter : This class represents a chapter in the PDF
document. It is created using a Paragraph as title and an int as chapter
number.
 com.itextpdf.text.Font : This class 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.itextpdf.text.List : This class represents a list, which, in turn, contains
a number of ListItems.
 com.itextpdf.text.pdf.PDFPTable : This is a table that can be put at an
absolute position but can also be added to the document as the class
Table.
 com.itextpdf.text.Anchor : An Anchor can be a reference or a destination
of a reference. A link like we have in HTML pages.
 com.itextpdf.text.pdf.PdfWriter : When this PdfWriter is added to a
certain PdfDocument, the PDF representation of every Element added to
this Document will be written to the outputstream attached to writer (file
or network).
 com.itextpdf.text.pdf.PdfReader : Used to read a PDF document. Simple
and clear.

2. iText hello world example


Let’s start writing our example codes with customary Hello World application. In
this application, I will create a PDF file with a single statement in content.

JavaPdfHelloWorld.java
import java.io.FileNotFoundException;
import java.io.FileOutputStream;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;

public class JavaPdfHelloWorld


{
public static void main(String[] args)
{
Document document = new Document();
try
{
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("Hell
document.open();
document.add(new Paragraph("A Hello World PDF document."));
document.close();
writer.close();
} catch (DocumentException e)
{
e.printStackTrace();
} catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
}
Hello World Program Output as Pdf

4. Set file attributes to PDF file


This example shows how to set various attributes like author name, created
date, creator name or simply title of the pdf file.

Document document = new Document();


try
{
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("SetAttrib
document.open();
document.add(new Paragraph("Some content here"));

//Set attributes here


document.addAuthor("Lokesh Gupta");
document.addCreationDate();
document.addCreator("HowToDoInJava.com");
document.addTitle("Set Attribute Example");
document.addSubject("An example to show how attributes can be added to pdf files."

document.close();
writer.close();
} catch (Exception e)
{
e.printStackTrace();
}
SetAttributeExample Pdf Output

5. Add images to PDF file


An example to show how images can be added to PDF files. Example contain
adding images from file system as well as URLs. Also, I have added code
to position the images within document.

Document document = new Document();


try
{
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("AddImageE
document.open();
document.add(new Paragraph("Image Example"));

//Add Image
Image image1 = Image.getInstance("temp.jpg");
//Fixed Positioning
image1.setAbsolutePosition(100f, 550f);
//Scale to new height and new width of image
image1.scaleAbsolute(200, 200);
//Add to document
document.add(image1);

String imageUrl = "http://www.eclipse.org/xtend/images/java8_logo.png";


Image image2 = Image.getInstance(new URL(imageUrl));
document.add(image2);

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

AddImageExample Pdf Output

6. Generate tables in PDFs


Below example shows how to add tables in a pdf document.

public static void main(String[] args)


{
Document document = new Document();
try
{
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("AddTa
document.open();

PdfPTable table = new PdfPTable(3); // 3 columns.


table.setWidthPercentage(100); //Width 100%
table.setSpacingBefore(10f); //Space before table
table.setSpacingAfter(10f); //Space after table

//Set Column widths


float[] columnWidths = {1f, 1f, 1f};
table.setWidths(columnWidths);

PdfPCell cell1 = new PdfPCell(new Paragraph("Cell 1"));


cell1.setBorderColor(BaseColor.BLUE);
cell1.setPaddingLeft(10);
cell1.setHorizontalAlignment(Element.ALIGN_CENTER);
cell1.setVerticalAlignment(Element.ALIGN_MIDDLE);

PdfPCell cell2 = new PdfPCell(new Paragraph("Cell 2"));


cell2.setBorderColor(BaseColor.GREEN);
cell2.setPaddingLeft(10);
cell2.setHorizontalAlignment(Element.ALIGN_CENTER);
cell2.setVerticalAlignment(Element.ALIGN_MIDDLE);

PdfPCell cell3 = new PdfPCell(new Paragraph("Cell 3"));


cell3.setBorderColor(BaseColor.RED);
cell3.setPaddingLeft(10);
cell3.setHorizontalAlignment(Element.ALIGN_CENTER);
cell3.setVerticalAlignment(Element.ALIGN_MIDDLE);

//To avoid having the cell border and the content overlap, if you are having t
//cell1.setUserBorderPadding(true);
//cell2.setUserBorderPadding(true);
//cell3.setUserBorderPadding(true);

table.addCell(cell1);
table.addCell(cell2);
table.addCell(cell3);

document.add(table);

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

AddTableExample Pdf Output

7. Create list items in PDF file


Below example will help you in understanding that how to write lists in pdf
files using iText library.

Document document = new Document();


try
{
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("ListExamp
document.open();
document.add(new Paragraph("List Example"));

//Add ordered list


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

//Add un-ordered list


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

//Add roman list


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

//Add Greek list


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

//ZapfDingbatsList List Example


ZapfDingbatsList zapfDingbatsList = new ZapfDingbatsList(43, 30);
zapfDingbatsList.add(new ListItem("Item 1"));
zapfDingbatsList.add(new ListItem("Item 2"));
zapfDingbatsList.add(new ListItem("Item 3"));
document.add(zapfDingbatsList);

//List and Sublist Examples


List nestedList = new List(List.UNORDERED);
nestedList.add(new ListItem("Item 1"));

List sublist = new List(true, false, 30);


sublist.setListSymbol(new Chunk("", FontFactory.getFont(FontFactory.HELVETICA, 6))
sublist.add("A");
sublist.add("B");
nestedList.add(sublist);

nestedList.add(new ListItem("Item 2"));

sublist = new List(true, false, 30);


sublist.setListSymbol(new Chunk("", FontFactory.getFont(FontFactory.HELVETICA, 6))
sublist.add("C");
sublist.add("D");
nestedList.add(sublist);

document.add(nestedList);

document.close();
writer.close();
} catch (Exception e)
{
e.printStackTrace();
}
ListExample Pdf
example

8. Generate PDF and style / format PDF file


content
Let’s see some examples of styling the content of PDF file. Example contains
the usage of Fonts as well as chapter and sections as well.

Font blueFont = FontFactory.getFont(FontFactory.HELVETICA, 8, Font.NORMAL, new CMYKCol


Font redFont = FontFactory.getFont(FontFactory.COURIER, 12, Font.BOLD, new CMYKColor(0
Font yellowFont = FontFactory.getFont(FontFactory.COURIER, 14, Font.BOLD, new CMYKColo
Document document = new Document();
try
{
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("StylingEx
document.open();
//document.add(new Paragraph("Styling Example"));

//Paragraph with color and font styles


Paragraph paragraphOne = new Paragraph("Some colored paragraph text", redFont);
document.add(paragraphOne);

//Create chapter and sections


Paragraph chapterTitle = new Paragraph("Chapter Title", yellowFont);
Chapter chapter1 = new Chapter(chapterTitle, 1);
chapter1.setNumberDepth(0);

Paragraph sectionTitle = new Paragraph("Section Title", redFont);


Section section1 = chapter1.addSection(sectionTitle);

Paragraph sectionContent = new Paragraph("Section Text content", blueFont);


section1.add(sectionContent);

document.add(chapter1);

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

StylingExample Pdf Example


9. Generate password protected PDF file
Let’s see an example of creating password protected pdf file.
Here writer.setEncryption() is used to set password to generated PDF.

We need to add bouncy castle jars generating for password protected PDFs. I
have added these jars in sourcecode of examples for this post.
private static String USER_PASSWORD = "password";
private static String OWNER_PASSWORD = "lokesh";

public static void main(String[] args) {


try
{
OutputStream file = new FileOutputStream(new File("PasswordProtected.pdf"));
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, file);

writer.setEncryption(USER_PASSWORD.getBytes(),
OWNER_PASSWORD.getBytes(), PdfWriter.ALLOW_PRINTING,
PdfWriter.ENCRYPTION_AES_128);

document.open();
document.add(new Paragraph("Password Protected pdf example !!"));
document.close();
file.close();

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

PasswordProtected Pdf file


10. Create PDF with limited permissions
In this example, I am setting few file permissions for a pdf file to limit access
for other users. Following are several permission values:

PdfWriter.ALLOW_PRINTING
PdfWriter.ALLOW_ASSEMBLY
PdfWriter.ALLOW_COPY
PdfWriter.ALLOW_DEGRADED_PRINTING
PdfWriter.ALLOW_FILL_IN
PdfWriter.ALLOW_MODIFY_ANNOTATIONS
PdfWriter.ALLOW_MODIFY_CONTENTS
PdfWriter.ALLOW_SCREENREADERS

You can provide multiple permissions by ORing different values. For example
PdfWriter.ALLOW_PRINTING | PdfWriter.ALLOW_COPY.

public static void main(String[] args) {


try {
OutputStream file = new FileOutputStream(new File(
"LimitedAccess.pdf"));
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, file);

writer.setEncryption("".getBytes(), "".getBytes(),
PdfWriter.ALLOW_PRINTING , //Only printing allowed; Try to copy text !
PdfWriter.ENCRYPTION_AES_128);

document.open();
document.add(new Paragraph("Limited Access File !!"));
document.close();
file.close();

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

11. Read and modify an existing PDF file


To complete this tutorial, let’s see an example of reading and modifying a PDF
file using PDFReader class provided by iText library itself. In this example, I
will read content from PDF file and add some random content to it’s all pages.

public static void main(String[] args) {


try
{
//Read file using PdfReader
PdfReader pdfReader = new PdfReader("HelloWorld.pdf");

//Modify file using PdfReader


PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileOutputStream("HelloWorld-

Image image = Image.getInstance("temp.jpg");


image.scaleAbsolute(100, 50);
image.setAbsolutePosition(100f, 700f);

for(int i=1; i<= pdfReader.getNumberOfPages(); i++)


{
PdfContentByte content = pdfStamper.getUnderContent(i);
content.addImage(image);
}

pdfStamper.close();

} catch (IOException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
}
}

Modified Pdf Example

12. Write PDF as Output Stream in HTTP response


This is the last example in list and in this example, I am writing the content
of created PDF file into output stream attached to
HttpServletResponse object. This will be needed when you want to stream the
PDF file in a client-server environment.

Document document = new Document();


try{
response.setContentType("application/pdf");
PdfWriter.getInstance(document, response.getOutputStream());
document.open();
document.add(new Paragraph("howtodoinjava.com"));
document.add(new Paragraph(new Date().toString()));
//Add more content here
}catch(Exception e){
e.printStackTrace();
}
document.close();
}

That’s all for this big list of iText example codes. Leave a comment if something
is not clear to you OR you would like to add any other example into this list.

Download Sourcecode of iText Examples

Happy Learning !!

Vous aimerez peut-être aussi