An InvoiceLab invoice takes about 25 milliseconds to generate and weighs about 50 KB. With numbers like those, nobody worries about performance... until Nebula Distribution has to issue 10,000 invoices at the end of the month, the REST service in the next lesson receives 50 requests at once, or someone uploads a 1,000-page batch to extract its text. That's when the questions appear: how much memory does PDFBox need? Can invoices be generated in parallel? Why is it slower with 12 threads than with 4? In this lesson we'll answer with measured data, not assumptions: we'll see how PDFBox uses memory and its caches, how to load documents the right way, why fonts and images are the main cost of each invoice, how to reduce file size and how to work with several threads. We'll finish by generating 10,000 invoices in a batch and processing a 1,000-page PDF, page by page.
Contents
- How PDFBox uses memory
- The stream cache:
RandomAccessStreamCache - Loading from a file, a
byte[]or anInputStream - Releasing resources
- The resource cache (
ResourceCache) - Measure before optimising
- Where an invoice's time goes
- Reused images:
PreencodedImage - Fonts: bytes, parsing and subsets
- Compression and file size
- Concurrency
- The system font cache
- Generating 10,000 invoices in a batch
- Processing a 1,000-page PDF
About the figures. All the measurements in this lesson were taken on the same machine (12 logical processors, 15 GB of RAM, JDK 21 running code compiled for Java 17, PDFBox 3.0.8). Your numbers will be different; what matters are the proportions and, above all, the method used to measure.
How PDFBox uses memory
flowchart LR
F["PDF file<br/>on disk"] -->|"RandomAccessRead<br/>(on-demand reading)"| P["Parser"]
P --> COS["Parsed COS objects<br/>(kept until close)"]
COS --> PD["PD objects<br/>PDPage, PDFont..."]
PD --> RC["ResourceCache<br/>fonts, images, ExtGState<br/>(SoftReference)"]
N["New streams<br/>(contents, images, merges)"] --> SC["Stream cache<br/>memory or temporary file"]
PD -->|"render"| IMG["BufferedImage<br/>(by far the largest)"]
There are five different memory consumers, and it's worth not mixing them up:
| Consumer | What it holds | When it's released | How it's controlled |
|---|---|---|---|
Read source (RandomAccessRead) |
The bytes of the original PDF, or a window over them | When the document is closed | Load from a file instead of from a byte[] |
| Parsed COS objects | Dictionaries, arrays and numbers of every object read | When the document is closed | Process in parts, close early |
| Stream cache | New streams (the ones you create or copy) | When the document is closed | StreamCacheCreateFunction |
ResourceCache |
Fonts, images and colour spaces already interpreted | When the JVM needs memory (soft references) or on close | setResourceCache |
| Results | BufferedImage when rendering, String when extracting text, byte[] when saving |
When you stop using them | Your code |
Two ideas to take away:
- PDFBox 3 reads on demand. When loading, it doesn't read the whole file: it parses the cross-reference table and reads objects as you ask for them. But whatever it has already read stays in memory while the document is open.
- Original streams aren't copied. The content of a page or an image from the original file is read from the
RandomAccessReadevery time it's needed; the stream cache only stores what you create.
The stream cache: RandomAccessStreamCache
In PDFBox 2 this was controlled with MemoryUsageSetting; in PDFBox 3 it's decided by a StreamCacheCreateFunction, which you can pass to Loader.loadPDF, to the PDDocument constructor, to PDFMergerUtility.mergeDocuments and to Splitter:
PDDocument created = new PDDocument(IOUtils.createTempFileOnlyStreamCache());
PDDocument loaded = Loader.loadPDF(new File("batch.pdf"), IOUtils.createTempFileOnlyStreamCache());
merger.mergeDocuments(IOUtils.createMemoryOnlyStreamCache());
splitter.setStreamCacheCreateFunction(IOUtils.createTempFileOnlyStreamCache());| Option | Where it stores | When to use it |
|---|---|---|
| Default (no parameter) | Memory | Almost always: small and medium-sized documents |
IOUtils.createMemoryOnlyStreamCache() |
Memory, unlimited | The same, explicitly |
IOUtils.createTempFileOnlyStreamCache() |
Temporary files (java.io.tmpdir) |
Documents that grow a lot (merges of hundreds of pages), servers with little memory, PDFs of unknown origin |
MemoryUsageSetting.setupMixed(bytes).streamCache |
Memory up to a limit, then disk | A configurable middle ground |
In 04-04 we promised to measure the impact. We merged 500 copies of F-2026-0001.pdf (1,000 pages, 25.5 MB) with each option:
| Merging 1,000 pages | Time | With -Xmx128m |
|---|---|---|
| Memory | 843 ms | Works (879 ms) |
| Temporary files | 1,009 ms | Works (919 ms) |
| Mixed (16 MB in memory) | 996 ms | — |
The conclusion is surprising: with well-built PDFs like ours, the three options behave the same and the merge fits comfortably in 128 MB, because PDFMergerUtility copies streams without decompressing them and most of the data stays in the source files. The disk cache is an insurance policy for the cases you don't control (documents with huge images, third-party files), which is why we use it in the REST service for everything that comes from outside. It costs little: about 150 ms more in this example.
Loading from a file, a byte[] or an InputStream
| Method | Code | Memory |
|---|---|---|
| From a file | Loader.loadPDF(file) |
Uses RandomAccessReadBufferedFile: reads in 4 KB pages with a cache of up to 1,000 pages (about 4 MB) |
From a byte[] |
Loader.loadPDF(bytes) |
Wraps the array without copying it: the whole file in memory |
From an InputStream |
Loader.loadPDF(new RandomAccessReadBuffer(input)) |
Copies the whole stream into memory before starting |
| Memory-mapped file | Loader.loadPDF(new RandomAccessReadMemoryMappedFile(path)) |
The operating system decides; 2 GB maximum |
We measured page-by-page text extraction from the 1,000-page PDF loaded in each way:
| Loading | Time | Characters extracted |
|---|---|---|
Loader.loadPDF(File) |
3.9 s | 1,834,500 |
Loader.loadPDF(File, createTempFileOnlyStreamCache()) |
4.0 s | 1,834,500 |
Loader.loadPDF(byte[]) |
3.8 s | 1,834,500 |
RandomAccessReadBuffer(InputStream) |
3.7 s | 1,834,500 |
Loader.loadPDF(File) with -Xmx128m |
4.0 s | 1,834,500 |
There are no noticeable differences in time. The difference lies in the minimum memory: with byte[] or InputStream, the file's 25.5 MB are on the heap from the start; with File, they aren't. For a 25 MB file it doesn't matter; for a 2 GB one, it's the difference between working and OutOfMemoryError. The rule:
- If the PDF is on disk, load it from the file. Don't read it first with
Files.readAllBytes. - If it reaches you over the network (an HTTP upload), first write it to a temporary file (we'll do this in 08-04) and load it from there.
- Use
byte[]only for small documents you already have in memory, such as the ones our generators return.
Releasing resources
PDFBox has no "partial collection": whatever has been read from a document is released when you close it. Hence the rules we've been applying since 01-04:
- Close every
PDDocumentwith try-with-resources, in tests and on error paths too. - Don't hold on to
PD*objects (PDPage,PDFont,PDImageXObject) in lists or fields that outlive their document. Besides being a design error (03-04), they prevent the garbage collector from freeing the entire document, because each object keeps references to itsCOSDocument. - Process giant documents in parts. If you only need to go through a 10,000-page PDF once, by the time you reach the last page you'll have everything read from all of them in memory. For truly enormous documents, split them first with
Splitter(04-04), using a disk cache, and process each part separately. - Don't use a document after closing it: PDFBox doesn't always throw an exception, and the results may be wrong.
The resource cache (ResourceCache)
Each PDDocument has a DefaultResourceCache that stores fonts, images, colour spaces, graphics states, shadings and patterns already interpreted, so they don't need to be interpreted again if they appear on another page. It uses SoftReference: the JVM can empty it when it needs memory.
Its effect is most noticeable when rendering. We rendered the 1,000 pages of the batch at 50 dpi, one image at a time:
| Rendering 1,000 pages | Time | Peak heap | Collections |
|---|---|---|---|
With cache (default), -Xmx2g |
12.9 s | 1,139 MB | 83 |
Without cache (setResourceCache(null)), -Xmx2g |
39.8 s | 234 MB | 241 |
With cache, -Xmx128m |
15.7 s | 183 MB | 1,052 |
try (PDDocument document = Loader.loadPDF(pdf)) {
document.setResourceCache(null); // no cache: every page reinterprets fonts and images
PDFRenderer renderer = new PDFRenderer(document);
for (int p = 0; p < document.getNumberOfPages(); p++) {
BufferedImage image = renderer.renderImageWithDPI(p, 50, ImageType.RGB);
// ... use and discard the image
}
}How to read the table:
- With plenty of memory, the cache takes up a lot (a 1.1 GB peak) because the JVM has no reason to empty it, and it triples the speed.
- With little memory (
-Xmx128m), the cache adapts: the JVM releases the soft references when it needs to, and rendering is still 2.5 times faster than without a cache, albeit with many more collections. - Turning it off only pays off if the document doesn't repeat resources across pages and you want more predictable memory usage, or if you render from many threads at once and would rather each document didn't hog the heap. In most cases, leave it as it is.
The "peak heap" in this table and the ones that follow is how much the garbage collector ended up occupying, not what the program needs: with more memory available, the JVM collects less often. To find out how much memory a process really needs, the reliable test is the one we do with -Xmx128m or -Xmx64m: run it with little memory and see whether it finishes and how much it suffers.
Measure before optimising
To take measurements we use a simple class, Benchmark, in the com.invoicelab.performance package: it times a task and reads from the JVM's MXBeans the peak usage of each heap area and the number of collections.
public final class Benchmark {
public record Measurement(String scenario, long milliseconds, long peakHeapMb, long collections) {
}
@FunctionalInterface
public interface Task {
void run() throws Exception;
}
public static Measurement measure(String scenario, Task task) throws Exception {
System.gc(); // start from a clean heap
ManagementFactory.getMemoryPoolMXBeans().forEach(MemoryPoolMXBean::resetPeakUsage);
long gcBefore = collections();
long start = System.nanoTime();
task.run();
long ms = (System.nanoTime() - start) / 1_000_000;
long peak = 0;
for (MemoryPoolMXBean pool : ManagementFactory.getMemoryPoolMXBeans()) {
if (pool.getType() == MemoryType.HEAP) {
peak += pool.getPeakUsage().getUsed(); // sum of each area's peak
}
}
return new Measurement(scenario, ms, peak / (1024 * 1024), collections() - gcBefore);
}
private static long collections() {
long total = 0;
for (GarbageCollectorMXBean gc : ManagementFactory.getGarbageCollectorMXBeans()) {
total += Math.max(0, gc.getCollectionCount());
}
return total;
}
}Rules for measurements that are worth something:
- Warm up the JVM before measuring: the first runs include class loading and JIT compilation. Our programs generate 200 unmeasured invoices before starting.
- A fresh JVM per scenario, with the same
-Xmx: that way one scenario doesn't inherit the cache or the heap of the previous one. - Measure realistic volumes. 10 invoices tell you nothing; 10,000 do.
- Don't measure with other things running (builds, the IDE indexing).
For micro-optimisations (exactly how much a method costs), the right tool is JMH (Java Microbenchmark Harness), which handles warm-up, repetitions and JIT effects for you. For questions like "how long does the batch take?" or "does it fit in 512 MB?", a stopwatch like Benchmark and runs with different -Xmx values are enough. And if you need to know what is taking up the memory, take a heap dump (jcmd <pid> GC.heap_dump file.hprof) and open it with an analyser such as Eclipse MAT or VisualVM; or record a session with Java Flight Recorder (-XX:StartFlightRecording) to see where the time goes and what gets allocated.
Where an invoice's time goes
Before optimising, we measured the pieces separately (500 repetitions after warm-up, a single thread):
| Operation | Time per document |
|---|---|
Load the PNG logo with Images.loadResource (02-06) |
13.9 ms |
| Document with the 3 DejaVu fonts (regular, bold, italic) and save | 6.0 ms |
| Full invoice with 12 lines | 24.3 ms |
| Full invoice with 30 lines | 28.6 ms |
The surprise: more than half of an invoice's time goes on the logo. PDImageXObject.createFromByteArray decodes the 720 × 240-pixel PNG, separates the alpha channel and compresses both parts again with Flate. And it does so for every invoice, even though the logo is always the same. The lines, the text and the tables, the things that really change between invoices, cost a few milliseconds.
Reused images: PreencodedImage
A PDImageXObject belongs to one document and can't be shared between documents (or between threads). But we can share the result of the expensive work: the image dictionary and its already compressed bytes. For each new document we just have to copy them into a new stream, without decoding or recompressing anything:
/**
* An image converted to an XObject and compressed ONCE per application.
* For each document only the compressed bytes are copied: no PNG decoding and no recompression.
*/
public final class PreencodedImage {
private static final Map<String, PreencodedImage> CACHE = new ConcurrentHashMap<>();
private final COSDictionary dictionary; // /Width, /Height, /Filter, /ColorSpace... (no /SMask or /Length)
private final byte[] data; // stream content as is, already compressed
private final PreencodedImage mask; // /SMask (alpha channel) or null
private PreencodedImage(COSStream stream) throws IOException {
dictionary = new COSDictionary();
for (Map.Entry<COSName, COSBase> e : stream.entrySet()) {
if (!e.getKey().equals(COSName.LENGTH) && !e.getKey().equals(COSName.SMASK)) {
dictionary.setItem(e.getKey(), deepCopy(e.getValue()));
}
}
try (InputStream input = stream.createRawInputStream()) { // "raw": not decompressed
data = input.readAllBytes();
}
COSStream smask = stream.getCOSStream(COSName.SMASK);
mask = smask == null ? null : new PreencodedImage(smask);
}
/** Image from the classpath, pre-encoded the first time it's requested (thread-safe). */
public static PDImageXObject in(PDDocument document, String path) throws IOException {
PreencodedImage image = CACHE.get(path);
if (image == null) {
try (PDDocument scratch = new PDDocument()) {
PDImageXObject original = Images.loadResource(scratch, path); // the expensive work, once
image = new PreencodedImage(original.getCOSObject());
}
CACHE.putIfAbsent(path, image);
}
return new PDImageXObject(new PDStream(image.copyTo(document)), null);
}
private COSStream copyTo(PDDocument document) throws IOException {
COSStream stream = document.getDocument().createCOSStream();
for (Map.Entry<COSName, COSBase> e : dictionary.entrySet()) {
stream.setItem(e.getKey(), deepCopy(e.getValue())); // each document gets its own objects
}
try (OutputStream output = stream.createRawOutputStream()) { // without compressing again
output.write(data);
}
if (mask != null) {
stream.setItem(COSName.SMASK, mask.copyTo(document));
}
return stream;
}
/** Deep copy of dictionaries and arrays, resolving indirect references. */
private static COSBase deepCopy(COSBase value) {
if (value instanceof COSObject indirect) {
return deepCopy(indirect.getObject());
}
if (value instanceof COSDictionary source && !(value instanceof COSStream)) {
COSDictionary target = new COSDictionary();
source.entrySet().forEach(e -> target.setItem(e.getKey(), deepCopy(e.getValue())));
return target;
}
if (value instanceof COSArray source) {
COSArray target = new COSArray();
source.forEach(v -> target.add(deepCopy(v)));
return target;
}
return value; // COSName, COSInteger, COSFloat... are immutable
}
}The keys to the design:
createRawInputStreamandcreateRawOutputStreamread and write the stream exactly as it is in the file, compressed, without going through the filters. That's what saves us the work.- The cache is static and shares only immutable data (
byte[]and dictionaries that are never modified after construction). Each document receives copies of the dictionaries (deepCopy), so no COS object is shared between documents that might be being saved on different threads.DecodeParms, for example, was an indirect reference to the scratch document:deepCopyresolves it and duplicates it. - The
/SMask(the logo's alpha channel) is another image: it's pre-encoded the same way, recursively. ConcurrentHashMapandputIfAbsentmake the cache thread-safe. If two threads ask for the logo at the same time the first time round, both pre-encode it and one of the results is discarded: harmless duplicated work.
To use it, PdfContext.image (03-04) changes a single line:
public PDImageXObject image(String path) throws IOException {
PDImageXObject image = images.get(path);
if (image == null) {
image = PreencodedImage.in(document, path); // before: Images.loadResource(document, path)
images.put(path, image);
}
return image;
}Is the result identical? We generated F-2026-0001.pdf with both versions: the two files are exactly 52,410 bytes, they differ in only 120 bytes (the trailer's /ID, which changes on every save) and VisualComparator finds 0 different pixels on the two pages. In the 10,000-invoice batch, this class doubles the speed on a single thread (from 262 s to 125 s).
Fonts: bytes, parsing and subsets
InvoiceLabFonts (02-03) already applies the basic rule: the bytes of the .ttf are read from the classpath once per application; the PDType0Fonts, once per document. We measured the cost of several strategies by generating 1,000 one-line documents:
| Strategy | Time per document | Size |
|---|---|---|
| Helvetica (Standard 14, not embedded) | 0.26 ms | 851 bytes |
| DejaVu read from the classpath for each document | 2.32 ms | 5,962 bytes |
DejaVu from a cached byte[] (what InvoiceLabFonts does) |
1.96 ms | 5,962 bytes |
DejaVu with an already parsed TrueTypeFont |
0.74 ms | 5,962 bytes |
DejaVu from a byte[], without subsetting |
29.98 ms | 394,550 bytes |
What the table tells us:
- Always subset: embedding the full font multiplies the size by 66 and the time by 15 (700 KB of font have to be compressed in every document).
- Reading from the classpath each time costs little more than having the bytes cached:
InvoiceLabFonts' byte cache helps, but it isn't the main thing. - Parsing the font (turning the bytes into a
TrueTypeFontwith its tables) is the most expensive part:PDType0Font.load(doc, InputStream, true)does it for every document. Reusing an already parsedTrueTypeFontcuts it to a third.
PDType0Font.load(PDDocument, TrueTypeFont, boolean) lets you pass an already parsed font. But TrueTypeFont isn't thread-safe (it reads its tables on demand from a shared data source), so we can't have a single one for the whole application. The solution is one per thread, with ThreadLocal:
/** Already parsed fonts, one copy per thread (TrueTypeFont isn't thread-safe). */
private static final ThreadLocal<Map<String, TrueTypeFont>> TTF_PER_THREAD =
ThreadLocal.withInitial(HashMap::new);
public PDFont load(String file) throws IOException {
Map<String, TrueTypeFont> map = TTF_PER_THREAD.get();
TrueTypeFont ttf = map.get(file);
if (ttf == null) {
ttf = new TTFParser().parse(new RandomAccessReadBuffer(readBytes(file)));
map.put(file, ttf);
}
return PDType0Font.load(document, ttf, true); // subset, without parsing again
}This version of InvoiceLabFonts.load once again produces PDFs of the same size that are visually identical (0 different pixels). Bear in mind its conditions:
- It works well with fixed-size thread pools (threads live a long time and reuse their fonts). With threads that are constantly created and destroyed, or with virtual threads (one per task), each thread would parse the font once and you'd gain nothing.
- Each thread keeps its own parsed fonts: with 12 threads and 3 fonts, 36
TrueTypeFonts in memory, a few MB. Affordable. - They're never closed: they live as long as the application. If your application loads and unloads fonts dynamically, you'll need a clean-up mechanism.
As we'll see in the batch, for parallel generation this optimisation is the most important of all, and not because of CPU time but because of the garbage that parsing fonts generates.
Compression and file size
Size matters: files are stored for years, sent by email and travel across the network. The main levers, ordered by impact:
| Lever | Measured effect | Where we saw it |
|---|---|---|
| Font subsetting | 394,550 → 5,962 bytes per font | 02-03 |
| Image format | JPEG for photos, PNG (Flate) for logos with flat colours | 02-06 |
| Not duplicating resources | One logo per document, not one per page (PdfContext) |
03-04 |
| Object streams and compressed xref | F-2026-0001: 52,416 versus 55,437 bytes (5%); 1,000-page batch: 25.5 versus 27.6 MB (7%) |
01-05 |
| Object stream size | new CompressParameters(20) versus the default (200): 25.65 versus 25.54 MB |
— |
document.save(output); // default: object streams of 200 objects
document.save(output, CompressParameters.NO_COMPRESSION); // classic xref (PDF/A-1, debugging)
document.save(output, new CompressParameters(500)); // larger object streamsChanging the size of the object streams hardly matters; what weighs are the fonts and images. Notice the batch too: 1,000 pages take up 25.5 MB because each of the 500 merged invoices carries its own copy of the logo and the font subsets. If you generate a 1,000-page document in one go (with Paginator), the logo and fonts are saved only once and the file is much, much smaller. Merging documents is convenient, but it doesn't deduplicate resources.
Concurrency
The fundamental rule: PDDocument isn't thread-safe, and neither are the objects hanging off it (PDPage, PDFont, PDPageContentStream...). Never have two threads working on the same document. The correct pattern is one document per task:
ExecutorService pool = Executors.newFixedThreadPool(threads);
List<Future<?>> tasks = new ArrayList<>();
for (Invoice f : invoices) {
tasks.add(pool.submit(() -> {
byte[] pdf = generator.generate(f); // each call creates and closes its own PDDocument
save(f, pdf);
return null;
}));
}
for (Future<?> t : tasks) {
t.get(); // waits and propagates the first exception
}
pool.shutdown();What can be shared between threads in InvoiceLab?
| Object | Shareable? | Why |
|---|---|---|
InvoiceGenerator, Theme, Invoice |
Yes | Immutable or stateless between calls |
Font bytes (InvoiceLabFonts) |
Yes | byte[] in a ConcurrentHashMap, read-only |
PreencodedImage |
Yes | Immutable data; each document receives copies |
Parsed TrueTypeFont |
No | One per thread (ThreadLocal) |
PDDocument, PDFont, PDImageXObject, PdfContext |
No | They belong to one document |
PDFTextStripper, PDFRenderer |
No | They hold state while working; one per task |
How many threads? Generating PDFs is CPU work, so more threads than cores adds nothing, but, as we'll see shortly, the real limit is usually memory before CPU.
The system font cache
There's one situation in which PDFBox looks for fonts on your operating system: when a PDF uses a font that isn't embedded (a Standard 14 font such as Helvetica, or a badly made supplier PDF, 06-01) and it has to be rendered or its glyphs measured. Then FontMappers.instance() goes through all the installed fonts to build an index. The first time, it saves it to a file, .pdfbox.cache, so as not to repeat the work:
INFO FileSystemFontProvider -- Building on-disk font cache, this may take a while
INFO FileSystemFontProvider -- Finished building on-disk font cache, found 2669 fontsMeasured on a fresh JVM, the first lookup of a system font takes 1.2 s building the cache (2,669 fonts) and about 0.24 s when the cache already exists. On a server with thousands of fonts, or in a container that starts from scratch every time, that long second is paid on the first request.
| System property | Effect |
|---|---|
-Dpdfbox.fontcache=/path/folder |
Folder where .pdfbox.cache is stored (by default, the user's home directory and, if it isn't writable, java.io.tmpdir) |
-Dpdfbox.fontcache.skipchecksums=true |
Doesn't verify the font files' checksums when loading the cache |
Recommendations:
- Avoid it by design: InvoiceLab embeds its fonts and never uses Standard 14 fonts in real documents, so it doesn't touch the system cache when generating.
- If your application renders or extracts third-party PDFs, trigger the loading at start-up (a test lookup in an initialisation thread) rather than on the first request, and set
pdfbox.fontcacheto a writable folder. - If applications using PDFBox 2 and 3 coexist on the same machine and user, give them different cache folders: they use different formats and each invalidates the other's (we'll see this in 08-06).
Generating 10,000 invoices in a batch
The BulkInvoices program generates invoices F-2026-0000 to F-2026-9999 (each with between 12 and 31 lines, that is, 1 or 2 pages) with a thread pool and keeps them in memory, writes them to disk or produces them as PDF/A:
/** Invoice number i in the batch: F-2026-0000 ... F-2026-9999, with 12 to 31 lines (1 or 2 pages). */
static Invoice invoice(int i) {
Invoice base = SampleData.invoice(12 + i % 20);
return new Invoice(String.format("F-2026-%04d", i), base.date(), base.issuer(), base.customer(),
base.lines(), base.paymentTerms());
}
public static long generate(DocumentGenerator<Invoice> generator, int n, int threads, Path folder)
throws Exception {
AtomicLong bytes = new AtomicLong();
ExecutorService pool = Executors.newFixedThreadPool(threads);
try {
List<Future<?>> tasks = new ArrayList<>(n);
for (int i = 0; i < n; i++) {
Invoice f = invoice(i);
tasks.add(pool.submit(() -> {
if (folder == null) {
bytes.addAndGet(generator.generate(f).length); // in memory only
} else {
Path target = folder.resolve(f.number() + ".pdf");
generator.generate(f, target); // atomic write (03-04)
bytes.addAndGet(Files.size(target));
}
return null;
}));
}
for (Future<?> t : tasks) {
t.get();
}
} finally {
pool.shutdown();
}
return bytes.get();
}The main method warms up the JVM with 200 invoices, measures the batch with Benchmark and shows the result. Each row is a fresh JVM; in total, 486 MB of PDF are generated (553 MB as PDF/A, because of each invoice's ICC profile and XMP):
| Configuration | Threads | -Xmx |
Time | Invoices/s | Collections |
|---|---|---|---|---|---|
| Original (logo and fonts per document) | 1 | 512 MB | 262 s | 38 | 1,084 |
| Original | 12 | 512 MB | 116 s | 87 | 5,853 |
+ PreencodedImage |
1 | 512 MB | 125 s | 80 | 1,006 |
+ PreencodedImage |
4 | 512 MB | 96 s | 104 | 3,400 |
+ PreencodedImage |
12 | 512 MB | 122 s | 82 | 4,580 |
+ PreencodedImage |
12 | 2 GB | 51 s | 197 | 1,018 |
+ PreencodedImage + TrueTypeFont per thread |
1 | 512 MB | 96 s | 104 | 1,854 |
+ PreencodedImage + TrueTypeFont per thread |
4 | 512 MB | 29 s | 342 | 819 |
+ PreencodedImage + TrueTypeFont per thread |
12 | 512 MB | 37 s | 268 | 644 |
+ PreencodedImage, writing to disk |
12 | 512 MB | 124 s | 80 | 4,605 |
+ PreencodedImage, PDF/A-2b (08-01) |
12 | 512 MB | 145 s | 69 | 5,239 |
+ PreencodedImage |
1 | 64 MB | 349 s | 29 | 52,727 |
+ PreencodedImage |
12 | 128 MB | OutOfMemoryError |
— | — |
+ PreencodedImage + TrueTypeFont per thread |
12 | 128 MB | OutOfMemoryError |
— | — |
What this table teaches us:
- First, eliminate repeated work. Pre-encoding the logo doubled the speed on one thread, and reusing the parsed fonts added another 30%. No parallelism technique gives you so much for so little risk.
- More threads isn't faster. With 12 threads and 512 MB it was slower than with 4 (122 s versus 96 s). The clue is in the last column: 4,580 collections. Each invoice parses three 700 KB fonts and generates a lot of temporary garbage; with 12 threads at once, the collector can't keep up and the threads spend their time waiting for it. With a 2 GB heap, the same code takes 51 s: the problem was memory, not CPU.
- Reducing garbage fixes parallelism. With the fonts already parsed (one per thread), collections drop from 4,580 to 644 and the full batch with 4 threads takes 29 seconds: 9 times faster than the original. With 12 threads it no longer improves (37 s): we've reached the limit of what the machine can do with 512 MB.
- One thread fits in almost nothing. Sequentially, the batch finishes even with a 64 MB heap, although the collector works incredibly hard (52,727 collections, three times the time). Each invoice in progress needs a few MB; with 12 in parallel, 128 MB isn't enough.
- Writing to disk made no measurable difference (124 s versus 122 s): the bottleneck is still generation.
- PDF/A costs 20% more, because the decorator loads and saves each invoice again (08-01). If the batch were PDF/A only, it would be worth integrating the conversion into
BaseGeneratorso as to save just once.
The recommended configuration for InvoiceLab: PreencodedImage, TrueTypeFont per thread, a fixed thread pool of moderate size (on this machine, 4) and a heap sized for the number of threads. For a service, the same thing translates into the semaphore in 08-04.
Processing a 1,000-page PDF
The other typical case is the reverse: an enormous document that has to be read. LargeDocument creates the 1,000-page batch by merging 500 invoices and then goes through it page by page:
/** Extracts the text page by page: a String with the whole document is never built. */
static long text(PDDocument document) throws IOException {
PDFTextStripper stripper = new PDFTextStripper();
long characters = 0;
for (int p = 1; p <= document.getNumberOfPages(); p++) {
stripper.setStartPage(p);
stripper.setEndPage(p);
characters += stripper.getText(document).length(); // process and forget
}
return characters;
}
static long render(PDDocument document) throws IOException {
PDFRenderer renderer = new PDFRenderer(document);
long pixels = 0;
for (int p = 0; p < document.getNumberOfPages(); p++) {
BufferedImage image = renderer.renderImageWithDPI(p, 50, ImageType.RGB);
pixels += (long) image.getWidth() * image.getHeight(); // the image is discarded on each iteration
}
return pixels;
}- A
getTextof the whole document would build aStringof 1.8 million characters; page by page, eachStringis small and is discarded straight away. The same goes for images: never a list of 1,000BufferedImages. - We reuse one
PDFTextStripperand onePDFRendererfor the whole document (on a single thread): creating them per page adds nothing. - You've already seen the results in the previous tables: 3.9 s to extract the text from the 1,000 pages, which works just the same with 128 MB, and 12.9 s to render them at 50 dpi (15.7 s with 128 MB, thanks to the resource cache adapting).
Common Mistakes and Tips
- Optimising without measuring. We'd have bet on compression or the number of threads; the culprit was the logo. Measure first, piece by piece.
- Loading a PDF that's already on disk with
Files.readAllBytes. It doubles the memory for no gain.Loader.loadPDF(File). - Sharing a
PDDocumentor aPDFontbetween threads to save memory. It corrupts the document intermittently and in ways that are hard to debug. Share bytes and immutable data; one document per task. - Using as many threads as cores "just because". With PDF generation, the heap usually saturates before the CPU. Try several pool sizes with your real
-Xmx. - Reading the peak heap as "what I need". With more memory, the JVM takes up more. To find the minimum, run with reduced
-Xmxvalues. - Turning off the resource cache to "save memory" without measuring: in our rendering it tripled the time. It's a soft-reference cache: it already empties itself when needed.
- Embedding full fonts. A one-line document went from 6 KB to 395 KB. Always subset (except in forms where the user will type new text, 05-04).
- Holding
PD*objects in static caches: they retain the whole document. If you need to cache something across documents, cache bytes. - Tip: keep your measurements (scenario, machine, version,
-Xmx, results) alongside the code. When you upgrade PDFBox or change a template, repeat them and compare.
Exercises
Exercise 1. Write a program that extracts the text of the 1,000-page batch on 4 threads, each with its own PDDocument and its own range of 250 pages, and compare the time with single-threaded extraction (3.9 s on our machine).
Exercise 2. PreencodedImage.in stores the 720 × 240-pixel logo in the cache. Work out how much memory the cache entry takes up (compressed bytes of the image and its mask) and compare it with that of the decoded ARGB BufferedImage. What do you conclude?
Exercise 3. Modify BulkInvoices so that, instead of one Future per invoice (10,000 objects in a list), it processes the invoices in blocks of 100 and prints a summary per block. Does the memory change? And the time?
Solutions
Solution 1.
Path pdf = Path.of("output/performance/batch-1000.pdf");
int threads = 4;
ExecutorService pool = Executors.newFixedThreadPool(threads);
List<Future<Long>> parts = new ArrayList<>();
long start = System.nanoTime();
for (int h = 0; h < threads; h++) {
int from = h * 250 + 1;
int to = from + 249;
parts.add(pool.submit(() -> {
try (PDDocument doc = Loader.loadPDF(pdf.toFile())) { // one document per thread
PDFTextStripper stripper = new PDFTextStripper(); // one stripper per thread
long characters = 0;
for (int p = from; p <= to; p++) {
stripper.setStartPage(p);
stripper.setEndPage(p);
characters += stripper.getText(doc).length();
}
return characters;
}
}));
}
long total = 0;
for (Future<Long> f : parts) {
total += f.get();
}
pool.shutdown();
System.out.printf("%,d characters in %d ms%n", total, (System.nanoTime() - start) / 1_000_000);Each thread opens its own PDDocument from the same file: since it's loaded from a File, each one reads on demand and there's no shared data. The total number of characters matches the single-threaded one (1,834,500). The improvement (from 3.9 s to 2.3 s on our machine) doesn't reach ×4: each thread parses the document structure and the fonts on its pages all over again. Typical mistake: sharing one PDDocument among the four threads with different ranges; it may work in one test and fail in the next.
Solution 2.
// Inside PreencodedImage (or with a debugging helper method):
long compressed = data.length + (mask == null ? 0 : mask.data.length);
long decoded = 720L * 240 * 4; // ARGB: 4 bytes per pixelThe ARGB BufferedImage takes up 720 × 240 × 4 = 691,200 bytes. The cache entry takes up whatever the Flate streams of the RGB image and its mask take up, in the order of tens of KB (in the PDF, the logo's RGB stream is 11,930 bytes, as we saw in the Preflight report in 08-01). Conclusion: caching the compressed result is far cheaper in memory than caching the decoded image, and it's also what the PDF needs. That's why the cache stores bytes and not BufferedImages.
Solution 3.
int block = 100;
for (int blockStart = 0; blockStart < n; blockStart += block) {
List<Future<Integer>> tasks = new ArrayList<>(block);
for (int i = blockStart; i < Math.min(n, blockStart + block); i++) {
Invoice f = invoice(i);
tasks.add(pool.submit(() -> generator.generate(f).length));
}
long blockBytes = 0;
for (Future<Integer> t : tasks) {
blockBytes += t.get();
}
System.out.printf("Invoices %d-%d: %,d bytes%n", blockStart, blockStart + tasks.size() - 1, blockBytes);
}The memory used by the list of Futures and pending invoices goes down (100 instead of 10,000 at a time), and the program also reports its progress and can resume from the last completed block if something fails. The time changes little: at the end of each block some threads wait for the others to finish, which costs a small percentage. With 10,000 small invoices the memory difference is modest; with millions of invoices, or with large invoice data, processing in blocks is essential.
Conclusion
PDFBox 3 reads documents on demand, keeps what it has read until you close them, stores new streams in a configurable cache (IOUtils.createMemoryOnlyStreamCache() or createTempFileOnlyStreamCache()) and speeds up rendering with a soft-reference ResourceCache that adapts to the available memory. With real measurements we've seen that the cost of an invoice wasn't where we expected: the logo and font parsing accounted for most of it, and eliminating that repeated work with PreencodedImage and a TrueTypeFont per thread made the 10,000-invoice batch nine times faster. We've also learnt that in parallel generation memory runs out before CPU, that a document belongs to a single thread and that huge PDFs are processed page by page.
With these pieces we can now put InvoiceLab behind an API without fear of the load. In the next lesson we'll build a REST service with Spring Boot that generates invoices from JSON, signs them on request, merges user-uploaded PDFs with every precaution and applies the concurrency limits we've just measured.
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
