Almost every business application ends up producing PDFs: invoices, delivery notes, contracts, certificates, monthly reports... And sooner or later it also has to read or modify them: stamp a "PAID" mark, merge several documents into one, fill in an official form, or pull the amount out of an invoice that arrives by email. In this first lesson you will learn what a PDF really is, why it is so different from a Word document or an HTML page, and what role Apache PDFBox plays: the open-source Java library we will use throughout the course. You will also meet InvoiceLab, the project we will build lesson by lesson.
Contents
- What a PDF is: a brief history and standardization
- A presentation format, not an editing format
- Typical PDF use cases on the backend
- What Apache PDFBox is
- The PDFBox modules
- What PDFBox can do… and what it can't
- PDFBox compared with the alternatives
- The course project: InvoiceLab
- A first look at the code
What a PDF is: a brief history and standardization
PDF (Portable Document Format) was born at Adobe in the early 1990s with a very specific goal: a document should look exactly the same on any computer, operating system or printer, regardless of the fonts or programs installed on the machine of whoever opens it.
Some key milestones:
| Year | Milestone | Why it matters |
|---|---|---|
| 1993 | Adobe releases PDF 1.0 and Acrobat | The format is born, descended from the PostScript language |
| 1990s–2000s | Versions 1.1 to 1.7 | Encryption, forms, transparency, signatures, object compression… are added |
| 2005 | ISO 19005 (PDF/A) | A subset for long-term archiving (covered in module 8) |
| 2008 | ISO 32000-1 (PDF 1.7) | Adobe hands over the format: PDF becomes an open standard |
| 2017/2020 | ISO 32000-2 (PDF 2.0) | A modern revision of the standard, maintained by ISO |
The practical consequence of standardization is huge: anyone can write software that reads and generates PDFs without paying Adobe licence fees, and there is a public specification (around 1,000 pages long) that defines every detail of the format. PDFBox is, in essence, a Java implementation of that specification.
Note: throughout the course we will refer to "the specification" or "ISO 32000" whenever we need to justify why something works a certain way. You don't need to read it, but it helps to know it exists and that it is the ultimate reference.
A presentation format, not an editing format
This is probably the most important idea in the lesson, and the one that surprises people coming from HTML or Word the most.
A PDF does not describe the structure of a document ("this is a paragraph, this is a table with three columns"). It describes how to paint each page: "set the font to 12-point Helvetica at position (72, 700) and write Total:; draw a line from (50, 690) to (545, 690)".
Compare it with other formats:
| Feature | HTML | Word (.docx) | |
|---|---|---|---|
| Basic unit | Elements (paragraphs, tables, divs) | Paragraphs, styles, sections | Pages with drawing instructions |
| Text "reflows" when the size changes | Yes | Yes | No |
| Positions | Calculated by the browser | Calculated by the word processor | Absolute, fixed when the file is created |
| Line and page breaks | Automatic | Automatic | Decided by whoever generates the PDF |
| Designed for | Displaying on screen and adapting | Editing | Faithful display and printing |
What does this mean for a programmer?
- When generating: you are the "layout engine". If a line of text is too long, nobody wraps it for you; if a table doesn't fit on the page, you have to create another page and carry on. We will learn how in modules 2 and 3.
- When modifying: "changing a word" in an existing PDF is nothing like editing a text document. The usual approach is to add content on top (a stamp, a watermark) rather than rewrite what is already there.
- When extracting: getting the text out of a PDF means rebuilding it from fragments positioned on the page. That is why extracted text sometimes comes out jumbled (we will see this in module 6).
flowchart LR
A[Business data<br/>invoice, customer, lines] --> B[Your Java code<br/>decides positions,<br/>fonts and breaks]
B --> C[PDFBox<br/>translates into PDF objects]
C --> D[.pdf file<br/>drawing instructions<br/>per page]
D --> E[Viewer / printer<br/>paints exactly<br/>what it is told]
Typical PDF use cases on the backend
On the server side, PDFs show up in a handful of recurring scenarios. This course covers all of them:
- Transactional documents: invoices, delivery notes, quotes, receipts, tickets. They are generated from database data, usually in high volume.
- Reports: listings with tables, totals and pagination (headers and footers with "Page 3 of 12").
- Contracts and forms: PDF templates with fields (AcroForm) that are filled in automatically with the customer's data.
- Document post-processing: adding stamps ("PAID", "COPY"), watermarks ("DRAFT"), merging several PDFs into one or splitting a large one.
- Information extraction: reading supplier invoices, indexing documents for search, generating thumbnails.
- Digital signatures: giving a document legal validity and guaranteeing its integrity.
- Long-term archiving: storing documents as PDF/A so they can still be opened in 20 or 30 years' time, something regulations often require.
What Apache PDFBox is
Apache PDFBox is an open-source Java library, maintained by the Apache Software Foundation, for creating, reading, modifying, extracting, signing and validating PDF documents.
Its main characteristics:
- Apache 2.0 licence: you can use it in commercial, closed-source software without having to publish your code. You only need to keep the licence notices. This is a key point when comparing it with other libraries.
- Works at a low level: it gives you direct access to the PDF objects and drawing instructions. That means more layout work, but also full control.
- Mature project: it has been around since 2002 and is used by many other projects (for example, Apache Tika to extract text from documents).
- Current version 3.0.x: requires Java 8 or later. In this course we will use PDFBox 3.0.x with Java 17. Version 2.x is still very common in older projects and its API differs in some important ways; we will point it out whenever an example you find online is written for 2.x (and in lesson 08-06 we will cover the migration in detail).
The PDFBox modules
PDFBox is not a single JAR but a family of modules. You will almost always need only the first one (it pulls in whatever else it needs automatically):
| Module (artifactId) | What it is for | Will we use it? |
|---|---|---|
pdfbox |
Core: create, load, modify, extract, encrypt, sign | Always |
pdfbox-io |
Low-level reading/writing (new in 3.0) | Comes in automatically with pdfbox |
fontbox |
Font parsing (TrueType, Type 1, CFF…) | Comes in automatically with pdfbox |
xmpbox |
Reading and writing XMP metadata | Modules 4 and 8 (metadata and PDF/A) |
preflight |
Validating whether a PDF complies with PDF/A-1 | Module 8 |
pdfbox-tools |
Command-line utilities (extract text, merge, render…) | Lesson 01-05 |
pdfbox-debugger |
PDFDebugger, a GUI application for inspecting the inside of a PDF | Lesson 01-05 and the whole course |
pdfbox-app |
Executable JAR that bundles all of the above | Lesson 01-05 |
What PDFBox can do… and what it can't
Setting clear expectations saves a lot of frustration. PDFBox is a PDF library, not a report generator or a browser.
| PDFBox can | PDFBox cannot (on its own) |
|---|---|
| Create pages and draw text, lines, rectangles and images | Convert HTML/CSS to PDF |
| Embed TrueType fonts with Unicode support (€, ñ, accented characters…) | Lay out content automatically: there are no "flowing paragraphs" or automatic tables |
| Load existing PDFs and add content to them | Reliably edit existing text "like in Word" |
| Merge, split, rotate and reorder pages | Convert Word/Excel to PDF |
| Fill in, create and flatten AcroForm forms | Fill in dynamic XFA forms (an obsolete Adobe format) |
| Extract text, images and metadata | Run OCR on scanned documents (combine it with Tesseract or similar) |
| Render pages to images (PNG, JPG) | Guarantee a valid PDF/A unless you follow the rules |
| Encrypt, decrypt and digitally sign (with Bouncy Castle) | — |
Validate PDF/A-1 with preflight |
— |
The limitation that affects day-to-day work the most is the lack of automatic layout. With PDFBox you don't say "put a table here"; you say "draw a line here, write this text there". That is why in module 3 we will build our own utilities (tables, pagination, a small reusable generator). It takes more work up front, but in return you get pixel-perfect output with no heavyweight dependencies.
PDFBox compared with the alternatives
There is no "best" library in the abstract: it depends on the problem. This table summarizes the most common options in Java:
| Tool | Licence | Approach | Strengths | Weaknesses |
|---|---|---|---|---|
| Apache PDFBox | Apache 2.0 | Low level: create, read, modify | Free for commercial use, very complete for reading/extraction, signing, forms | No automatic layout; complex documents require more code |
| iText 7/8 | AGPL or commercial licence | High and low level | Rich layout API (paragraphs, tables), very powerful | The AGPL requires you to release your application's source code if you distribute it or offer it as a service; otherwise you have to buy a licence |
| OpenPDF | LGPL / MPL | Fork of iText 4 | High-level API with tables and paragraphs, permissive licence | Based on an old API; fewer advanced features |
| JasperReports | LGPL | Template-based reporting engine (.jrxml) | Visual designer, ideal for data-heavy tabular reports | Heavy, its own learning curve, inflexible outside its model |
| Flying Saucer / OpenHTMLtoPDF | LGPL | HTML + CSS → PDF | You design with familiar HTML/CSS | Limited CSS support (largely CSS 2.1), little ability to modify existing PDFs |
A fun fact: OpenHTMLtoPDF uses PDFBox internally to write the PDF. In other words, even if you choose an HTML-based approach, PDFBox is often underneath.
When should you choose PDFBox?
- When you need to modify, merge, sign, fill in or extract data from existing PDFs (this is where it really shines).
- When you generate documents with a fixed, controlled design (invoices, labels, certificates).
- When the licence matters and you can't accept the AGPL or pay for iText.
When should you consider something else?
- If your team already has its templates in HTML/CSS and the document is mostly "running text", OpenHTMLtoPDF can save you work.
- If you need reports with groupings, subtotals and a visual designer for non-programmers, JasperReports is a better fit.
The course project: InvoiceLab
To give everything you learn a real-world context, we will work on a single project throughout the course: InvoiceLab.
The (fictional) client: Nebula Distribution Ltd., an office supplies distributor based in Zaragoza, Spain (fictional VAT ID B00000000). Today it produces its invoices by hand with a spreadsheet and wants to automate all of its paperwork.
What it needs, and where we will learn it:
| Nebula Distribution's need | Course module |
|---|---|
| Understand the format and set up the project | 1 — Fundamentals |
| Write text in its typeface, with its logo, lines and corporate colours | 2 — Generating content |
| Invoices and delivery notes with tables, multiple pages, a QR code | 3 — Business documents |
| Stamp invoices as "PAID", mark drafts, merge documents | 4 — Modifying existing PDFs |
| Fill in template contracts with the customer's data | 5 — AcroForm forms |
| Read supplier invoices and generate thumbnails | 6 — Extraction and analysis |
| Protect and digitally sign contracts | 7 — Security and signatures |
| Archive as PDF/A, publish a REST service and test everything | 8 — PDFBox in production |
Project conventions (we will set them in the next lesson and keep them for the whole course):
- A Maven project with
groupIdcom.invoicelabandartifactIdinvoicelab. - Root package
com.invoicelab; the standalone examples from each lesson go incom.invoicelab.examples. - Generated PDFs are saved in the project's
output/folder. - Fonts in
src/main/resources/fonts/and images (the logo) insrc/main/resources/img/. - All data is fictional: customers, tax IDs, addresses and amounts.
Later on, a small domain model (Invoice, InvoiceLine, Customer) will appear to feed the document generators. In this first module we will stick to creating the project skeleton and the first simple PDFs.
A first look at the code
We won't start programming yet (that begins in lesson 01-04), but to give you a feel for the "flavour" of PDFBox, this is how you create an empty one-page document:
try (PDDocument document = new PDDocument()) { // 1. New document in memory
document.addPage(new PDPage()); // 2. Add a blank page
document.save("output/empty.pdf"); // 3. Write it to disk
} // 4. try-with-resources closes itPDDocumentrepresents a complete PDF document.PDPageis a page; if you don't specify a size, PDFBox uses the US Letter format. In InvoiceLab we will use A4.save(...)serializes the document into the PDF format.- In practice
try-with-resourcesis mandatory: aPDDocumentholds resources that must be released.
Notice what is not there: no margins, no styles, no paragraphs. We will build all of that ourselves.
Common Mistakes and Tips
- Expecting PDFBox to convert HTML to PDF. It doesn't. If that is your main requirement, consider OpenHTMLtoPDF (which uses PDFBox under the hood).
- Copying PDFBox 2.x examples. Many online tutorials use
PDDocument.load(...)orPDType1Font.HELVETICA, which no longer exist in 3.x. If an example doesn't compile, suspect the version first. - Assuming that "editing a PDF" is simple. Modifying existing text inside a page is fragile; the professional strategy is to regenerate the document or overlay content.
- Ignoring the licence. Before choosing a PDF library for a commercial product, review its licence carefully; iText's AGPL has given more than one company a nasty surprise.
- Tip: always keep a PDF viewer other than your browser's at hand (for example, your operating system's viewer and Adobe Acrobat Reader). Some bugs only show up in certain viewers.
Exercises
Exercise 1. For each of the following needs, state whether PDFBox on its own is a good choice, or which tool you would add or use instead:
a) Generating 5,000 invoices a month with a fixed design. b) Converting a website's help pages, written in HTML and CSS, to PDF. c) Extracting the text from scanned contracts (they are photos of paper). d) Adding a "PAID" stamp to invoices that have already been issued.
Exercise 2. Explain in your own words, in 3–4 lines, why in a PDF you can't "insert a word in the middle of a paragraph" the way you would in a word processor.
Exercise 3. A company is developing a closed-source invoicing SaaS (it does not want to publish its code). It is torn between iText and PDFBox. What would you advise it to consider regarding the licence?
Solutions
Solution 1.
a) Yes, PDFBox is ideal: fixed design, high volume, full control. You will have to program the layout yourself (we will do so in modules 2 and 3). b) Not on its own: PDFBox does not interpret HTML. OpenHTMLtoPDF (which uses PDFBox internally) is a better option. c) Not on its own: a scan is an image and contains no text. You need OCR (for example, Tesseract); PDFBox can help by rendering the pages to images or extracting the embedded images. d) Yes: loading a PDF and adding content on top is a textbook case (module 4).
Solution 2. A PDF doesn't store "paragraphs" but drawing instructions with absolute positions: each line, or even each word, is placed at fixed coordinates. If you insert a word, nothing repositions the rest of the text or recalculates the line breaks; the following text would overlap. You would have to recompute the entire layout, which the format simply doesn't provide for.
Solution 3. iText is distributed under the AGPL: if it is used in a service offered over a network, the AGPL requires the application's source code to be made available to its users, unless a commercial licence is purchased. PDFBox uses Apache 2.0, which allows it to be used in closed-source software without publishing the code, as long as the licence notices are respected. In this case, PDFBox avoids the problem (or else the company must budget for an iText commercial licence).
Conclusion
You have seen that a PDF is a presentation format: it describes how to paint each page using absolute positions, not the logical structure of the document. That nature explains almost everything that follows: why we will have to lay things out by hand, why modifying means "adding on top" and why extracting text can be tricky. You also know what Apache PDFBox is, its modules, its permissive licence and its limits, and you have seen how it compares with iText, OpenPDF, JasperReports and OpenHTMLtoPDF.
Finally, you have met InvoiceLab, the Nebula Distribution Ltd. project that will accompany us to the end. In the next lesson we get hands-on: we will create the Maven project with PDFBox 3, establish its folder structure and check that everything works by generating our first file.
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
