1. Introduction
iText and PdfBox are both Java libraries that we use to create and manipulate PDF files. Although the final output of the libraries is the same, they operate differently. In this quick tutorial, we’ll focus on creating PDF documents from scratch based on the iText and PdfBox libraries. We discuss reading PDF files with these libraries in another tutorial.
2. Maven Dependencies
First, we need to include the following Maven dependencies in our project:
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13.4</version>
</dependency>
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>3.0.5</version>
</dependency>
The latest versions of the iText and PdfBox libraries are available on Maven Central.
It’s important to know that iText is available under the open-source AGPL license, as well as a commercial license. If we purchase a commercial license, we can keep our source code to ourselves, allowing us to retain our IP. If we use the AGPL version, we’ll need to release our source code free of charge to make sure our software complies with AGPL.
We’ll also need to add one extra dependency in case we need to encrypt our file. The Bouncy Castle Provider package contains implementations of cryptographic algorithms and is required by both libraries:
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcpkix-jdk18on</artifactId>
<version>1.80</version>
</dependency>
The latest version of The Bouncy Castle Provider library is available on Maven Central.
3. Create a PDF With iText
iText is the leading PDF library for developers.
3.1. Inserting Text
Let’s look at how we insert a new file with “Hello World” text into a PDF file:
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream("iTextHelloWorld.pdf"));
document.open();
Font font = FontFactory.getFont(FontFactory.COURIER, 16, BaseColor.BLACK);
Chunk chunk = new Chunk("Hello World", font);
document.add(chunk);
document.close();
Creating a PDF with the use of the iText library is based on manipulating objects implementing the Elements interface in Document (in version 5.5.10, there are 45 of those implementations).
The smallest element we can add to the document and use is Chunk, which is a string with the applied font.
Additionally, we can combine Chunks with other elements, like Paragraphs, Sections, etc., resulting in nice-looking documents.
3.2. Inserting Images
The iText library provides an easy way to add an image to the document. We simply need to create an Image instance and add it to the Document:
Path path = Paths.get(ClassLoader.getSystemResource("Java_logo.png").toURI());
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream("iTextImageExample.pdf"));
document.open();
Image img = Image.getInstance(path.toAbsolutePath().toString());
document.add(img);
document.close();
3.3. Adding a Paragraph
iText allows us to add paragraphs to a PDF document.
Again, first, we create an instance of PdfWriter using a Document object. Then, we open the Document:
Document documentParagraph = new Document();
PdfWriter.getInstance(documentParagraph, new FileOutputStream("iTextParagraph.pdf"));
documentParagraph.open();
Next, we construct a Paragraph object, provide our text, and add the paragraph to the document. We can also set its alignment:
Paragraph paragraph = new Paragraph("This paragraph will be horizontally centered.");
paragraph.setAlignment(Element.ALIGN_CENTER);
document.add(paragraph);
And, of course, let’s remember to close the document when we’re done.
3.4. Inserting Tables
iText also allows us to add tabular data.
First, we need to create a PdfTable object and provide several columns for our table in the constructor.
Then we can simply add new cells by calling the addCell method on the newly created table object. iText will create table rows as long as all the necessary cells are defined. This means that once we create a table with three columns and add eight cells to it, only two rows with three cells in each will be displayed.
Let’s first set up our task at a high level with some helper methods that we’ll fill out in a moment. First, we create an instance of PdfWriter using a Document object. Then, we open the Document. Subsequently, we add a PDF table:
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream("iTextTable.pdf"));
document.open();
PdfPTable table = new PdfPTable(3);
addTableHeader(table);
addRows(table);
addCustomRows(table);
document.add(table);
document.close();
Now we’ll create a new table with three columns and three rows. We’ll treat the first row as a table header with a changed background color and border width:
private void addTableHeader(PdfPTable table) {
Stream.of("column header 1", "column header 2", "column header 3")
.forEach(columnTitle -> {
PdfPCell header = new PdfPCell();
header.setBackgroundColor(BaseColor.LIGHT_GRAY);
header.setBorderWidth(2);
header.setPhrase(new Phrase(columnTitle));
table.addCell(header);
});
}
The second row will consist of three cells with just text, and no extra formatting:
private void addRows(PdfPTable table) {
table.addCell("row 1, col 1");
table.addCell("row 1, col 2");
table.addCell("row 1, col 3");
}
We can also include images in cells. Furthermore, we can format each cell individually.
In this example, we’re applying horizontal and vertical alignment adjustments:
private void addCustomRows(PdfPTable table)
throws URISyntaxException, BadElementException, IOException {
Path path = Paths.get(ClassLoader.getSystemResource("Java_logo.png").toURI());
Image img = Image.getInstance(path.toAbsolutePath().toString());
img.scalePercent(10);
PdfPCell imageCell = new PdfPCell(img);
table.addCell(imageCell);
PdfPCell horizontalAlignCell = new PdfPCell(new Phrase("row 2, col 2"));
horizontalAlignCell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(horizontalAlignCell);
PdfPCell verticalAlignCell = new PdfPCell(new Phrase("row 2, col 3"));
verticalAlignCell.setVerticalAlignment(Element.ALIGN_BOTTOM);
table.addCell(verticalAlignCell);
}
3.5. Setting Table Cell Widths
At the outset, column widths determine cell widths. Therefore, we can’t set the width of individual cells directly. Instead, we need to use the setWidths() method of the PdfTable class to define the relative or absolute widths of the table columns.
While we consider these examples, remember that the unit of measurement in a PDF document is “user space units”. One unit is equal to 1/72 inch, which is approximately the same as the “point” unit used in printing.
In the first example, we set the absolute column widths. Therefore, we’ll set and lock the total table width to, say, 500 units. Then, we’ll use setWidths to define three column widths that add to 500:
private static void setAbsoluteColumnWidths(PdfPTable table) {
table.setTotalWidth(500);
table.setLockedWidth(true);
float[] columnWidths = { 100f, 200f, 200f };
table.setWidths(columnWidths);
}
Note that it’s important to both set and lock the width when working with absolute widths. If we don’t call setLockedWidth(true), iText will calculate the width based on the default width percentage and available space.
In this second example, let’s again set absolute column widths. However, this time, let’s set column widths in the call to the setTotalWidth() method itself.
We’ll set the first column to 1 inch, the second column to 2 inches, and the third column to 3 inches:
private static void setAbsoluteColumnWidthsInTableWidth(PdfPTable table) {
table.setTotalWidth(new float[] { 72f, 144f, 216f });
table.setLockedWidth(true);
}
We also have the option to set column widths relative to each other. As an example, let’s set the column widths in proportion 1:2:1. Further, let’s set the table width as 80% of page width this time:
private static void setRelativeColumnWidths(PdfPTable table) {
table.setWidths(new float[] { 1, 2, 1 });
table.setWidthPercentage(80);
}
Note how, when we need to set relative column widths, we don’t set and lock the total table width.
Finally, we have the option of setting relative widths at the time of initializing a table:
PdfPTable table = new PdfPTable(new float[] { 1, 2, 1 });
3.6. File Encryption
To apply permissions using the iText library, we need to have already created the PDF document. In our example, we’ll use our previously generated iTextHelloWorld.pdf file.
Once we load the file using PdfReader, we need to create a PdfStamper, which we’ll use to apply additional content to the file, like metadata, encryption, etc.:
PdfReader pdfReader = new PdfReader("HelloWorld.pdf");
PdfStamper pdfStamper
= new PdfStamper(pdfReader, new FileOutputStream("encryptedPdf.pdf"));
pdfStamper.setEncryption(
"userpass".getBytes(),
".getBytes(),
0,
PdfWriter.ENCRYPTION_AES_256
);
pdfStamper.close();
In our example, we encrypted the file with two passwords: the user password (“userpass”), where a user has read-only rights with no possibility to print it, and the owner password (“ownerpass”), which is used as a master key to allow a person full access to the pdf.
If we want to allow the user to print the PDF, then instead of 0 (third parameter of setEncryption), we can pass:
PdfWriter.ALLOW_PRINTING
Of course, we can mix different permissions as well, like:
PdfWriter.ALLOW_PRINTING | PdfWriter.ALLOW_COPY
Keep in mind that when using iText to set access permissions, we’re also creating a temporary pdf, which should be deleted. If we don’t delete it, it could be fully accessible to anyone.
4. Create a Pdf in PdfBox
The Apache PDFBox is an open source library for working with PDF documents.
4.1. Inserting Text
In contrast to iText, the PdfBox library provides an API based on stream manipulation. There are no classes like Chunk/Paragraph, etc. The PDDocument class is an in-memory PDF representation, where the user writes data by manipulating PDPageContentStream class.
Let’s take a look at the code example:
PDDocument document = new PDDocument();
PDPage page = new PDPage();
document.addPage(page);
PDPageContentStream contentStream = new PDPageContentStream(document, page);
contentStream.setFont(PDType1Font.COURIER, 12);
contentStream.beginText();
contentStream.showText("Hello World");
contentStream.endText();
contentStream.close();
document.save("pdfBoxHelloWorld.pdf");
document.close();
4.2. Inserting Images
Inserting images is also straightforward.
We need to load a file and create a PDImageXObject, subsequently drawing it on the document (need to provide exact x, y coordinates):
PDDocument document = new PDDocument();
PDPage page = new PDPage();
document.addPage(page);
Path path = Paths.get(ClassLoader.getSystemResource("Java_logo.png").toURI());
PDPageContentStream contentStream = new PDPageContentStream(document, page);
PDImageXObject image
= PDImageXObject.createFromFile(path.toAbsolutePath().toString(), document);
contentStream.drawImage(image, 0, 0);
contentStream.close();
document.save("pdfBoxImage.pdf");
document.close();
4.3. Inserting a Table or Setting Column Widths
PdfBox doesn’t provide any out-of-the-box methods that allow us to create tables. Since PdfBox doesn’t support tables, we also can’t set the cell width of tables. In this situation, we can draw it manually, drawing each line until our drawing resembles our desired table. Alternatively, we can use the Boxable library to create tables in PDF documents. Boxable uses the PDFBox PDF library under the hood.
4.4. File Encryption
The PdfBox library provides the ability to encrypt and adjust file permissions for the user. Compared to iText, it doesn’t require us to use an already existing file, as we simply use PDDocument. Pdf file permissions are handled by the AccessPermission class, where we can set if a user will be able to modify, extract content, or print a file.
Subsequently, we create a StandardProtectionPolicy object, which adds password-based protection to the document. We can specify two types of passwords. The user password allows the user to open a file with the applied access permissions, and the owner password has no limitations to the file:
PDDocument document = new PDDocument();
PDPage page = new PDPage();
document.addPage(page);
AccessPermission accessPermission = new AccessPermission();
accessPermission.setCanPrint(false);
accessPermission.setCanModify(false);
StandardProtectionPolicy standardProtectionPolicy
= new StandardProtectionPolicy("ownerpass", "userpass", accessPermission);
document.protect(standardProtectionPolicy);
document.save("pdfBoxEncryption.pdf");
document.close();
Our example demonstrates that if the user provides their password, the file can’t be modified or printed.
5. Conclusion
In this article, we learned how to create a PDF file in two popular Java libraries.
The code backing this article is available on GitHub. Once you're
logged in as a Baeldung Pro Member, start learning and coding on the project.