Before writing a single line of PDF, we need a properly set-up project: the right PDFBox dependency, the right Java version, a clear folder structure and logging that doesn't flood the console with messages. In this lesson we will create the InvoiceLab project from scratch (it will be the foundation of the whole course) and check that it works with a small class that prints the PDFBox version and generates an empty PDF. Spending a few minutes getting this right will save you a lot of "it doesn't compile" or "class not found" headaches later on.
Contents
- Prerequisites
- Creating the InvoiceLab Maven project
- The complete
pom.xml, explained - Alternative: the same project with Gradle
- Project folder structure
- Dependencies coming later
- Logging: how to configure or silence PDFBox messages
- Checking the installation
- Dependency differences between PDFBox 2.x and 3.x
Prerequisites
| Tool | Minimum version | How to check |
|---|---|---|
| JDK | 17 | java -version and javac -version |
| Maven | 3.8 or later | mvn -version |
| IDE (optional) | IntelliJ IDEA, Eclipse or VS Code with the Java extension | — |
| PDF viewer | Any (your system's, Acrobat Reader, your browser) | — |
PDFBox 3 runs on Java 8 and later, but in this course we will use Java 17 (an LTS release) so we can take advantage of modern syntax such as var, text blocks and record.
Creating the InvoiceLab Maven project
You can create the project from your IDE ("New Maven Project") or from the command line with Maven's basic archetype:
mvn archetype:generate \
-DgroupId=com.invoicelab \
-DartifactId=invoicelab \
-DarchetypeArtifactId=maven-archetype-quickstart \
-DarchetypeVersion=1.4 \
-DinteractiveMode=false
cd invoicelabgroupIdidentifies the organization: we will usecom.invoicelab.artifactIdis the name of the project and of the folder that gets created:invoicelab.maven-archetype-quickstartgenerates a minimal Java project with anAppclass and a test.-DinteractiveMode=falsestops Maven from asking questions.
The archetype generates a pom.xml with old versions of Java and JUnit. We will replace it entirely in the next section. You can also delete the generated App.java class and its test.
The complete pom.xml, explained
This is the InvoiceLab pom.xml. Replace the contents of the generated file with this:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.invoicelab</groupId>
<artifactId>invoicelab</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>jar</packaging>
<name>InvoiceLab</name>
<description>PDF document generation and modification for Nebula Distribution Ltd.</description>
<properties>
<maven.compiler.release>17</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<pdfbox.version>3.0.5</pdfbox.version>
</properties>
<dependencies>
<!-- PDFBox core: pulls in pdfbox-io, fontbox and commons-logging -->
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>${pdfbox.version}</version>
</dependency>
<!-- Testing (we will use it seriously in module 8) -->
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>5.10.2</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.13.0</version>
<configuration>
<release>${maven.compiler.release}</release>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.2.5</version>
</plugin>
<!-- Optional: run main classes with "mvn exec:java" -->
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>3.5.0</version>
<configuration>
<mainClass>com.invoicelab.examples.CheckInstallation</mainClass>
</configuration>
</plugin>
</plugins>
</build>
</project>Let's go over the important parts:
<properties>maven.compiler.release=17: compiles for Java 17. Thereleaseoption (instead of the oldsource/targetpair) also prevents you from accidentally using APIs from newer JDK versions.project.build.sourceEncoding=UTF-8: essential in a project that handles non-ASCII text such as Spanish company data. Without it, strings like"€"or"ñ"in the source code could be compiled with the wrong encoding.pdfbox.version: we centralize the version in a property. That way, when we add other PDFBox modules (all of which must be on the same version), we only have to change it in one place. We use3.0.5; any later 3.0.x is compatible, and it's a good idea to use the latest release of the 3.0 branch the project publishes, since these usually include security fixes.
pdfboxdependency: the only one we need for now. Maven automatically downloads its transitive dependencies (pdfbox-io,fontboxandcommons-logging).maven-compiler-plugin: pins a modern compiler version and appliesrelease 17.exec-maven-plugin: lets us run a class with amainmethod without packaging anything:
mvn compile exec:java # runs the configured mainClass
mvn compile exec:java -Dexec.mainClass=com.invoicelab.examples.AnotherClass # any other classTo see which dependencies Maven has actually pulled in, use:
The output will look something like this (exact versions may vary):
[INFO] com.invoicelab:invoicelab:jar:1.0.0-SNAPSHOT
[INFO] +- org.apache.pdfbox:pdfbox:jar:3.0.5:compile
[INFO] | +- org.apache.pdfbox:pdfbox-io:jar:3.0.5:compile
[INFO] | +- org.apache.pdfbox:fontbox:jar:3.0.5:compile
[INFO] | \- commons-logging:commons-logging:jar:1.3.5:compile
[INFO] \- org.junit.jupiter:junit-jupiter:jar:5.10.2:testNotice that pdfbox-io and fontbox have the same version as pdfbox. This is crucial: mixing versions of PDFBox modules leads to strange runtime errors such as NoSuchMethodError.
Alternative: the same project with Gradle
If your team uses Gradle, the equivalent build.gradle.kts (Kotlin DSL) is:
plugins {
java
application
}
group = "com.invoicelab"
version = "1.0.0-SNAPSHOT"
java {
toolchain {
languageVersion.set(JavaLanguageVersion.of(17))
}
}
repositories {
mavenCentral()
}
val pdfboxVersion = "3.0.5"
dependencies {
implementation("org.apache.pdfbox:pdfbox:$pdfboxVersion")
testImplementation("org.junit.jupiter:junit-jupiter:5.10.2")
testRuntimeOnly("org.junit.platform:junit-platform-launcher")
}
application {
mainClass.set("com.invoicelab.examples.CheckInstallation")
}
tasks.withType<JavaCompile> {
options.encoding = "UTF-8"
}
tasks.test {
useJUnitPlatform()
}toolchainmakes Gradle use (or download) a JDK 17 even if you have a different one installed.implementation(...)is the equivalent of Maven'scompilescope.- The
applicationplugin lets you run the project with./gradlew run.
For the rest of the course, configuration examples will be given in Maven, but translating them to Gradle is always this straightforward.
Project folder structure
This is the structure we are establishing for InvoiceLab. Create any missing folders now, even if they are empty:
invoicelab/
├── pom.xml
├── output/ ← generated PDFs (NOT committed to the repository)
├── src/
│ ├── main/
│ │ ├── java/
│ │ │ └── com/invoicelab/
│ │ │ └── examples/ ← example classes from each lesson
│ │ └── resources/
│ │ ├── fonts/ ← TrueType fonts (.ttf) — module 2
│ │ └── img/ ← logo and other images — module 2
│ └── test/
│ └── java/
│ └── com/invoicelab/ ← automated tests — module 8
└── .gitignore| Folder | Contents | Why there |
|---|---|---|
output/ |
Every PDF we generate | Keeps generated files separate from source code; it can be deleted safely |
src/main/resources/fonts/ |
.ttf files |
They are packaged inside the JAR and read as classpath resources |
src/main/resources/img/ |
logo-nebula.png, etc. |
Same as the fonts |
com.invoicelab.examples |
Standalone classes with main |
Each lesson's experiments, kept apart from "production" code |
Other packages will appear later, such as com.invoicelab.model (for Invoice, InvoiceLine and Customer) or com.invoicelab.pdf (for our generators), but we won't get ahead of ourselves.
Add a minimal .gitignore so that PDFs and compiled files are not committed to the repository:
Important: relative paths such as
output/invoice.pdfare resolved against the Java process's working directory. Withmvn exec:javathat is the project root; in your IDE, make sure the run configuration also uses the project root.
Dependencies coming later
Don't add these yet; this is just so you know what's coming and why:
| Dependency | What for | Module |
|---|---|---|
org.apache.pdfbox:pdfbox-tools |
Command-line utilities, also reusable from code | 1 (lesson 01-05, as an executable JAR) |
org.apache.pdfbox:xmpbox |
XMP metadata | 4 and 8 |
org.apache.pdfbox:preflight |
PDF/A validation | 8 |
org.bouncycastle:bcprov-jdk18on and bcpkix-jdk18on |
Cryptography for AES-256 encryption and digital signatures | 7 |
| A barcode/QR library (e.g. ZXing) | Generating QR codes on invoices | 3 |
All the PDFBox ones will be declared with ${pdfbox.version} to keep the versions aligned.
Logging: how to configure or silence PDFBox messages
PDFBox logs warnings (fonts it can't find, damaged structures it repairs, and so on) through Apache Commons Logging. Commons Logging doesn't write anything by itself: it is a facade that delegates to whatever logging system it finds. The 1.3.x versions, which come with PDFBox 3, look for them in this order:
- Log4j 2 (if
log4j-apiis on the classpath). - SLF4J (if present, together with Logback,
slf4j-simple, etc.). - If neither is found, java.util.logging (JUL), the logging built into the JDK.
Our minimal project has neither Log4j nor SLF4J, so JUL is used, which by default prints messages of level INFO or higher to the console (stderr).
Option A: adjusting the level with java.util.logging
Create src/main/resources/logging.properties:
handlers = java.util.logging.ConsoleHandler
.level = INFO
java.util.logging.ConsoleHandler.level = ALL
# Only severe errors from PDFBox and FontBox
org.apache.pdfbox.level = SEVERE
org.apache.fontbox.level = SEVEREJUL doesn't read this file from the classpath automatically; you have to load it at startup. The simplest way, from code:
try (var in = CheckInstallation.class.getResourceAsStream("/logging.properties")) {
if (in != null) {
java.util.logging.LogManager.getLogManager().readConfiguration(in);
}
}Alternatively, from the command line, with -Djava.util.logging.config.file=src/main/resources/logging.properties.
Option B: using SLF4J (common in Spring Boot applications)
If your application already uses SLF4J + Logback (as Spring Boot does), Commons Logging 1.3 detects it and PDFBox will write to your usual logs. All you need to do is set the package level:
<!-- logback.xml -->
<logger name="org.apache.pdfbox" level="WARN"/>
<logger name="org.apache.fontbox" level="WARN"/>Option C: silencing everything (experiments only)
Don't do this in production: PDFBox's warnings often explain why a supplier's PDF renders badly or why a character is missing.
Checking the installation
Create the class src/main/java/com/invoicelab/examples/CheckInstallation.java:
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.common.PDRectangle;
import org.apache.pdfbox.util.Version;
/**
* Checks that PDFBox is correctly configured in InvoiceLab:
* prints the version and generates a PDF with a blank A4 page.
*/
public class CheckInstallation {
public static void main(String[] args) throws IOException {
// 1. The PDFBox version actually on the classpath
System.out.println("PDFBox version: " + Version.getVersion());
System.out.println("Java version: " + System.getProperty("java.version"));
// 2. Make sure the output folder exists
Path outputFolder = Path.of("output");
Files.createDirectories(outputFolder);
// 3. Create a document with an empty A4 page and save it
Path target = outputFolder.resolve("check.pdf");
try (PDDocument document = new PDDocument()) {
document.addPage(new PDPage(PDRectangle.A4));
document.save(target.toFile());
}
System.out.println("PDF generated at: " + target.toAbsolutePath());
}
}Step-by-step explanation:
Version.getVersion()(packageorg.apache.pdfbox.util) returns the PDFBox version read from the JAR itself. It is very useful for detecting whether a dependency conflict is causing a different version from the one you declared to be loaded.Files.createDirectories(...)createsoutput/if it doesn't exist (and doesn't fail if it already does). Without it,savewould throw anIOExceptionbecause it can't create a file in a folder that doesn't exist.new PDDocument()creates an empty document in memory.new PDPage(PDRectangle.A4)creates an A4-sized page (roughly 595 × 842 points; we will study units in module 2).document.save(File)writes the PDF. There are also variants that take aStringor anOutputStream(lesson 01-04).try-with-resourcesguarantees thatclose()is called even if something goes wrong.
Run it:
Expected output (versions may vary):
PDFBox version: 3.0.5
Java version: 17.0.12
PDF generated at: /home/user/projects/invoicelab/output/check.pdfOpen output/check.pdf: you should see a blank A4 page. If you do, the project is ready.
Dependency differences between PDFBox 2.x and 3.x
If you maintain older projects, or copy configuration from other projects, bear in mind these dependency-level differences. API changes (such as Loader.loadPDF) will come up throughout the course, and the full migration is covered in lesson 08-06.
| Aspect | PDFBox 2.0.x | PDFBox 3.0.x |
|---|---|---|
| Minimum Java | 6 | 8 |
| I/O module | Included in pdfbox |
New pdfbox-io module (pulled in transitively) |
| Tools JAR | pdfbox-tools with standalone classes |
pdfbox-tools based on picocli (subcommands) |
| Bouncy Castle | -jdk15on artifacts |
-jdk18on artifacts |
| Logging | Commons Logging 1.2 | Commons Logging 1.3.x (detects Log4j 2/SLF4J) |
| Mixing versions | — | Never mix 2.x and 3.x modules on the same classpath |
A typical symptom of mixed versions is code that compiles but fails at runtime with NoSuchMethodError or ClassNotFoundException. mvn dependency:tree and Version.getVersion() are your best friends for diagnosing it.
Common Mistakes and Tips
- Not setting the UTF-8 encoding. It causes
"€"to show up as"€". Always keepproject.build.sourceEncodingset toUTF-8. - Different versions across PDFBox modules. If you add
xmpbox3.0.5 alongsidepdfbox3.0.3, you'll run into trouble. Always use the${pdfbox.version}property. - An old dependency drags in PDFBox 2.x. Some libraries (for example, older versions of Apache Tika) depend on PDFBox 2. Check
mvn dependency:treeand, if necessary, use<exclusions>or<dependencyManagement>to force 3.x. IOExceptionwhen saving. It is almost always because theoutput/folder doesn't exist or because the PDF is open in a viewer that locks the file (common on Windows).- Can't find the generated PDF. Check the working directory of your run; printing
toAbsolutePath()as in the example settles the question. - Tip: save source code as UTF-8 in your IDE too (in Eclipse: Window → Preferences → General → Workspace → Text file encoding).
Exercises
Exercise 1. Modify CheckInstallation so that it generates a document with three blank A4 pages, saved as output/three-pages.pdf, and prints to the console how many pages the document has before saving it (hint: PDDocument has a getNumberOfPages() method).
Exercise 2. Add the xmpbox dependency to the pom.xml (we won't use it yet) so that its version always stays aligned with pdfbox's. Then run mvn dependency:tree and check that all the PDFBox modules share the same version.
Exercise 3. Configure JUL so that PDFBox messages are only shown from level WARNING upwards, loading the logging.properties file from the classpath at the start of main.
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.common.PDRectangle;
public class ThreePages {
public static void main(String[] args) throws IOException {
Files.createDirectories(Path.of("output"));
try (PDDocument document = new PDDocument()) {
for (int i = 0; i < 3; i++) {
document.addPage(new PDPage(PDRectangle.A4)); // a new page on each iteration
}
System.out.println("Pages: " + document.getNumberOfPages()); // Pages: 3
document.save("output/three-pages.pdf");
}
}
}Common mistake: creating a single PDPage object and adding it three times. Each page must be a separate object; adding the same instance several times produces an inconsistent page tree.
Solution 2. Inside <dependencies>:
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>xmpbox</artifactId>
<version>${pdfbox.version}</version>
</dependency>When you run mvn dependency:tree you will see pdfbox, pdfbox-io, fontbox and xmpbox all on the same version. If you change pdfbox.version to another 3.0.x, they all change together.
Solution 3. The file src/main/resources/logging.properties:
handlers = java.util.logging.ConsoleHandler
java.util.logging.ConsoleHandler.level = ALL
org.apache.pdfbox.level = WARNING
org.apache.fontbox.level = WARNINGAnd at the start of main:
try (var in = CheckInstallation.class.getResourceAsStream("/logging.properties")) {
if (in != null) {
java.util.logging.LogManager.getLogManager().readConfiguration(in);
} else {
System.err.println("logging.properties not found on the classpath");
}
}The leading slash in "/logging.properties" indicates that the resource is at the root of the classpath (that is, directly in src/main/resources/). It is important to load the configuration before using any PDFBox class, because the loggers are created when the classes are initialized.
Conclusion
The InvoiceLab project is now ready: a pom.xml with PDFBox 3 and Java 17, the PDFBox version centralized in a property, a folder structure with output/, fonts/ and img/, logging under control and a CheckInstallation class that proves everything works. You also know which dependencies will be added along the way and how to avoid the most common version conflicts.
We have generated a PDF, but we don't yet know what's inside that file. In the next lesson we will open the "black box": we will study the anatomy of a PDF, its COS objects, the page tree and resources, and we will write a minimal PDF by hand to understand every byte.
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
