You now know what's inside a PDF and you have the InvoiceLab project set up. It's time to work with PDFBox's central class: PDDocument. In this lesson you will learn its lifecycle (and why closing it is mandatory), create a document with one page and the text "Hello, InvoiceLab", save it in several ways (file, OutputStream, byte[]) and learn how to load existing PDFs, including password-protected ones. We will finish with a very handy utility, PdfInfo, which prints a summary of any PDF and which we will reuse throughout the course to check what we generate.
Contents
- The
PDDocumentlifecycle - Creating a document and adding pages
- Writing some minimal text: "Hello, InvoiceLab"
- Saving: to a file, to an
OutputStreamand to abyte[] - Loading existing PDFs with
Loader.loadPDF - Password-protected PDFs
- Querying basic document information
- Typical exceptions and how to handle them
- The
PdfInfoutility: a summary of any PDF
The PDDocument lifecycle
A PDDocument represents a complete PDF document, whether it's new or loaded from a file. Its life always goes through the same phases:
stateDiagram-v2
[*] --> Open: new PDDocument()<br/>or Loader.loadPDF(...)
Open --> Open: add pages,<br/>draw, modify
Open --> Open: save(...)<br/>(can be saved several times)
Open --> Closed: close()
Closed --> [*]
The most important thing: a PDDocument must always be closed. While it is open it holds on to resources:
- The source file, kept open (if it was loaded from disk), which on Windows prevents it from being deleted or overwritten.
- In-memory (or temporary on-disk) buffers holding the document's streams.
- References to fonts and images.
If you forget to close it, PDFBox logs a warning (Warning: You did not close a PDF Document) when the garbage collector detects it, and on a server that generates thousands of documents you will end up with memory or file-descriptor leaks.
The correct way in modern Java is try-with-resources, because PDDocument implements Closeable:
try (PDDocument document = new PDDocument()) {
// ... work with the document ...
document.save("output/example.pdf");
} // document.close() is called automatically here, even if an exception occursGolden rules of the lifecycle:
| Rule | Reason |
|---|---|
Open the document in a try-with-resources |
Guarantees close() even when errors occur |
| Save before closing | After close() the document can no longer be used |
Don't return a PDDocument from a method without making it clear who closes it |
It's the most common cause of leaks |
Don't share a PDDocument between threads |
It isn't thread-safe; each thread must use its own document |
| Don't save over the same file you have open | The file is being read while it's being written; save to another file and then rename it (we will see this in module 4) |
Creating a document and adding pages
A new document is empty: it has no pages at all. A PDF with no pages isn't valid for most viewers, so we will always add at least one.
try (PDDocument document = new PDDocument()) {
PDPage page = new PDPage(PDRectangle.A4); // portrait A4 page
document.addPage(page); // append it to the end of the document
System.out.println(document.getNumberOfPages()); // 1
}new PDPage()with no arguments creates a Letter-sized page (US Letter, 612 × 792 points). In Spain, as in most of the world, we want A4, so we passPDRectangle.A4(about 595 × 842 points).PDRectanglehas constants for common sizes:A4,A5,A3,LETTER,LEGAL… The coordinate system and units are explained in lesson 02-01.addPageappends the page to the end. Operations such as inserting, removing or reordering pages are covered in module 4.
Writing some minimal text: "Hello, InvoiceLab"
To draw on a page you use a content stream, PDPageContentStream. Remember the stream from the hand-written PDF in the previous lesson (BT /F1 24 Tf 72 770 Td (Hello, InvoiceLab) Tj ET): PDPageContentStream generates exactly those operators for you, and it also registers the font in the page's resources.
Here we'll cover only the bare essentials; lesson 02-02 explains it in depth. Create com.invoicelab.examples.HelloInvoiceLab:
package com.invoicelab.examples;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.apache.pdfbox.pdmodel.font.Standard14Fonts;
public class HelloInvoiceLab {
public static void main(String[] args) throws IOException {
Files.createDirectories(Path.of("output"));
try (PDDocument document = new PDDocument()) {
PDPage page = new PDPage(PDRectangle.A4);
document.addPage(page);
// Standard Helvetica Bold font (PDFBox 3 API)
PDType1Font helveticaBold = new PDType1Font(Standard14Fonts.FontName.HELVETICA_BOLD);
try (PDPageContentStream content = new PDPageContentStream(document, page)) {
content.beginText(); // BT
content.setFont(helveticaBold, 24); // /F1 24 Tf
content.newLineAtOffset(72, 770); // 72 770 Td
content.showText("Hello, InvoiceLab"); // (Hello, InvoiceLab) Tj
content.endText(); // ET
} // the content stream is closed BEFORE saving
document.save("output/hello-invoicelab.pdf");
}
}
}Step by step:
new PDType1Font(Standard14Fonts.FontName.HELVETICA_BOLD)creates one of the 14 standard PDF fonts. In PDFBox 2.x you wrotePDType1Font.HELVETICA_BOLD; that constant no longer exists in 3.x.new PDPageContentStream(document, page)opens a stream for drawing on the page. This constructor replaces any existing content on the page; in module 4 we will see how to add content without erasing it.beginText()/endText()delimit a text block. EveryshowTextmust sit between the two.setFont(font, size)is mandatory before the firstshowText; if you forget it, PDFBox throws an exception.newLineAtOffset(72, 770)places the text cursor 72 points from the left edge and 770 points from the bottom edge (in PDF, the origin is at the bottom left).showText(...)writes the string. With the standard fonts only characters from the WinAnsi encoding are allowed (enough for Western European languages, including Spanish: á, é, ñ, ¿, €…), but not for other alphabets; the solution, using TrueType fonts, is in lesson 02-03.- The
PDPageContentStreamis also opened in atry-with-resources. It must be closed beforesave: otherwise the content isn't written in full and the page may come out blank.
Saving: to a file, to an OutputStream and to a byte[]
PDDocument offers several save overloads. They all produce the same PDF; only the destination changes.
| Method | When to use it |
|---|---|
save(String path) |
Scripts and quick examples |
save(File file) |
When you're already working with File or Path (path.toFile()) |
save(OutputStream out) |
Sending the PDF to an HTTP response, a ZIP file, cloud storage… |
save(..., CompressParameters) |
Controlling structure compression (we'll use it for debugging in 01-05) |
To get a byte[] (for example, to store it in a database or attach it to an email), combine save(OutputStream) with a ByteArrayOutputStream:
public static byte[] toBytes(PDDocument document) throws IOException {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
document.save(buffer); // writes the complete PDF to memory
return buffer.toByteArray(); // copies the bytes into an array
}And to write to an OutputStream that you manage yourself:
Details to bear in mind:
save(OutputStream)does not close the stream you pass it; close it yourself (again, withtry-with-resources).- You can call
saveseveral times on the same document (for example, to save the same PDF both to disk and to memory). - By default, PDFBox 3 saves with object compression (object streams), which requires PDF 1.5 or later. That's why, even though a new document starts out as version 1.4, after saving it you will usually see that its header is
%PDF-1.6. This is expected.
Loading existing PDFs with Loader.loadPDF
In PDFBox 3, documents are loaded with the static methods of the org.apache.pdfbox.Loader class. (In 2.x you used PDDocument.load(...), which no longer exists.)
| Source | Call | Comment |
|---|---|---|
| File | Loader.loadPDF(new File("path.pdf")) |
The most efficient option: reads from disk on demand |
| Byte array | Loader.loadPDF(bytes) |
When the PDF is already in memory (DB, HTTP request) |
RandomAccessRead |
Loader.loadPDF(new RandomAccessReadBufferedFile(path)) |
PDFBox 3's general-purpose reading interface (pdfbox-io module) |
InputStream |
Loader.loadPDF(new RandomAccessReadBuffer(inputStream)) |
There's no direct InputStream overload: you wrap it |
Examples of each:
// 1. From a file
try (PDDocument doc = Loader.loadPDF(new File("output/hello-invoicelab.pdf"))) {
System.out.println("Pages: " + doc.getNumberOfPages());
}
// 2. From a byte[] (for example, read from a database)
byte[] bytes = Files.readAllBytes(Path.of("output/hello-invoicelab.pdf"));
try (PDDocument doc = Loader.loadPDF(bytes)) {
System.out.println("Pages: " + doc.getNumberOfPages());
}
// 3. From a RandomAccessRead over a file
try (PDDocument doc = Loader.loadPDF(
new RandomAccessReadBufferedFile(Path.of("output/hello-invoicelab.pdf")))) {
System.out.println("Pages: " + doc.getNumberOfPages());
}
// 4. From an InputStream (for example, a classpath resource)
try (InputStream in = HelloInvoiceLab.class.getResourceAsStream("/templates/contract.pdf");
PDDocument doc = Loader.loadPDF(new RandomAccessReadBuffer(in))) {
System.out.println("Pages: " + doc.getNumberOfPages());
}Notes:
- The
RandomAccessReadBufferedFileandRandomAccessReadBufferclasses live in theorg.apache.pdfbox.iopackage. - When you close the
PDDocument, PDFBox also closes the sourceRandomAccessRead, so you don't need to close it separately. RandomAccessReadBuffer(InputStream)reads the entire stream into memory. For very large PDFs it's better to load from a file; memory management is covered in lesson 08-03.- In example 4,
contract.pdfis a hypothetical resource: ifgetResourceAsStreamreturnsnull, the constructor will fail with aNullPointerException. In real code, check for it first.
Password-protected PDFs
A PDF can be encrypted with two passwords (we will create the encryption itself in lesson 07-01):
- User password: required to open the document.
- Owner password: grants full permissions (print, copy, modify…).
Every loadPDF variant has an overload that takes the password as its second parameter:
try (PDDocument doc = Loader.loadPDF(new File("output/protected-contract.pdf"), "thePassword")) {
System.out.println("Encrypted? " + doc.isEncrypted()); // true
System.out.println("Can print? " + doc.getCurrentAccessPermission().canPrint());
}- If the PDF only has an owner password (very common: "you can open it, but not copy from it"), PDFBox opens it without a password, because the user password is the empty string.
- If it has a user password and you don't provide it (or it's wrong), an
InvalidPasswordExceptionis thrown. getCurrentAccessPermission()tells you what the password used to open the document allows you to do. If you open it with the owner password, you get every permission.
Querying basic document information
Once a document is loaded, you can easily query its main characteristics:
| Method | Returns |
|---|---|
getNumberOfPages() |
Number of pages |
getVersion() |
PDF version as a float (1.4, 1.7, 2.0…) |
isEncrypted() |
Whether the document is encrypted |
getPage(int index) |
A specific page (index starting at 0) |
getPages() |
All the pages, iterable with a for loop |
getDocumentInformation() |
Basic metadata: title, author, producer, dates… (PDDocumentInformation) |
getDocumentCatalog() |
The catalog (the document root, lesson 01-03) |
The PDDocumentInformation metadata may be null if whoever created the PDF didn't fill it in. Incidentally, PDFBox does not fill in the Producer field automatically; if you want your PDFs to say "InvoiceLab", you'll have to do it yourself (we'll see how in lesson 04-06).
Typical exceptions and how to handle them
| Exception | When it occurs | What to do |
|---|---|---|
InvalidPasswordException (org.apache.pdfbox.pdmodel.encryption) |
PDF encrypted with a user password that isn't provided or is wrong | Ask for the password or reject the document with a clear message |
IOException with a parsing message |
The file isn't a PDF or is badly damaged (for example, a truncated download) | Log the error and reject the file |
FileNotFoundException / NoSuchFileException |
The path doesn't exist | Validate the path beforehand |
IllegalStateException |
Using a PDPageContentStream incorrectly (e.g. showText without setFont) |
Check the order of operations |
IllegalArgumentException |
Writing a character the font doesn't support with showText |
Use a TrueType font (lesson 02-03) |
Since InvalidPasswordException extends IOException, if you want to handle it differently you must catch it first:
try (PDDocument doc = Loader.loadPDF(file, password)) {
// ...
} catch (InvalidPasswordException e) { // the most specific one first
System.err.println("Wrong password");
} catch (IOException e) { // then the general one
System.err.println("Unreadable or damaged PDF: " + e.getMessage());
}PDFBox is quite forgiving: many PDFs with minor defects (incorrect xref offsets, for example) still load, because the parser rebuilds the structure. You'll only get the exception when the file is beyond repair.
The PdfInfo utility: a summary of any PDF
Let's put it all together in a tool we will use often to check InvoiceLab's PDFs. Create com.invoicelab.examples.PdfInfo:
package com.invoicelab.examples;
import java.io.File;
import java.io.IOException;
import java.util.Calendar;
import org.apache.pdfbox.Loader;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDDocumentInformation;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.encryption.InvalidPasswordException;
/**
* Prints a summary of a PDF.
* Usage: PdfInfo <file.pdf> [password]
*/
public class PdfInfo {
public static void main(String[] args) {
if (args.length == 0) {
System.err.println("Usage: PdfInfo <file.pdf> [password]");
System.exit(1);
}
File file = new File(args[0]);
String password = args.length > 1 ? args[1] : "";
try {
printSummary(file, password);
} catch (InvalidPasswordException e) {
System.err.println("The PDF is protected and the password is not valid: " + e.getMessage());
System.exit(2);
} catch (IOException e) {
System.err.println("Could not read the PDF (does it exist, or is it damaged?): " + e.getMessage());
System.exit(3);
}
}
public static void printSummary(File file, String password) throws IOException {
try (PDDocument document = Loader.loadPDF(file, password)) {
PDDocumentInformation info = document.getDocumentInformation();
System.out.println("=== " + file.getName() + " ===");
System.out.printf("File size : %,d bytes%n", file.length());
System.out.println("PDF version : " + document.getVersion());
System.out.println("Pages : " + document.getNumberOfPages());
System.out.println("Encrypted : " + (document.isEncrypted() ? "yes" : "no"));
System.out.println("Title : " + value(info.getTitle()));
System.out.println("Author : " + value(info.getAuthor()));
System.out.println("Producer : " + value(info.getProducer()));
System.out.println("Created : " + date(info.getCreationDate()));
int number = 1;
for (PDPage page : document.getPages()) {
PDRectangle box = page.getMediaBox();
System.out.printf(" Page %d: %.0f x %.0f pt (%.0f x %.0f mm), rotation %d%n",
number++, box.getWidth(), box.getHeight(),
box.getWidth() * 25.4 / 72, box.getHeight() * 25.4 / 72,
page.getRotation());
}
}
}
private static String value(String text) {
return (text == null || text.isBlank()) ? "(not set)" : text;
}
private static String date(Calendar calendar) {
return calendar == null ? "(not set)" : calendar.toInstant().toString();
}
}How it works:
mainvalidates the arguments and keeps the logic (printSummary) separate from the error handling. That way we can reuseprintSummaryfrom other classes and from tests.- The default password is the empty string
"", which is equivalent to "no user password". - The exit codes (
System.exit(2),System.exit(3)) let you use it in scripts and tell the kind of error apart. getMediaBox()returns aPDRectanglewith the size in points. To convert to millimetres: 1 point = 1/72 of an inch and 1 inch = 25.4 mm, hence× 25.4 / 72.getRotation()returns the page's display rotation (0, 90, 180 or 270).- The
valueanddatemethods avoid printingnull.
Run it on the PDF we've just generated:
mvn compile exec:java -Dexec.mainClass=com.invoicelab.examples.PdfInfo \
-Dexec.args="output/hello-invoicelab.pdf"Output (approximate):
=== hello-invoicelab.pdf ===
File size : 959 bytes
PDF version : 1.6
Pages : 1
Encrypted : no
Title : (not set)
Author : (not set)
Producer : (not set)
Created : (not set)
Page 1: 595 x 842 pt (210 x 297 mm), rotation 0Also try it with output/minimal-by-hand.pdf from the previous lesson, with a file that doesn't exist and with a file that isn't a PDF (for example, pom.xml) to see how it responds to each error.
Common Mistakes and Tips
- Using
PDDocument.load(...)orPDType1Font.HELVETICA. These are PDFBox 2.x APIs. In 3.x:Loader.loadPDF(...)andnew PDType1Font(Standard14Fonts.FontName.HELVETICA). - Not closing the
PDPageContentStreambeforesave. The result: a blank page or a damaged PDF. Always use nestedtry-with-resourcesblocks as inHelloInvoiceLab. - Forgetting to
close()the document. The warning "You did not close a PDF Document" appears and memory leaks. - Catching
IOExceptionbeforeInvalidPasswordException. The compiler rejects it (the secondcatchwould be unreachable); order them from most specific to most general. - Page indexes starting at 1.
getPage(0)is the first page;getPage(getNumberOfPages())throws anIndexOutOfBoundsException. - Saving to the same path as the loaded file. It can corrupt the result. Save to a different file.
- Tip: reuse font instances within the same document instead of creating a new one on every page.
Exercises
Exercise 1. Create com.invoicelab.examples.HelloMultiplePages, which generates output/hello-3-pages.pdf with three A4 pages. Each page must display the text "Hello, InvoiceLab - page N" (N = 1, 2, 3). Then check it with PdfInfo.
Exercise 2. Write a static byte[] generateHello() method that creates the "Hello, InvoiceLab" PDF in memory only and returns its bytes. Then, in main, load those bytes back with Loader.loadPDF(byte[]) and print the number of pages and the version, without writing anything to disk.
Exercise 3. Modify PdfInfo so that it accepts several files as arguments (without a password) and prints the summary of each one. If one fails, it must display the error and carry on with the next.
Solutions
Solution 1.
package com.invoicelab.examples;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.apache.pdfbox.pdmodel.font.Standard14Fonts;
public class HelloMultiplePages {
public static void main(String[] args) throws IOException {
Files.createDirectories(Path.of("output"));
try (PDDocument document = new PDDocument()) {
PDType1Font font = new PDType1Font(Standard14Fonts.FontName.HELVETICA); // a single instance
for (int n = 1; n <= 3; n++) {
PDPage page = new PDPage(PDRectangle.A4); // a new page each time
document.addPage(page);
try (PDPageContentStream content = new PDPageContentStream(document, page)) {
content.beginText();
content.setFont(font, 18);
content.newLineAtOffset(72, 770);
content.showText("Hello, InvoiceLab - page " + n);
content.endText();
}
}
document.save("output/hello-3-pages.pdf");
}
}
}Common mistake: opening the PDPageContentStream just once outside the loop. Each content stream belongs to one specific page, so you need to open one per page. This text happens to be plain ASCII, but accented characters such as the "á" in the Spanish word "página" would work too: Helvetica with WinAnsi encoding handles them without any trouble.
Solution 2.
static byte[] generateHello() throws IOException {
try (PDDocument document = new PDDocument()) {
PDPage page = new PDPage(PDRectangle.A4);
document.addPage(page);
try (PDPageContentStream content = new PDPageContentStream(document, page)) {
content.beginText();
content.setFont(new PDType1Font(Standard14Fonts.FontName.HELVETICA_BOLD), 24);
content.newLineAtOffset(72, 770);
content.showText("Hello, InvoiceLab");
content.endText();
}
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
document.save(buffer);
return buffer.toByteArray();
} // the document is closed here, but the bytes have already been copied
}
public static void main(String[] args) throws IOException {
byte[] pdf = generateHello();
try (PDDocument reloaded = Loader.loadPDF(pdf)) {
System.out.println("Bytes: " + pdf.length);
System.out.println("Pages: " + reloaded.getNumberOfPages());
System.out.println("Version: " + reloaded.getVersion());
}
}Add the imports for java.io.ByteArrayOutputStream and org.apache.pdfbox.Loader. This "generate in memory and return a byte[]" pattern is exactly the one we will use in the REST service in module 8.
Solution 3.
public static void main(String[] args) {
if (args.length == 0) {
System.err.println("Usage: PdfInfo <file1.pdf> [file2.pdf ...]");
System.exit(1);
}
for (String path : args) {
try {
printSummary(new File(path), "");
} catch (InvalidPasswordException e) {
System.err.println(path + ": password-protected");
} catch (IOException e) {
System.err.println(path + ": could not be read (" + e.getMessage() + ")");
}
System.out.println();
}
}By catching the exceptions inside the loop, a bad file doesn't stop the rest from being processed. Since printSummary uses try-with-resources, each document is closed even if it fails halfway through.
Conclusion
You've now mastered the PDDocument lifecycle: create or load, work, save and always close with try-with-resources. You have generated your first PDF with text, saved it to a file, to an OutputStream and to memory, and loaded documents with Loader.loadPDF from different sources, including password-protected PDFs. You also know how to tell the typical exceptions apart and handle them, and InvoiceLab now has the PdfInfo utility for inspecting any document.
But PdfInfo only shows a summary. What do you do when a PDF comes out blank, a font doesn't appear or a viewer shows something other than what you expected? In the next lesson we'll get to know the debugging tools: PDFDebugger, for looking inside the COS tree, and the PDFBox command line, for extracting, rendering or merging documents without writing any code.
PDF Generation and Editing with Apache PDFBox
Module 1: PDF and PDFBox Fundamentals
- The PDF Format and Apache PDFBox
- Setting Up the Project with PDFBox 3
- Anatomy of a PDF: COS Objects, Pages and Resources
- Your First PDF: Creating, Saving and Loading Documents
- Debugging Tools: PDFDebugger and the Command Line
Module 2: Generating Content
- Pages and the Coordinate System
- Writing Text with PDPageContentStream and Standard Fonts
- Embedded TrueType Fonts and Unicode
- Text Layout: Measuring, Aligning and Wrapping Lines
- Vector Graphics: Lines, Shapes and Colours
- Inserting Images
Module 3: Business Documents
- Building Tables from Scratch
- Multi-Page Documents: Pagination, Headers and Footers
- Barcodes and QR Codes
- Designing a Reusable Document Generator
- Project: the Complete Invoice
Module 4: Editing Existing PDFs
- Load, Modify and Save: Full and Incremental Saves
- Adding Content to Existing Pages: Stamps and Watermarks
- Page Manipulation: Inserting, Removing, Rotating and Reordering
- Merging and Splitting Documents
- Overlays, Layers and Optional Content
- Document Metadata: Info and XMP
Module 5: AcroForm Forms
- Introduction to AcroForm Forms
- Reading and Filling In Forms
- Creating Forms Programmatically
- Form Appearances and Flattening
Module 6: Extraction and Analysis
- Extracting Text with PDFTextStripper
- Area-Based Extraction and Text Positions
- Extracting Images and Resources
- Rendering Pages to Images
- Bookmarks, Links and Annotations
Module 7: Security and Digital Signatures
- Encryption and Permissions
- Digital Signatures: Concepts and PDF Structure
- Signing Documents with PDFBox and Bouncy Castle
- Verifying Signatures and Visible Signatures
