When a PDF generated from code doesn't look the way you expected (a blank page, missing text, a substituted font), looking at the Java code usually isn't enough: you need to see what's actually inside the file. In this lesson you'll get to know the tools that make that possible. We'll start with the pdfbox-app executable JAR and its subcommands (extract text, render, merge, split, encrypt…), move on to PDFDebugger, a GUI application for walking the COS object tree we studied in lesson 01-03, and learn how to generate uncompressed PDFs so you can read them. We'll finish with a step-by-step procedure for the most classic problem of all: "my PDF comes out blank". This wraps up the fundamentals module.
Contents
- The
pdfbox-appexecutable JAR - The PDFBox 3 command-line subcommands
- PDFDebugger: inspecting the inside of a PDF
- Viewing content streams: generating uncompressed PDFs
- Other useful tools
- Debugging workflow: "the PDF comes out blank"
The pdfbox-app executable JAR
pdfbox-app is a single JAR that bundles PDFBox with all its dependencies, the command-line utilities (pdfbox-tools) and the graphical debugger (pdfbox-debugger). It isn't part of your application: it's a working tool for your own machine.
To get it:
- From the official Apache PDFBox downloads page (Commandline tools section), or
- From Maven Central:
org.apache.pdfbox:pdfbox-app, in the same version you use in InvoiceLab (in our case,3.0.5).
We recommend keeping it outside the project, for example in a ~/tools/ folder. To avoid typing the full path every time, you can define an alias (Linux/macOS):
On Windows, a pdfbox.bat file containing java -jar C:\tools\pdfbox-app-3.0.5.jar %* in a folder on your PATH does the same job. In this lesson's examples we'll write out the full command so you don't depend on the alias.
If you run the JAR with no arguments, it shows the list of available subcommands:
The PDFBox 3 command-line subcommands
In PDFBox 3 the command line was reorganized around the picocli library: you now use a subcommand followed by options in the form -option=value. (In PDFBox 2.x the names were different, such as ExtractText or PDFMerger; if you come across examples like that online, they're for the old version.)
The general syntax is:
| Subcommand | What it does | Example use in InvoiceLab |
|---|---|---|
export:text |
Extracts the text | Check that an invoice's text can be extracted |
export:images |
Extracts the embedded images | Verify that the logo was embedded correctly |
export:xmp |
Extracts the XMP metadata | Review metadata (modules 4 and 8) |
render |
Converts pages to images | Visually compare a generated PDF |
merge |
Merges several PDFs | Combine an invoice and a delivery note |
split |
Splits a PDF | Break up a batch of invoices |
encrypt / decrypt |
Encrypts or decrypts | Test protected documents (module 7) |
overlay |
Overlays one PDF on top of another | Try out a corporate letterhead background (module 4) |
fromtext / fromimage |
Creates a PDF from text or images | Quickly generate test PDFs |
decode |
Rewrites the PDF with decompressed streams | Debugging |
print |
Prints a PDF | — |
debug |
Opens PDFDebugger | Debugging |
Every subcommand accepts -h (or --help) to show its options and -V (or --version) to show the version. Whenever in doubt, --help is the definitive reference for your exact version.
Extracting text
-i=specifies the input file.-consoleprints the text to the screen instead of creating a.txtfile next to the PDF.- Other useful options:
-o=file.txt(output),-startPage=2 -endPage=3(page range),-sort(sorts the text by position),-html(HTML output) and-password=(for protected PDFs).
It's a lightning-fast test: if export:text returns "Hello, InvoiceLab", the text is in the PDF even if your viewer doesn't show it (which points to a position or colour problem, not a content problem).
Rendering pages to images
It generates one image per page, named after the PDF followed by the page number (for example, output/hello-invoicelab1.png). Options: -page=1 (a single page), -startPage/-endPage, -prefix= (file name prefix) and -color=GRAY (greyscale). It lets you see the result exactly as PDFBox paints it, without depending on any viewer. We'll program this very thing in lesson 06-04.
Merging and splitting
# Merge: repeat -i once per file, in the desired order
java -jar pdfbox-app-3.0.5.jar merge -i=output/invoice.pdf -i=output/delivery-note.pdf -o=output/shipment.pdf
# Split: one file per page (-split=1); the results are named <name>-1.pdf, <name>-2.pdf…
java -jar pdfbox-app-3.0.5.jar split -split=1 -i=output/hello-3-pages.pdf(The files invoice.pdf and delivery-note.pdf don't exist yet; we'll generate them in module 3. You can try it with any pair of PDFs.)
Encrypting and decrypting
# Encrypt with an owner password (-O) and a user password (-U)
java -jar pdfbox-app-3.0.5.jar encrypt -O=owner -U=user \
-i=output/hello-invoicelab.pdf -o=output/hello-protected.pdf
# Decrypt (requires the owner password)
java -jar pdfbox-app-3.0.5.jar decrypt -password=owner \
-i=output/hello-protected.pdf -o=output/hello-decrypted.pdfYou can use output/hello-protected.pdf to test PdfInfo's password handling (lesson 01-04). Programmatic encryption is covered in lesson 07-01.
Decompressing for reading
Watch out: decode takes positional arguments (input and output, without -i=). The resulting file has its streams decompressed and can be opened in a text editor. We'll come back to this in the section on content streams.
PDFDebugger: inspecting the inside of a PDF
PDFDebugger is a desktop application (Swing) included in pdfbox-app that displays a PDF as the COS object tree we studied in lesson 01-03, alongside a preview of the page. It's the most valuable tool for understanding why a PDF doesn't behave the way you expect.
To open it:
- The file is passed as a positional argument (you can also leave it out and open it from the File → Open menu).
-password=lets you open protected PDFs.-viewstructurestarts in the physical structure view (objects and xref) instead of the logical view.
What you'll find in PDFDebugger
The window is split into a tree on the left and a detail panel on the right:
| Tree element | What it represents | What to look at |
|---|---|---|
Trailer |
The trailer dictionary | /Root, /Info, /ID, /Encrypt if it's encrypted |
Root (Catalog) |
The document catalog | /Pages, /AcroForm, /Metadata, /Outlines |
Pages |
The page tree | /Count and /Kids |
Page 1, Page 2… |
Each page | /MediaBox, /Resources, /Contents, /Rotate |
Resources → Font → F1 |
A font used on the page | /BaseFont, /Subtype, whether it's embedded (/FontFile2…) |
Contents |
The content stream | When you select it, the right-hand panel shows the decompressed operators |
XObject → Im1 |
An image | When you select it, it's displayed |
When you select a stream, PDFDebugger lets you choose how to display it (for example, decoded or raw). For a content stream, the decoded view shows something like this:
In other words, exactly what our PDPageContentStream wrote in the previous lesson. If the page doesn't show the text, this is where you'll see whether the Tj operator is there, where it's positioned (Td) and which font it uses (Tf).
Guided exercise with InvoiceLab
- Open
output/hello-invoicelab.pdfwith PDFDebugger. - Expand
Root → Pages → Kids → [0](the first page). - Look at
/MediaBox: you'll see[0.0 0.0 595.27563 841.8898], the exact A4 size in points. - Expand
/Resources → /Font → /F1: check that/BaseFontisHelvetica-Bold. - Select
/Contentsand read the text operators. - Compare it with
output/minimal-by-hand.pdffrom lesson 01-03: the structure is the same, although PDFBox numbers the objects its own way and adds keys such as/Encoding /WinAnsiEncodingto the font.
Viewing content streams: generating uncompressed PDFs
If you open a PDF generated by PDFBox 3 in a text editor, you'll mostly see unreadable bytes. There are two levels of compression, and it's worth telling them apart:
| What gets compressed | Who decides | How to turn it off |
|---|---|---|
Each page's content streams (/Filter /FlateDecode) |
The PDPageContentStream constructor |
The compress = false parameter |
| The document structure: objects grouped into object streams and a compressed xref table | PDDocument.save(...) |
save(file, CompressParameters.NO_COMPRESSION) |
To get a fully readable PDF you need to turn off both. Create com.invoicelab.examples.DebuggableHello:
package com.invoicelab.examples;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import org.apache.pdfbox.Loader;
import org.apache.pdfbox.pdfwriter.compress.CompressParameters;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.PDPageContentStream.AppendMode;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.apache.pdfbox.pdmodel.font.Standard14Fonts;
/**
* Generates a "Hello, InvoiceLab" that is fully readable in a text editor
* and prints the content stream of its first page to the console.
*/
public class DebuggableHello {
public static void main(String[] args) throws IOException {
Files.createDirectories(Path.of("output"));
File target = new File("output/hello-debuggable.pdf");
try (PDDocument document = new PDDocument()) {
PDPage page = new PDPage(PDRectangle.A4);
document.addPage(page);
// compress = false -> the content stream is written without FlateDecode
try (PDPageContentStream content = new PDPageContentStream(
document, page, AppendMode.OVERWRITE, false)) {
content.beginText();
content.setFont(new PDType1Font(Standard14Fonts.FontName.HELVETICA_BOLD), 24);
content.newLineAtOffset(72, 770);
content.showText("Hello, InvoiceLab");
content.endText();
}
// NO_COMPRESSION -> no object streams and no compressed xref
document.save(target, CompressParameters.NO_COMPRESSION);
}
// Read back the (already decoded) content stream of the first page
try (PDDocument document = Loader.loadPDF(target);
InputStream in = document.getPage(0).getContents()) {
System.out.println("--- Content stream of page 1 ---");
System.out.println(new String(in.readAllBytes(), StandardCharsets.ISO_8859_1));
}
}
}Explanation:
- The
PDPageContentStream(document, page, AppendMode.OVERWRITE, false)constructor takes:AppendMode.OVERWRITE: replaces the page's content (the behaviour of the short constructor). In module 4 we'll useAPPENDandPREPENDto add content to existing pages.false: don't compress this content stream.
document.save(target, CompressParameters.NO_COMPRESSION)writes each object separately along with a classic plain-text xref table, just like the hand-written PDF. In addition, the document keeps version 1.4 (without object streams there's no need for 1.5 or later).page.getContents()returns anInputStreamwith the page content already decoded (if it were compressed, PDFBox would decompress it as it reads). It's a quick way to see the operators from code, without any external tools. We use ISO-8859-1 because content streams are bytes, not UTF-8 text.
Console output:
If you now open output/hello-debuggable.pdf in a text editor, you'll see something very similar to the PDF we wrote by hand:
%PDF-1.4
%âãÏÓ
1 0 obj
<<
/Type /Catalog
/Version /1.4
/Pages 2 0 R
>>
endobj
...
5 0 obj
<<
/Length 49
>>
stream
BT
/F1 24 Tf
72 770 Td
(Hello, InvoiceLab) Tj
ET
endstream
endobjFor debugging only. In production, leave the default compression on: uncompressed PDFs can be several times larger. A handy trick is to enable the "debuggable" mode through a system property or a configuration flag, rather than by changing the code.
Other useful tools
PDFBox isn't the only tool worth keeping at hand. Cross-checking against other implementations helps you tell whether a problem lies in your PDF or in a particular viewer.
| Tool | Type | What it's for | Example |
|---|---|---|---|
| qpdf | Command line (open source) | Rewriting a PDF in readable form ("QDF"), checking its structure | qpdf --qdf --object-streams=disable in.pdf readable.pdf |
qpdf --check |
Command line | Detecting structural errors (xref, streams) | qpdf --check output/hello-invoicelab.pdf |
| Adobe Acrobat Reader | Viewer | The de facto reference; many customers will use it | Open the file and check that it doesn't ask you to "save changes" when closing (a sign that it had to repair the PDF) |
| Browser viewer (Chrome, Firefox with pdf.js) | Viewer | Checking how web users will see it | — |
| Other viewers (Evince, SumatraPDF, macOS Preview) | Viewer | A quick cross-check between implementations | — |
| veraPDF | Validator | Validating PDF/A (we'll use it in module 8) | — |
qpdf --qdf is especially useful with PDFs you didn't generate yourself (for example, the contract template a customer sends you): it produces a file with the objects ordered, decompressed and annotated, ideal for comparing in an editor or with diff.
Debugging workflow: "the PDF comes out blank"
This is by far the most common problem when you're starting out. It almost always has one of the following causes, and this procedure leads you to it systematically:
flowchart TD
A[The PDF comes out blank] --> B{Does the PDF open<br/>without errors?}
B -- No --> B1[Was the content stream closed<br/>before save?<br/>Was the document closed?<br/>Run qpdf --check]
B -- Yes --> C{Does export:text return<br/>the text?}
C -- Yes --> D[The text exists but isn't visible:<br/>coordinates off the page?<br/>white colour?<br/>covered by a rectangle?]
C -- No --> E{In PDFDebugger,<br/>does /Contents have operators?}
E -- No --> F[Nothing was written:<br/>content stream not closed?<br/>drawn on another page?<br/>overwritten with OVERWRITE?]
E -- Yes --> G{Is the font used in Tf<br/>in /Resources?}
G -- No --> H[Resources out of sync:<br/>check the code that manipulates COS]
G -- Yes --> I[Check Td/Tm, font size<br/>and MediaBox;<br/>render it with 'render']
Step by step:
- Is the file valid? Open it in two different viewers and, if you can, run
qpdf --check. If it's damaged, check that you closed thePDPageContentStreambeforesaveand that you didn't save over the source file. - Does the content exist? Run
export:text -console. If the text appears, the content is there; the problem is one of visibility. - Visibility problems (the text exists but can't be seen):
- Coordinates off the page: remember that Y grows upwards from the bottom edge. A
newLineAtOffset(72, 900)on an A4 page (842 high) puts the text outside it. - White fill colour on a white background.
- A filled rectangle drawn after the text, covering it.
- A tiny font size (for example, 0.1 instead of 10).
- Coordinates off the page: remember that Y grows upwards from the bottom edge. A
- Are there operators on the page? Open PDFDebugger and look at
/Contents. If it's empty or doesn't exist, the code never got as far as writing anything (content stream not closed, wrong page, content overwritten by a secondPDPageContentStreaminOVERWRITEmode). - Do Contents and Resources match? Every
/Fxused withTfand every/Imxused withDomust exist in that page's/Resources. With the PD API this rarely goes wrong; if you've touched the COS layer, that's where to look. - Confirm with
render. If the image rendered by PDFBox shows the content but a particular viewer doesn't, the problem is compatibility with that viewer (for example, a non-embedded font); make a note of it for module 2.
And as for habits, three tips that will save you hours:
- Change one thing at a time and regenerate.
- Have a "debuggable" (uncompressed) mode ready so you can compare files with
diff. - Keep a known-good reference PDF and compare against it when something breaks.
Common Mistakes and Tips
- Using the 2.x command-line syntax (
ExtractText,PDFMerger,-split 2without=). In 3.x these are subcommands (export:text,merge) with options in the form-option=value. Always check--help. - Using a
pdfbox-appwhose version differs from the project's. It may behave differently; keep both versions aligned. - Turning off only one of the two kinds of compression. With
NO_COMPRESSIONbut a compressed content stream, you'll still see unreadable bytes for the page; withcompress=falsebut the default save, the stream will end up inside a compressed object stream. For debugging, turn off both (or usedecode). - Leaving uncompressed mode on in production. Larger files with no benefit whatsoever for the user.
- Trusting a single viewer. Some viewers are very forgiving and silently "fix" errors; others, such as Acrobat, are stricter. Test in at least two.
- Tip: PDFDebugger is also an excellent learning tool: open real invoice PDFs from your suppliers (without sharing them outside your organization) and look at how they're built.
Exercises
Exercise 1. Using only the PDFBox command line:
a) Extract the text of output/hello-3-pages.pdf (the exercise from lesson 01-04) to the console, but only from pages 2 and 3.
b) Render only its page 2 to PNG at 72 dpi.
c) Split it into single-page files and merge pages 3 and 1 back together, in that order, into output/reordered.pdf.
Exercise 2. Write a ShowPageContents class that takes the path of a PDF and, for each page, prints its number and its decoded content stream (using getContents()). Test it with output/hello-3-pages.pdf.
Exercise 3. A colleague hands you this code and says the PDF comes out blank. Find the bugs using what you've learned in this lesson (there's no need to run it):
try (PDDocument document = new PDDocument()) {
PDPage page = new PDPage(PDRectangle.A4);
document.addPage(page);
PDPageContentStream content = new PDPageContentStream(document, page);
content.beginText();
content.setFont(new PDType1Font(Standard14Fonts.FontName.HELVETICA), 12);
content.newLineAtOffset(72, 900);
content.showText("Invoice F-2026-0001");
content.endText();
document.save("output/blank-invoice.pdf");
content.close();
}Solutions
Solution 1.
# a) Text from pages 2 and 3 to the console
java -jar pdfbox-app-3.0.5.jar export:text -i=output/hello-3-pages.pdf -startPage=2 -endPage=3 -console
# b) Only page 2 to PNG at 72 dpi (generates output/hello-3-pages2.png)
java -jar pdfbox-app-3.0.5.jar render -i=output/hello-3-pages.pdf -page=2 -format=png -dpi=72
# c) Split into single pages and merge 3 and 1
java -jar pdfbox-app-3.0.5.jar split -split=1 -i=output/hello-3-pages.pdf
java -jar pdfbox-app-3.0.5.jar merge -i=output/hello-3-pages-3.pdf -i=output/hello-3-pages-1.pdf \
-o=output/reordered.pdfThe order of the -i options in merge determines the order of the pages. Check the result with export:text -console: "page 3" should appear first, followed by "page 1". (The exact names of the files generated by split and render may vary slightly; check them with ls output/.)
Solution 2.
package com.invoicelab.examples;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import org.apache.pdfbox.Loader;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
public class ShowPageContents {
public static void main(String[] args) throws IOException {
String path = args.length > 0 ? args[0] : "output/hello-3-pages.pdf";
try (PDDocument document = Loader.loadPDF(new File(path))) {
int number = 1;
for (PDPage page : document.getPages()) {
System.out.println("=== Page " + number++ + " ===");
if (!page.hasContents()) { // a page may have no /Contents
System.out.println("(no content)");
continue;
}
try (InputStream in = page.getContents()) {
System.out.println(new String(in.readAllBytes(), StandardCharsets.ISO_8859_1));
}
}
}
}
}Notice that it works even when the PDF is compressed: getContents() decodes the streams for you. hasContents() avoids processing completely empty pages, such as those in check.pdf (lesson 01-02).
Solution 3. There are two bugs:
savebefore closing the content stream.content.close()is called after saving, so the content isn't complete at the moment the PDF is written. Fix: open thePDPageContentStreamin its owntry-with-resourcesand save after it has been closed.- Y coordinate off the page. An A4 page is about 842 points high;
y = 900places the text above the top edge.export:textwould show the text (it exists), but it isn't visible. Fix: a value such as770.
Corrected version:
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), 12);
content.newLineAtOffset(72, 770);
content.showText("Invoice F-2026-0001");
content.endText();
}
document.save("output/fixed-invoice.pdf");
}Conclusion
This lesson wraps up module 1. You now have the tools to stop working blind: the pdfbox-app JAR with its PDFBox 3 subcommands (export:text, render, merge, split, encrypt, decode…), PDFDebugger for walking the COS tree and reading content streams, the technique for generating uncompressed PDFs (compress = false on the content stream and CompressParameters.NO_COMPRESSION when saving) and a systematic procedure for diagnosing the dreaded "blank PDF".
Let's review the whole module: you know what a PDF is and why it's a presentation format, you have the InvoiceLab project set up with PDFBox 3, you understand the file's internal anatomy and the PD and COS layers, you know how to create, save and load documents, and you know how to inspect them when something goes wrong. So far our pages contain a single line of text positioned "by eye"; in module 2 we'll start generating real content: we'll get to grips with a page's coordinate system and units so we can place every element precisely, the first step towards turning Nebula Distribution's invoice into something more than a "Hello, InvoiceLab".
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
