At the end of the month, Nebula Distribution's accounts department has to send all the issued invoices to the external accountants. Sending thirty separate attachments is awkward; what they ask for is a single batch PDF with a cover page that works as an index. And the other way round: the warehouse scanner produces a single PDF with all the day's delivery notes, which has to be split into one document per delivery note, and the accountants' mail server rejects attachments above a certain size. In this lesson you'll learn to merge documents with PDFMergerUtility (on disk or in memory) and to split them with Splitter (by number of pages, by range, by size and by separator sheets). We'll reuse the generator from module 3 to create the batch's cover page, and we'll carefully close every document that gets opened along the way.
Contents
- Merging PDFs: what it really involves
PDFMergerUtility: merging files into one- Merging in memory or on disk: the stream cache
appendDocument: merging one document at a time- Project: the monthly invoice batch with a cover page and index
- Splitting PDFs with
Splitter - Splitting by number of pages and by range
- Splitting by size
- Splitting a scanned batch by separator sheets
- Closing all the resulting documents
Merging PDFs: what it really involves
In lesson 04-03 you saw that importPage copies a page but leaves its resources pointing to the source document. Merging complete documents is more demanding, because every PDF brings with it:
- Its page tree, with content streams, fonts and images.
- Document-level elements: bookmarks (outline), forms (AcroForm), named destinations, tagging structure (accessible PDF), XMP metadata…
- Its own object numbering: object
12 0in one document has nothing to do with12 0in another.
That's why PDFBox provides a dedicated utility, PDFMergerUtility (package org.apache.pdfbox.multipdf), which deep-clones the objects of each source into the target document (renumbering them) and combines the document-level elements: it concatenates the bookmarks, merges forms and structure, and so on.
| Tool | Copies | Document-level elements | Source open until saving |
|---|---|---|---|
importPage (04-03) |
A page (resources shared with the source) | No | Yes |
PDFMergerUtility.appendDocument |
A complete document (cloned) | Yes | No |
PDFMergerUtility.mergeDocuments |
A list of documents | Yes | Handled by the utility itself |
PDFMergerUtility: merging files into one
The simplest way: specify the sources and the target, then call mergeDocuments. To try it out, the MonthlyInvoiceBatch program in section 5 generates five January invoices in output/2026-01/.
package com.invoicelab.examples;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.stream.Stream;
import org.apache.pdfbox.io.IOUtils;
import org.apache.pdfbox.multipdf.PDFMergerUtility;
public class MergeInvoices {
public static void main(String[] args) throws IOException {
List<File> invoices;
try (Stream<Path> files = Files.list(Path.of("output/2026-01"))) {
invoices = files.filter(p -> p.toString().endsWith(".pdf")).sorted().map(Path::toFile).toList();
}
// 1) To a file, with the stream cache in memory
PDFMergerUtility merger = new PDFMergerUtility();
for (File f : invoices) {
merger.addSource(f);
}
merger.setDestinationFileName("output/january-merged.pdf");
merger.mergeDocuments(IOUtils.createMemoryOnlyStreamCache());
System.out.printf("To file: %,d bytes%n", Files.size(Path.of("output/january-merged.pdf")));
// 2) To memory (byte[]), with the stream cache in temporary files
PDFMergerUtility memoryMerger = new PDFMergerUtility();
for (File f : invoices) {
memoryMerger.addSource(f);
}
ByteArrayOutputStream output = new ByteArrayOutputStream();
memoryMerger.setDestinationStream(output);
memoryMerger.mergeDocuments(IOUtils.createTempFileOnlyStreamCache());
byte[] pdf = output.toByteArray();
System.out.printf("To memory: %,d bytes%n", pdf.length);
}
}Step by step:
Files.list+sorted(): the order of the sources is the order of the final document.Files.listdoesn't guarantee any order, so we sort by name (F-2026-0001.pdf,F-2026-0002.pdf…). TheStreamgoes inside atrybecause it keeps the directory open.addSourceaccepts aFile, aString(path) or aRandomAccessRead(for PDFs that are already in memory; you'll see this in exercise 3). The utility doesn't open anything yet: it only records the sources.- The target is set with
setDestinationFileName(a file) or withsetDestinationStream(anyOutputStream, such as aByteArrayOutputStreamto get abyte[]). mergeDocuments(StreamCacheCreateFunction)opens each source, adds it to the target, saves the result and closes everything. The parameter decides where temporary data is stored (next section).- The utility isn't reset after
mergeDocuments: if you call it again, it will merge the same sources again. Create a new instance for each merge, as in the example. - The result (247 KB) is slightly smaller than the sum of the five files (252 KB): there's a single xref table and a single catalog. Fonts, on the other hand, aren't deduplicated: each invoice brings its own subset of DejaVu Sans, with different glyphs.
Two configuration options worth knowing, although we don't need them for invoices:
| Option | Values | What for |
|---|---|---|
setDocumentMergeMode |
PDFBOX_LEGACY_MODE (default), OPTIMIZE_RESOURCES_MODE |
The optimised mode opens and closes each source on the fly and reduces memory use; the classic mode keeps them open until the end and is required for merging tagged documents (with a structure tree) |
setAcroFormMergeMode |
PDFBOX_LEGACY_MODE (default), JOIN_FORM_FIELDS_MODE |
What to do if two documents have form fields with the same name: rename them or join them into a single field (forms in module 5) |
Merging in memory or on disk: the stream cache
When merging, PDFBox needs space for the target document's streams (content, images, fonts). The StreamCacheCreateFunction decides where:
| Call | Where it stores temporary data | When to use it |
|---|---|---|
IOUtils.createMemoryOnlyStreamCache() |
In memory (unlimited) | Small or medium-sized documents; the fastest option |
IOUtils.createTempFileOnlyStreamCache() |
In temporary files | Batches of hundreds of pages with images, or servers with little memory |
MemoryUsageSetting.setupMixed(bytes).streamCache |
In memory up to a limit, then on disk | A configurable middle ground |
null |
In memory, unlimited | Equivalent to the first one |
Notice that this choice is independent of the target: in the example, the first merge writes to a file with an in-memory cache, and the second produces a byte[] with an on-disk cache. The IOUtils and MemoryUsageSetting classes live in org.apache.pdfbox.io (the pdfbox-io module). In lesson 08-03 we'll measure the impact of each option.
appendDocument: merging one document at a time
mergeDocuments is convenient, but it doesn't let you step in between documents. That's what this is for:
targetandsourcearePDDocumentinstances that you open and close yourself.- The source's objects are cloned into the target, so, unlike
importPage, you can close the source right afterappendDocument, before saving the target. We'll confirm this in the batch. - Between one call and the next you can do whatever you like with
target: add a blank page, stamp a separator, note down the page on which each document starts…
Project: the monthly invoice batch with a cover page and index
We want batch-2026-01.pdf with:
- A cover page with the logo, the period, a summary and an index table: invoice number, date, customer, total and the page on which it starts within the PDF.
- Then, all the month's invoices.
- Ready for double-sided printing: each invoice starts on a new sheet.
flowchart LR
A["Issued invoices<br/>(PDFs on disk)"] --> B["1. Count pages<br/>(round up to even)"]
B --> C["2. Provisional cover<br/>how many pages does it take?"]
C --> D["3. Final cover<br/>with real page numbers"]
D --> E["4. appendDocument for<br/>each invoice + blank sheets"]
E --> F["batch-2026-01.pdf"]
The model: InvoiceBatch
In com.invoicelab.model, next to Invoice:
package com.invoicelab.model;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.List;
/** A set of invoices delivered together (for example, the month's invoices) in a single PDF. */
public record InvoiceBatch(String period, LocalDate date, Customer issuer, List<Entry> entries) {
/** An invoice within the batch and the page of the merged PDF on which it starts. */
public record Entry(Invoice invoice, int startPage, int pages) {
}
public InvoiceBatch {
entries = List.copyOf(entries);
}
public BigDecimal total() {
return entries.stream().map(e -> e.invoice().total()).reduce(BigDecimal.ZERO, BigDecimal::add);
}
}As in Invoice, the total calculation lives in the model: reduce adds up the totals of all the invoices, starting from zero.
The cover page: one more generator
The cover page is a business document just like the invoice or the delivery note, so we create it with the architecture from module 3: a subclass of BaseGenerator (lesson 03-04) that inherits pagination, the «Page X of N» footer and saving.
package com.invoicelab.generator;
// imports: InvoiceBatch, Alignment, Column, Formats, Images, Measures, TextMetrics, Paginator,
// IOException, ArrayList, List, PDFont, PDImageXObject
/** Cover page and index for an invoice batch. */
public final class BatchCoverGenerator extends BaseGenerator<InvoiceBatch> {
public BatchCoverGenerator(Theme theme) {
super(theme);
}
@Override
protected void validate(InvoiceBatch batch) {
super.validate(batch);
if (batch.entries().isEmpty()) {
throw new IllegalArgumentException("Batch " + batch.period() + " has no invoices");
}
}
@Override
protected Paginator.PageHeader firstPageHeader(PdfContext ctx, InvoiceBatch b) throws IOException {
PDImageXObject logo = ctx.image("/img/logo-nebula.png");
PDFont bold = ctx.fonts().bold();
PDFont regular = ctx.fonts().regular();
return (cs, page, box, n) -> {
float height = Measures.mm(16);
Images.drawFitted(cs, logo, box.left(), box.top(), Measures.mm(45), height);
cs.saveGraphicsState();
cs.setNonStrokingColor(ctx.theme().primary());
TextMetrics.writeAligned(cs, bold, 18, "INVOICE BATCH", box.right(),
box.top() - Measures.mm(7), Alignment.RIGHT);
cs.setNonStrokingColor(ctx.theme().secondaryText());
TextMetrics.writeAligned(cs, regular, 10, "Period " + b.period() + " · Issued on "
+ Formats.date(b.date()), box.right(), box.top() - Measures.mm(13), Alignment.RIGHT);
cs.restoreGraphicsState();
return box.top() - height - Measures.mm(8);
};
}
@Override
protected Paginator.PageHeader nextPagesHeader(PdfContext ctx, InvoiceBatch b) throws IOException {
PDFont bold = ctx.fonts().bold();
return (cs, page, box, n) -> {
cs.saveGraphicsState();
cs.setNonStrokingColor(ctx.theme().primary());
TextMetrics.writeAligned(cs, bold, 11, "Batch " + b.period() + " (continued)",
box.left(), box.top() - Measures.mm(4), Alignment.LEFT);
cs.restoreGraphicsState();
return box.top() - Measures.mm(10);
};
}
@Override
protected void compose(PdfContext ctx, InvoiceBatch b) throws IOException {
String summary = b.issuer().companyName() + " hereby delivers " + b.entries().size()
+ " invoices for the period " + b.period() + " for a total amount of "
+ Formats.euros(b.total()) + " (VAT included). Each invoice keeps its own page "
+ "numbering; the «Page» column shows where it starts within this PDF.";
List<Column> columns = List.of(
Column.fixed("Invoice", Measures.mm(28), Alignment.LEFT),
Column.fixed("Date", Measures.mm(22), Alignment.LEFT),
Column.relative("Customer", 1, Alignment.LEFT),
Column.fixed("Total", Measures.mm(28), Alignment.RIGHT),
Column.fixed("Page", Measures.mm(16), Alignment.RIGHT));
List<List<String>> rows = new ArrayList<>();
for (InvoiceBatch.Entry e : b.entries()) {
rows.add(List.of(e.invoice().number(), Formats.date(e.invoice().date()),
e.invoice().customer().companyName(), Formats.euros(e.invoice().total()),
String.valueOf(e.startPage())));
}
ctx.place(new ParagraphBlock("SUMMARY", summary), new TableBlock(columns, rows, null));
}
@Override
protected String footerText(InvoiceBatch b) {
return b.issuer().companyName() + " · Batch " + b.period();
}
}- The two headers are
Paginator.PageHeaderlambdas (lesson 03-02) that return theywhere the content can start. The first page carries the logo, title and period; the following pages, a continuation line. composereusesParagraphBlockandTableBlock: with hundreds of invoices, the index table spreads across several pages on its own, with a repeated header.- We haven't written a single line of pagination, footers or saving: that's the advantage of the template method.
Merging: the InvoiceBatches class
package com.invoicelab.editing;
// imports: BatchCoverGenerator, Theme, Customer, Invoice, InvoiceBatch, IOException, Path, LocalDate,
// ArrayList, List, Loader, PDFMergerUtility, PDDocument
/** Merges several issued invoices into a single PDF with a cover page and index. */
public final class InvoiceBatches {
/** An invoice that has already been issued: its data and the PDF that was sent. */
public record Issued(Invoice invoice, Path pdf) {
}
private InvoiceBatches() {
}
public static void create(String period, LocalDate date, Customer issuer, List<Issued> issued,
boolean duplex, Path target) throws IOException {
BatchCoverGenerator generator = new BatchCoverGenerator(Theme.nebula());
// 1) Pages of each invoice (rounded up to even when printing double-sided)
List<Integer> pages = new ArrayList<>();
for (Issued i : issued) {
try (PDDocument document = Loader.loadPDF(i.pdf().toFile())) {
pages.add(roundUp(document.getNumberOfPages(), duplex));
}
}
// 2) First pass: how many pages does the cover take? (the index doesn't yet know where each invoice starts)
InvoiceBatch provisional = batch(period, date, issuer, issued, pages, 0);
int coverPages;
try (PDDocument cover = Loader.loadPDF(generator.generate(provisional))) {
coverPages = roundUp(cover.getNumberOfPages(), duplex);
}
// 3) Second pass: final cover, written to target
generator.generate(batch(period, date, issuer, issued, pages, coverPages), target);
// 4) Append each invoice after the cover
PDFMergerUtility merger = new PDFMergerUtility();
PdfEditor.edit(target, target, PdfEditor.Mode.FULL, batch -> {
if (duplex) {
Pages.padForDuplex(batch);
}
for (Issued i : issued) {
try (PDDocument invoice = Loader.loadPDF(i.pdf().toFile())) {
merger.appendDocument(batch, invoice);
}
if (duplex) {
Pages.padForDuplex(batch);
}
}
});
}
private static InvoiceBatch batch(String period, LocalDate date, Customer issuer, List<Issued> issued,
List<Integer> pages, int coverPages) {
List<InvoiceBatch.Entry> entries = new ArrayList<>();
int next = coverPages + 1;
for (int i = 0; i < issued.size(); i++) {
entries.add(new InvoiceBatch.Entry(issued.get(i).invoice(), next, pages.get(i)));
next += pages.get(i);
}
return new InvoiceBatch(period, date, issuer, entries);
}
private static int roundUp(int pages, boolean duplex) {
return duplex && pages % 2 != 0 ? pages + 1 : pages;
}
}The keys to the design:
- The chicken-and-egg problem. The index has to say on which page each invoice starts, but that depends on how many pages the cover takes… which depends on the index. We solve it in two passes: the first generates the cover with provisional numbers (
0) only to count its pages; since the number of rows is the same, the second pass takes up the same space and now carries the correct numbers. The first pass doesn't touch the disk:generate(T)returns abyte[]that we load withLoader.loadPDF(byte[]). - The
batchmethod calculates each invoice's start page cumulatively: the first one starts after the cover (coverPages + 1), and each one adds its pages (rounded up to even for double-sided printing). - Reuse: step 3 uses
generate(T, Path)(the atomic save from module 3) and step 4 usesPdfEditor.editwith the same source and target (lesson 04-01) to append the invoices to the freshly written cover. - Each invoice is closed right after
appendDocument, before saving: this is safe becauseappendDocumentclones the objects. That way only one invoice is open at a time, even if the batch has a hundred. Pages.padForDuplex(lesson 04-03) is called after the cover and after each invoice: if the running total is odd, it adds a blank sheet and the next invoice starts on the front of a sheet.- The
PDFMergerUtilityis created only once and reused for every call toappendDocument.
The main program
public static void main(String[] args) throws IOException {
// 1) "Issue" five January invoices with different numbers of lines
InvoiceGenerator generator = new InvoiceGenerator(Theme.nebula());
Path folder = Path.of("output/2026-01");
int[] lines = { 12, 30, 5, 45, 18 };
List<InvoiceBatches.Issued> issued = new ArrayList<>();
for (int i = 0; i < lines.length; i++) {
Invoice base = SampleData.invoice(lines[i]);
Invoice invoice = new Invoice(String.format("F-2026-%04d", i + 1), LocalDate.of(2026, 1, 5 + i * 6),
base.issuer(), CUSTOMERS[i % CUSTOMERS.length], base.lines(), base.paymentTerms());
Path pdf = folder.resolve(invoice.number() + ".pdf");
generator.generate(invoice, pdf);
issued.add(new InvoiceBatches.Issued(invoice, pdf));
}
// 2) Merge them into a batch with a cover page, ready for double-sided printing
Path target = Path.of("output/batch-2026-01.pdf");
InvoiceBatches.create("2026-01", LocalDate.of(2026, 2, 1), SampleData.NEBULA, issued, true, target);
}CUSTOMERS is an array with Example Hardware and two more fictional customers ("Fictional Construction Ltd." and "Test Workshops Inc."), so that the index doesn't keep repeating the same name. Result:
Batch: 14 pages, 284,284 bytes
F-2026-0001: 1 page, 48,984 bytes
F-2026-0002: 2 pages, 52,184 bytes
F-2026-0003: 1 page, 46,844 bytes
F-2026-0004: 3 pages, 54,343 bytes
F-2026-0005: 2 pages, 50,051 bytesThe cover takes 1 page (+1 blank), and the invoices 1+1, 2, 1+1, 3+1 and 2: 14 in total. The cover's index table shows that the invoices start on pages 3, 5, 7, 9 and 13, all odd, that is, on the front of a sheet.
A batch of a hundred invoices is much easier to navigate with bookmarks (the viewer's side panel with one entry per invoice). We'll create them in lesson 06-05;
appendDocumentalready concatenates whatever bookmarks each source brings.
Splitting PDFs with Splitter
The reverse operation is done by org.apache.pdfbox.multipdf.Splitter. Its split(PDDocument) method returns a List<PDDocument> with the resulting documents, new and open.
| Method | Meaning | Default |
|---|---|---|
setSplitAtPage(int n) |
Each resulting document has n pages (the last one, whatever is left over) |
1 (one page per document) |
setStartPage(int) |
First page processed (1-based) | 1 |
setEndPage(int) |
Last page processed (1-based, inclusive) | The last one |
splitAtPage(int) (protected) |
Decides whether the (zero-based) page starts a new document; overridden for custom criteria | Every n pages |
processPage(PDPage) (protected) |
Copies a page into the current document | — |
A warning from the PDFBox documentation that dictates how you must work: the resulting documents share resources with the original. Therefore:
- You must save all of them before closing any, including the source document.
- If you want to keep modifying them, save them and load them again.
- Don't save them encrypted directly.
This contrasts with PDFMergerUtility, which does clone. All of InvoiceLab's splitting operations will live in the com.invoicelab.editing.Splitting class, with a helper method that saves and closes safely (section 10).
Splitting by number of pages and by range
/** Parts of n pages (the last one may have fewer). */
public static List<Path> everyNPages(Path source, int n, Path folder) throws IOException {
try (PDDocument document = Loader.loadPDF(source.toFile())) {
Splitter splitter = new Splitter();
splitter.setSplitAtPage(n);
return saveAndClose(splitter.split(document), folder, baseName(source));
}
}
/** Extracts pages from..to (1-based, both inclusive) into a single document. */
public static Path extract(Path source, int from, int to, Path target) throws IOException {
try (PDDocument document = Loader.loadPDF(source.toFile())) {
Splitter splitter = new Splitter();
splitter.setStartPage(from);
splitter.setEndPage(to);
splitter.setSplitAtPage(to - from + 1); // the whole range in a single document
List<PDDocument> parts = splitter.split(document);
try {
save(parts.get(0), target);
} finally {
closeAll(parts);
}
return target;
}
}- In
everyNPages,saveAndCloseruns inside the source document'stry: the parts are saved while the source is still open, asSplitterrequires. - In
extract,setSplitAtPage(to - from + 1)makes the whole range fit into a single document. Without that line you'd get one page per document (the default is 1). setStartPageandsetEndPageare 1-based, like the viewer's numbering. If you callsetEndPagewith a value lower than the start, anIllegalArgumentExceptionis thrown.
Splitting by size
Many mail servers reject large attachments. We want parts that don't exceed a byte limit, without separating consecutive pages. The problem is that a PDF's size isn't the sum of its pages' sizes: fonts and images are shared. We use a conservative estimate:
- We split into one-page documents and save each one to an
OutputStreamthat only counts bytes (it stores nothing). - We group consecutive pages as long as the sum doesn't exceed the limit.
- We extract each group with
extract.
public static List<Path> bySize(Path source, long maxBytes, Path folder) throws IOException {
try (PDDocument document = Loader.loadPDF(source.toFile())) {
// 1) Size of each page saved separately
List<Long> sizes = new ArrayList<>();
List<PDDocument> singles = new Splitter().split(document); // one page per document
try {
for (PDDocument single : singles) {
sizes.add(measure(single));
}
} finally {
closeAll(singles);
}
// 2) Group consecutive pages while they fit
List<int[]> groups = new ArrayList<>(); // {first, last}, 1-based
int start = 1;
long accumulated = 0;
for (int i = 0; i < sizes.size(); i++) {
if (accumulated > 0 && accumulated + sizes.get(i) > maxBytes) {
groups.add(new int[] { start, i });
start = i + 1;
accumulated = 0;
}
accumulated += sizes.get(i);
}
groups.add(new int[] { start, sizes.size() });
// 3) Extract each group
List<Path> result = new ArrayList<>();
String base = baseName(source);
for (int g = 0; g < groups.size(); g++) {
Path target = folder.resolve(String.format("%s-part%02d.pdf", base, g + 1));
result.add(extract(source, groups.get(g)[0], groups.get(g)[1], target));
}
return result;
}
}
private static long measure(PDDocument document) throws IOException {
CountingOutputStream counter = new CountingOutputStream();
document.save(counter);
return counter.bytes;
}
/** OutputStream that stores nothing: it only counts the bytes. */
private static final class CountingOutputStream extends OutputStream {
long bytes;
@Override
public void write(int b) {
bytes++;
}
@Override
public void write(byte[] b, int off, int len) {
bytes += len;
}
}- Why the estimate is conservative: each single page includes its own copy of the fonts. When several pages of the same invoice are put together, the font is stored only once, so the real document takes up less than the estimated sum. The result always stays below the limit (except for a page that exceeds it all by itself: it's left alone in its own part, thanks to the
accumulated > 0condition). - The index
iingroups.add(new int[] { start, i }): when pagei(zero-based) doesn't fit, the group ends at the previous page, whose 1-based number is preciselyi. CountingOutputStreamalso overrideswrite(byte[], int, int): PDFBox writes in blocks, and counting byte by byte with the default version would be very slow.
Splitting a scanned batch by separator sheets
The warehouse scanner digitises all the day's delivery notes into a single PDF. Between one delivery note and the next, the operator inserts a separator sheet. We want one PDF per delivery note, without the separators.
We need two things: to detect the separators and to cut at them. To cut using a custom criterion, you extend Splitter and override its protected methods:
/** Splitter that starts a new document after each separator and discards the separators. */
private static final class SeparatorSplitter extends Splitter {
private final IntPredicate isSeparator;
private int index = 0; // (zero-based) index of the page being processed
private boolean pendingNew = false;
SeparatorSplitter(IntPredicate isSeparator) {
this.isSeparator = isSeparator;
}
@Override
protected void processPage(PDPage page) throws IOException {
if (isSeparator.test(index++)) {
pendingNew = true; // not copied: it only marks the cut
} else {
super.processPage(page); // will call splitAtPage(...)
}
}
@Override
protected boolean splitAtPage(int pageNumber) {
boolean cut = pendingNew;
pendingNew = false;
return cut;
}
}How it fits in with Splitter:
splitcallsprocessPagefor every page. The original version creates a new document ifsplitAtPagereturnstrue(or if there isn't one yet) and copies the page into it.- Our version intercepts the separators: it doesn't call
super.processPage, so they aren't copied; they only setpendingNew. - For normal pages,
super.processPageaskssplitAtPage, which answerstrueonly once after each separator. Two consecutive separators don't produce empty documents, because documents are only created when a real page is copied. IntPredicateis Java's functional interface for "a condition on anint"; that way the splitter doesn't know how a separator is detected.
To detect them, in our simulated batch (GenerateScannedBatch creates 8 pages: a 2-page delivery note, separator, a 1-page one, separator, a 3-page one) the separator sheet contains the text #SEPARATOR#, which we search for with PDFTextStripper:
public static List<Path> bySeparators(Path source, String marker, Path folder) throws IOException {
try (PDDocument document = Loader.loadPDF(source.toFile())) {
PDFTextStripper stripper = new PDFTextStripper();
boolean[] separator = new boolean[document.getNumberOfPages()];
for (int i = 0; i < separator.length; i++) {
stripper.setStartPage(i + 1);
stripper.setEndPage(i + 1);
separator[i] = stripper.getText(document).contains(marker);
}
Splitter splitter = new SeparatorSplitter(i -> separator[i]);
return saveAndClose(splitter.split(document), folder, baseName(source));
}
}PDFTextStripper extracts the text from a range of pages; we'll study it in depth in lesson 06-01. In a real scan the pages are images with no text: the separator sheet usually carries a barcode, which is detected by rendering the page to an image (lesson 06-04) and reading it with ZXing (lesson 03-03), or with OCR. Thanks to the IntPredicate, only the way the separator array is filled would change.
Closing all the resulting documents
split returns several open PDDocument instances and all of them must be closed, even if saving one of them fails. A try-with-resources doesn't work for a list of variable size, so we do it by hand:
/** Saves each part as base-01.pdf, base-02.pdf... and then closes them all. */
public static List<Path> saveAndClose(List<PDDocument> parts, Path folder, String base) throws IOException {
try {
List<Path> paths = new ArrayList<>();
for (int i = 0; i < parts.size(); i++) {
Path target = folder.resolve(String.format("%s-%02d.pdf", base, i + 1));
save(parts.get(i), target);
paths.add(target);
}
return paths;
} finally {
closeAll(parts);
}
}
private static void closeAll(List<PDDocument> documents) throws IOException {
IOException first = null;
for (PDDocument d : documents) {
try {
d.close();
} catch (IOException e) {
if (first == null) {
first = e;
}
}
}
if (first != null) {
throw first;
}
}- The
finallyguarantees closing whether everything goes well orsavethrows an exception halfway through. closeAllkeeps closing even if aclose()fails, and at the end rethrows the first exception: no document is left open because of another one.savecreates the folder if it doesn't exist and writes withdocument.save(OutputStream);baseNamestrips the.pdfextension from the source name.
The SplitDocuments program applies the four kinds of splitting to the batch and to the scanned lot:
Every 4 pages:
batch-2026-01-01.pdf 4 pages 85,645 bytes
batch-2026-01-02.pdf 4 pages 97,069 bytes
batch-2026-01-03.pdf 4 pages 53,692 bytes
batch-2026-01-04.pdf 2 pages 49,543 bytes
Cover only:
cover.pdf 2 pages 37,984 bytes
Max. 120 KB:
batch-2026-01-part01.pdf 4 pages 85,645 bytes
batch-2026-01-part02.pdf 2 pages 51,679 bytes
batch-2026-01-part03.pdf 3 pages 91,862 bytes
batch-2026-01-part04.pdf 3 pages 50,503 bytes
batch-2026-01-part05.pdf 2 pages 49,543 bytes
By separators:
scanned-batch-01.pdf 2 pages 1,058 bytes
scanned-batch-02.pdf 1 page 888 bytes
scanned-batch-03.pdf 3 pages 1,230 bytesNotice that all the "by size" parts end up well below 120 KB: that's the price of the conservative estimate. And that splitting doesn't reduce the total: four parts of the batch add up to more than the whole batch, because each part embeds its fonts again.
Common Mistakes and Tips
- Relying on the order of
Files.listorFile.listFiles. It isn't guaranteed; always sort the sources before merging. - Reusing a
PDFMergerUtilityaftermergeDocuments. The sources you added are still there and would be merged again. Use one instance per merge (appendDocument, however, can be called many times). - Closing the original document before saving the
Splitterparts. The parts share resources with it: save them all first. - Not closing the parts. Each
PDDocumentholds on to memory (and sometimes temporary files). Use afinally, as insaveAndClose. - Expecting merging to reduce the size. Each document's subset fonts aren't merged; ten merged invoices take up almost the same as the ten separately.
- Calculating the index before knowing how many pages the cover takes. Do two passes, as
InvoiceBatches.createdoes. - Tip: after merging third-party documents, check the log. PDFBox warns about problems with forms or structure (for example, fields with duplicate names) instead of failing.
Exercises
Exercise 1. Modify the MonthlyInvoiceBatch program so that it also generates a batch per customer: a file batch-2026-01-<VATID>.pdf for each customer, containing only their invoices. Use InvoiceBatches.create without modifying it.
Exercise 2. The accountants send back the batch and ask you to recover the invoices separately. Knowing from the index that they start on pages 3, 5, 7, 9 and 13 and that they have 1, 2, 1, 3 and 2 pages, write a program that extracts them to output/separated/F-2026-000N.pdf with Splitting.extract, without the blank sheets.
Exercise 3. A web service generates three invoices (with 8, 25 and 40 lines) and must return them merged in a byte[], without writing anything to disk. Write it with PDFMergerUtility.
Solutions
Solution 1.
Map<String, List<InvoiceBatches.Issued>> byCustomer = issued.stream()
.collect(Collectors.groupingBy(i -> i.invoice().customer().taxId(),
TreeMap::new, Collectors.toList()));
for (Map.Entry<String, List<InvoiceBatches.Issued>> group : byCustomer.entrySet()) {
Path target = Path.of("output/batch-2026-01-" + group.getKey() + ".pdf");
InvoiceBatches.create("2026-01", LocalDate.of(2026, 2, 1), SampleData.NEBULA, group.getValue(), true, target);
}Collectors.groupingBy groups the invoices by VAT ID; passing TreeMap::new sorts the groups by VAT ID so that the files are always generated in the same order, and Collectors.toList() keeps the original order within each group (by invoice number). With the example data you get three batches: J00000000 (invoices 1 and 4), B11111111 (2 and 5) and A22222222 (3). Using the VAT ID rather than the company name in the file name avoids spaces and characters such as «ñ» or «é».
Solution 2.
String[] numbers = { "F-2026-0001", "F-2026-0002", "F-2026-0003", "F-2026-0004", "F-2026-0005" };
int[] start = { 3, 5, 7, 9, 13 };
int[] pages = { 1, 2, 1, 3, 2 };
for (int i = 0; i < numbers.length; i++) {
Path target = Path.of("output/separated", numbers[i] + ".pdf");
Splitting.extract(Path.of("output/batch-2026-01.pdf"), start[i], start[i] + pages[i] - 1, target);
}The last page of each invoice is start + pages - 1 (a 3-page invoice starting on page 9 ends on page 11). The blank sheets (4, 8 and 12, plus page 2 of the cover) are left out because we use each invoice's real number of pages, not the even-rounded figure stored in InvoiceBatch.Entry. You can check with PDFTextStripper that each file contains its invoice number. Each call to extract reloads the batch: for a hundred invoices it would be better to load it once and use one Splitter per range on the same document.
Solution 3.
public static byte[] mergeInMemory(List<Invoice> invoices) throws IOException {
InvoiceGenerator generator = new InvoiceGenerator(Theme.nebula());
PDFMergerUtility merger = new PDFMergerUtility();
for (Invoice invoice : invoices) {
byte[] pdf = generator.generate(invoice); // DocumentGenerator: no disk
merger.addSource(new RandomAccessReadBuffer(pdf)); // org.apache.pdfbox.io
}
ByteArrayOutputStream output = new ByteArrayOutputStream();
merger.setDestinationStream(output);
merger.mergeDocuments(IOUtils.createMemoryOnlyStreamCache());
return output.toByteArray();
}
// Usage
byte[] merged = mergeInMemory(List.of(SampleData.invoice(8), SampleData.invoice(25), SampleData.invoice(40)));
try (PDDocument d = Loader.loadPDF(merged)) {
System.out.println(d.getNumberOfPages() + " pages"); // 5 pages
}RandomAccessReadBuffer wraps a byte[] as a read source (lesson 01-04), and addSource(RandomAccessRead) accepts it just like any file. With the in-memory cache and the target in a ByteArrayOutputStream, everything happens in RAM: this is what the REST service in lesson 08-04 will do.
Conclusion
You now know how to combine and separate documents. PDFMergerUtility deep-clones each source into the target, with mergeDocuments for straightforward merges (to a file or to a byte[], with the stream cache in memory or on disk) and appendDocument when you need to step in between one document and the next. With it and the generator from module 3 you've built the monthly invoice batch with a cover page, a page index calculated in two passes and blank sheets for double-sided printing. Splitter, for its part, splits by number of pages or by range, and by extending it you've split by size and by separator sheets, always saving the parts before closing the original and closing all of them in a finally.
In the next lesson we'll take a further step in combining documents: instead of putting some pages after others, we'll put them on top of one another. We'll print invoices onto the corporate letterhead with Overlay, turn pages into reusable objects with LayerUtility and PDFormXObject, create optional content layers that the user can show or hide, and place two pages on one sheet.
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
