In the previous lesson we put some documents after others. Now we'll put them on top of one another. Nebula Distribution's marketing department has designed a PDF letterhead (a coloured strip, a decorative motif and the company registration details at the foot) and wants every invoice to be printed on it, without touching the generator. The accountants want a receipt stamp on every page of the batch, and the accounts department wants a single invoice to serve as either "Original" or "Customer copy" depending on what is switched on in the viewer. In this lesson you'll learn to overlay pages with Overlay, to turn pages into reusable objects (PDFormXObject) with LayerUtility, to create optional content (layers that are shown or hidden, even only when printing) and to place several pages on one sheet (N-up imposition). The new utilities will make up the Layers class.

Contents

  1. Form XObjects: reusable content
  2. Overlay: laying one PDF over another
  3. Letterhead: invoices on the corporate background
  4. LayerUtility: importing a page as a form XObject
  5. A stamp designed once and drawn on many pages
  6. Optional content: groups, layers and marked content
  7. "Original" and "Customer copy" layers
  8. A mark that only appears when printing
  9. Imposition: two pages on one sheet
  10. The Layers class

Form XObjects: reusable content

All the techniques in this lesson rely on a PDF object you already use without knowing it: the XObject. In lesson 02-06 you drew images with drawImage, which internally adds the image to the page resources as an /XObject and paints it with the Do operator. There's another type of XObject, the form XObject (PDFormXObject in PDFBox): instead of pixels, it contains a content stream with its own resources, like a mini page.

flowchart LR
    subgraph Page["Page 1, 2, 3..."]
        C["Content stream:<br/>q 1 0 0 1 400 30 cm<br/>/Fm1 Do<br/>Q"]
    end
    subgraph Resources["/Resources /XObject"]
        F["/Fm1 → form XObject<br/>/BBox [0 0 204 26]<br/>stream: box + text<br/>/Resources: font"]
    end
    C -->|"Do"| F
Property What it means
Defined once Its content and its fonts are stored in the file only once
Drawn many times Each use is a reference of a few bytes (/Fm1 Do), on the same page or on different pages
Transformable Whatever is in the CTM when it's drawn (translation, scale, rotation) applies to the whole form
/BBox Rectangle that bounds the form: anything outside it is clipped
/Matrix The form's own transformation (optional)

It's drawn with content.drawForm(form), which works like drawImage but without a size: the size is determined by the /BBox and the CTM. A form XObject can be created from scratch (new PDFormXObject(document) with setBBox, setResources and a PDFormContentStream to write into it), but our Shapes and TextMetrics utilities work with PDPageContentStream. That's why in InvoiceLab we'll take a more practical route: draw on a normal page and turn it into a form XObject with LayerUtility (section 4). This is also what Overlay and imposition do internally.

Overlay: laying one PDF over another

org.apache.pdfbox.multipdf.Overlay places the first page of one PDF (the overlay) on top of or underneath the pages of another (the input). Internally it turns the overlay page into a form XObject and adds it to each page of the input.

Method What it does
setInputPDF(PDDocument) / setInputFile(String) Document the overlay is added to
setDefaultOverlayPDF(...) / setDefaultOverlayFile(...) Overlay for every page that doesn't have a more specific one
setFirstPageOverlay..., setLastPageOverlay... Overlay for the first or the last page
setOddPageOverlay..., setEvenPageOverlay... For odd or even pages (double-sided printing)
setAllPagesOverlay... A multi-page PDF: its page n is laid over page n of the input
setOverlayPosition(Overlay.Position) BACKGROUND (default: underneath) or FOREGROUND (on top)
overlay(Map<Integer, String>) Runs the overlay. The map assigns files to specific pages (1-based); it must be an empty map, not null, if unused
close() Closes all the overlay documents, including the ones you passed in with set...PDF (it doesn't close the input)

When a page meets several conditions, the most specific one wins: first the map of specific pages, then first/last, then odd/even and finally the default overlay.

BACKGROUND and FOREGROUND work like PREPEND and APPEND from lesson 04-02:

  • BACKGROUND: the overlay is painted before the content: it ends up underneath and the page's opaque fills cover it.
  • FOREGROUND: the original content is wrapped in q … Q (like resetContext) and the overlay is painted afterwards: it ends up on top.

Letterhead: invoices on the corporate background

The GenerateLetterhead program simulates the PDF that marketing hands over: a 5 mm orange strip along the left edge, a large very light blue circle peeking out from the bottom-right corner, and the (fictional) company registration details 8 mm from the bottom edge. They're designed to sit outside the content box of the invoice (lesson 02-01) or underneath it.

/** 1) Print the invoice on the corporate letterhead. */
static void letterhead() throws IOException {
    try (Overlay overlay = new Overlay()) {                   // close() closes the letterhead it opens
        overlay.setDefaultOverlayFile("output/letterhead-nebula.pdf");
        overlay.setOverlayPosition(Overlay.Position.BACKGROUND);
        PdfEditor.edit(Path.of("output/F-2026-0001.pdf"), Path.of("output/F-2026-0001-letterhead.pdf"),
                PdfEditor.Mode.FULL, invoice -> {
                    overlay.setInputPDF(invoice);
                    overlay.overlay(new HashMap<>());         // no overlays for specific pages
                });
    } // the overlay (and the letterhead) are closed after the invoice has been saved
}

What matters is the lifetime order of the objects:

  1. The Overlay is created outside PdfEditor.edit, in a try-with-resources.
  2. Inside the lambda it receives the open invoice (setInputPDF) and overlay(...) runs, which opens the letterhead and modifies the invoice's pages in memory.
  3. PdfEditor.edit saves the invoice and closes it.
  4. Only then is the Overlay closed, and the letterhead along with it.

In PDFBox 3.0.x, Overlay copies the letterhead's content and clones its resources into the invoice, so in practice it would also work if you closed it before saving. Even so, we follow the module's general rule, which costs nothing and is essential with importPage (04-03) and with Splitter (04-04): source documents are closed after the target has been saved.

When you open F-2026-0001-letterhead.pdf you can see the orange strip on the left and the registration details at the foot; the decorative circle only peeks out where the invoice has no fills. With FOREGROUND, on the other hand, the circle would cover part of the table: for backgrounds, BACKGROUND; for stamps and visual annotations, FOREGROUND.

Why not include the letterhead in the module 3 generator? Because this way marketing can change the design by handing over a new PDF, without touching code, and the same letterhead works for invoices, delivery notes and batches. Besides, the letterhead PDF may come from a design tool, with elements that would be very laborious to reproduce with PDFBox.

LayerUtility: importing a page as a form XObject

org.apache.pdfbox.multipdf.LayerUtility works on a target document (new LayerUtility(target)) and offers three methods:

Method What it does
importPageAsForm(source, index) / importPageAsForm(source, page) Turns a page from another document into a PDFormXObject of the target: it copies its content, clones its resources and adjusts /BBox and /Matrix according to the page's CropBox and rotation
wrapInSaveRestore(page) Wraps a page's existing content in q … Q (the same thing resetContext does in 04-02)
appendFormAsLayer(page, form, transform, name) Draws the form on top of the page inside a new layer with that name and returns the group it created

Differences from importPage (04-03):

  • importPage adds a page; importPageAsForm returns a drawable object that you place wherever you like, at whatever scale you like, as many times as you like.
  • importPageAsForm copies the content and clones the resources into the target, so the form doesn't depend on the source. Even so, we'll keep the source open until saving, for consistency with the module's rule.

A stamp designed once and drawn on many pages

The accountants want a «RECEIVED» stamp on the 14 pages of the batch. We could call a Stamper method 14 times, but each page would get its own copy of the stamp's operators. With a form XObject, the stamp is stored once.

First we design it in an auxiliary document, on a page that is exactly the size of the stamp (72 × 9 mm), with our usual utilities:

/** Designs the stamp on a small page of an auxiliary (in-memory) document. */
static byte[] designStamp() throws IOException {
    try (PDDocument document = new PDDocument()) {
        PDPage page = new PDPage(new PDRectangle(Measures.mm(72), Measures.mm(9)));
        document.addPage(page);
        InvoiceLabFonts fonts = new InvoiceLabFonts(document);
        try (PDPageContentStream content = new PDPageContentStream(document, page)) {
            Shapes.drawBox(content, 1, 1, Measures.mm(72) - 2, Measures.mm(9) - 2, Measures.mm(2),
                    NebulaColors.BACKGROUND_BLUE, NebulaColors.BLUE, 1);
            content.setNonStrokingColor(NebulaColors.BLUE);
            TextMetrics.writeAligned(content, fonts.bold(), 8,
                    "RECEIVED · Example Accountants · 03/02/2026", Measures.mm(36), Measures.mm(3.4), Alignment.CENTER);
        }
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        document.save(output);                  // saving completes the font subset
        return output.toByteArray();
    }
}
  • The page is the same size as the stamp: when it's turned into a form, its /BBox will be [0 0 204 25.5] and nothing will be left over.
  • It's saved and reloaded (through the byte[]). The PDFBox documentation requires this for overlays and imports created in memory: the DejaVu font subset is generated when saving, and an unsaved document has a "half-finished" font. It's the same warning you saw with importPage in 04-03.
  • If the text doesn't fit within the width, it's clipped by the /BBox. In the first version of this example, at 62 mm, the stamp came out as «ECEIVED · … · 03/02/202». Measure the text (TextMetrics.width) when you design templates.

Then we import it and draw it on every page:

static void stampAsXObject() throws IOException {
    byte[] stamp = designStamp();
    try (PDDocument template = Loader.loadPDF(stamp)) {
        PdfEditor.edit(Path.of("output/batch-2026-01.pdf"), Path.of("output/batch-received-xobject.pdf"),
                PdfEditor.Mode.FULL, batch -> {
                    PDFormXObject form = new LayerUtility(batch).importPageAsForm(template, 0);
                    Stamper stamper = new Stamper(batch);
                    for (PDPage page : batch.getPages()) {
                        stamper.stamp(page, AppendMode.APPEND, (content, visible) -> {
                            // Bottom right, between the invoice footer and the edge of the paper
                            content.transform(Matrix.getTranslateInstance(
                                    visible.getWidth() - Measures.mm(90), Measures.mm(9)));
                            content.drawForm(form);
                        });
                    }
                });
    }
}
  • importPageAsForm is called only once, outside the loop. If you called it for each page, you'd create 14 identical forms and lose the advantage.
  • Stamper.stamp (04-02) still does its part: a stream with resetContext, "as seen" coordinates and save/restore. Inside, a translation positions the stamp's bottom-left corner and drawForm paints it.
  • The batch grows from 284,290 to 293,682 bytes: about 9 KB, almost all of it from the stamp's font subset, which is embedded once. Each page only adds a few bytes (q … cm /Fm1 Do Q). The advantage grows with the complexity of the stamp: a vector logo with hundreds of curves repeated over 500 pages makes a huge difference.

Optional content: groups, layers and marked content

Optional content (OC) lets you mark parts of the content so that the user or the viewer can decide whether they're shown. In viewers it appears as a layers panel. Its pieces:

Piece PDFBox class What it is
Optional content group (OCG) PDOptionalContentGroup A named "layer": new PDOptionalContentGroup("Original")
Optional content properties PDOptionalContentProperties The registry of all the document's groups (the catalog's /OCProperties) and their default configuration (/D): which ones are on when the document opens
Marked content beginMarkedContent(COSName.OC, group) … endMarkedContent() Whatever is drawn between the two calls belongs to the group
flowchart TB
    CAT["Catalog"] --> OCP["/OCProperties<br/>(PDOptionalContentProperties)"]
    OCP --> OCGS["/OCGs: [Original, Customer copy, ...]"]
    OCP --> D["/D (default configuration)<br/>/OFF [Customer copy]"]
    P["Page content stream"] --> MC["/OC /oc1 BDC<br/>... drawing ...<br/>EMC"]
    MC -.->|"/oc1 in /Resources /Properties"| OCGS
  • beginMarkedContent(COSName.OC, group) writes the BDC operator and registers the group in the page resources (/Properties); endMarkedContent() writes EMC. They must always come in pairs and be properly nested with saveGraphicsState/restoreGraphicsState and beginText/endText.
  • properties.setGroupEnabled(group, false) adds the group to the /OFF list of the default configuration: the document opens with that layer hidden.
  • The user can change the visibility from the viewer's layers panel (Acrobat, Foxit, Firefox and others). Some simple viewers ignore optional content and show everything.

We create the groups with a small method in the Layers class:

/** Returns the optional content group with that name, creating it if it doesn't exist. */
public static PDOptionalContentGroup group(PDDocument document, String name, boolean visible) {
    PDDocumentCatalog catalog = document.getDocumentCatalog();
    PDOptionalContentProperties properties = catalog.getOCProperties();
    if (properties == null) {
        properties = new PDOptionalContentProperties();
        catalog.setOCProperties(properties);
    }
    PDOptionalContentGroup group = properties.getGroup(name);
    if (group == null) {
        group = new PDOptionalContentGroup(name);
        properties.addGroup(group);
    }
    properties.setGroupEnabled(group, visible);
    return group;
}
  • If the document had no optional content, the /OCProperties dictionary is created in the catalog.
  • If a group with that name already exists, it's reused. That way, calling group(...) twice doesn't create two layers with the same name (which would confuse the user).

"Original" and "Customer copy" layers

A single invoice with two labels in the same spot, each on its own layer: «ORIGINAL» (visible when the document opens) and «CUSTOMER COPY» (hidden). Whoever prints the customer copy switches the layers in the viewer.

PDOptionalContentGroup original = Layers.group(document, "Original", true);
PDOptionalContentGroup copy = Layers.group(document, "Customer copy", false);

PDFont bold = new InvoiceLabFonts(document).bold();
Stamper stamper = new Stamper(document);
for (PDPage page : document.getPages()) {
    stamper.stamp(page, AppendMode.APPEND, (content, visible) -> {
        float x = visible.getWidth() - Measures.mm(18);
        float y = Measures.mm(13);
        label(content, original, bold, "ORIGINAL", x, y);
        label(content, copy, bold, "CUSTOMER COPY", x, y);
    });
}

private static void label(PDPageContentStream content, PDOptionalContentGroup group, PDFont font,
                          String text, float rightX, float y) throws IOException {
    content.beginMarkedContent(COSName.OC, group);
    content.setNonStrokingColor(NebulaColors.ORANGE);
    TextMetrics.writeAligned(content, font, 9, text, rightX, y, Alignment.RIGHT);
    content.endMarkedContent();
}
  • The groups are created once per document, outside the loop; every page refers to the same groups. That way, when you hide "Original" in the layers panel, it disappears from every page at once.
  • The labels sit 13 mm from the bottom edge, aligned with the 18 mm right margin: just below the «Page X of N» footer, in the free space between the footer and the edge of the paper.
  • TextMetrics.writeAligned opens and closes its own text object, so it's correctly nested inside the marked content.

LayerUtility.appendFormAsLayer does something similar in a single call (it creates the group, opens an APPEND stream and draws a form inside BDC … EMC), but it creates a new group each time and throws IllegalArgumentException if one with that name already exists. It's useful for adding a layer to a page; for a layer spanning the whole document, use a single group as in this section (you'll practise this in exercise 3).

A mark that only appears when printing

Each group can carry a /Usage dictionary describing its intended use: whether it should be seen on screen (/View), when printing (/Print) or when exporting (/Export). With it we can create a mark that is invisible on screen and visible on paper, such as "Printed copy: uncontrolled", typical of quality management systems. PDFBox has no high-level methods for /Usage, so we write it at the COS level:

/**
 * Makes the group hidden on screen and shown when printing
 * (the group's /Usage dictionary and the default configuration's /AS).
 */
public static void printOnly(PDDocument document, PDOptionalContentGroup group) {
    COSDictionary view = new COSDictionary();
    view.setItem(COSName.VIEW_STATE, COSName.OFF);
    COSDictionary print = new COSDictionary();
    print.setItem(COSName.PRINT_STATE, COSName.ON);
    COSDictionary usage = new COSDictionary();
    usage.setItem(COSName.VIEW, view);
    usage.setItem(COSName.PRINT, print);
    group.getCOSObject().setItem(COSName.USAGE, usage);

    // /AS: asks the viewer to apply /Usage automatically on the View and Print events
    COSDictionary configuration = document.getDocumentCatalog().getOCProperties().getCOSObject()
            .getCOSDictionary(COSName.D);
    COSArray automatic = new COSArray();
    for (COSName event : new COSName[] { COSName.VIEW, COSName.PRINT }) {
        COSDictionary rule = new COSDictionary();
        rule.setItem(COSName.getPDFName("Event"), event);
        COSArray groups = new COSArray();
        groups.add(group);
        rule.setItem(COSName.OCGS, groups);
        COSArray categories = new COSArray();
        categories.add(event);
        rule.setItem(COSName.getPDFName("Category"), categories);
        automatic.add(rule);
    }
    configuration.setItem(COSName.AS, automatic);
}

The result in the file is:

OCG:  << /Type /OCG /Name (Print mark)
         /Usage << /View << /ViewState /OFF >> /Print << /PrintState /ON >> >> >>
/D:   << ... /AS [ << /Event /View  /OCGs [OCG] /Category [/View]  >>
               << /Event /Print /OCGs [OCG] /Category [/Print] >> ] >>
  • /Usage describes how the group should behave; /AS (auto state) asks the viewer to apply it automatically when the document is displayed (/View) or printed (/Print). Both are needed.
  • The /Event and /Category names have no constant in COSName, so they're created with COSName.getPDFName.
  • Usage: Layers.printOnly(document, Layers.group(document, "Print mark", true)) and draw the mark between beginMarkedContent(COSName.OC, printed) and endMarkedContent(), just like the labels.
  • PDFBox's own renderer respects /Usage: when you render the first page of F-2026-0001-layers.pdf for the screen (RenderDestination.VIEW) only «ORIGINAL» appears; for printing (RenderDestination.PRINT) «Printed copy: uncontrolled» appears as well. We'll see this in lesson 06-04. Acrobat respects it too; some lightweight viewers don't.
  • It's a convenience feature, not a security one: anyone can switch the layer on on screen or remove it.

Imposition: two pages on one sheet

Imposing means placing several pages of a document on a larger sheet, as print shops do. The most common office case is 2-up: two shrunken A4 pages, side by side, on a landscape A4 sheet, to save paper when printing the batch as a draft.

/**
 * 2-up imposition: each pair of source pages is placed, shrunk, on a landscape sheet
 * of the same size. The returned document is new: the caller must save and close it.
 */
public static PDDocument twoUp(PDDocument source) throws IOException {
    PDDocument target = new PDDocument();
    try {
        LayerUtility layers = new LayerUtility(target);
        PDRectangle first = source.getPage(0).getMediaBox();
        PDRectangle sheet = new PDRectangle(first.getHeight(), first.getWidth());   // landscape
        float half = sheet.getWidth() / 2;
        for (int i = 0; i < source.getNumberOfPages(); i += 2) {
            PDPage page = new PDPage(sheet);
            target.addPage(page);
            try (PDPageContentStream content = new PDPageContentStream(target, page)) {
                for (int side = 0; side < 2 && i + side < source.getNumberOfPages(); side++) {
                    PDFormXObject form = layers.importPageAsForm(source, i + side);
                    PDRectangle box = form.getBBox();
                    float factor = Math.min(half / box.getWidth(), sheet.getHeight() / box.getHeight());
                    float x = side * half + (half - box.getWidth() * factor) / 2;
                    float y = (sheet.getHeight() - box.getHeight() * factor) / 2;
                    content.saveGraphicsState();
                    content.transform(new Matrix(factor, 0, 0, factor, x, y));
                    content.drawForm(form);
                    content.restoreGraphicsState();
                }
            }
        }
        return target;
    } catch (IOException | RuntimeException e) {
        target.close();
        throw e;
    }
}

Step by step:

  • The sheet is the first page turned sideways: width and height are swapped (new PDRectangle(height, width)), as you learned in 02-01 for creating landscape documents without /Rotate.
  • Each source page is turned into a form with importPageAsForm. Because LayerUtility takes the page's CropBox and rotation into account, the form's /BBox corresponds to what is visible.
  • The scale factor is the largest one that lets the page fit in half a sheet: from portrait A4 to half a landscape A4 it comes out at 0.707 (the classic "reduce to 71%" of photocopiers).
  • x and y centre each page in its half: side * half picks the left or right half and the rest distributes the leftover space.
  • The condition i + side < source.getNumberOfPages() avoids asking for a page that doesn't exist when the total is odd: the last sheet has only the left half.
  • Resource management: the method creates a PDDocument that it returns open (the caller saves and closes it). If something fails halfway, the catch closes it before rethrowing the exception, so no orphan document is left behind. This is the pattern for any method that "manufactures" a resource that has to be closed.

Usage:

try (PDDocument batch = Loader.loadPDF(new File("output/batch-2026-01.pdf"));
     PDDocument twoUp = Layers.twoUp(batch)) {
    try (OutputStream output = Files.newOutputStream(Path.of("output/batch-2up.pdf"))) {
        twoUp.save(output);
    }
    System.out.printf("2-up: %d pages → %d sheets%n", batch.getNumberOfPages(), twoUp.getNumberOfPages());
}
2-up: 14 pages → 7 sheets

The order of the resources in the try guarantees that twoUp (declared later) is closed before batch, and that both are closed after saving. Thanks to the batch being prepared for double-sided printing (04-04), each sheet contains either a one-page invoice with its blank page beside it, or the two pages of the same invoice.

The Layers class

The utility class com.invoicelab.editing.Layers brings together what we've built:

Method Lesson Use
group(document, name, visible) This one Create or retrieve a layer
printOnly(document, group) This one Layer invisible on screen and visible on paper
drawInLayer(content, group, form, placement) This one Draw a form XObject inside a layer: beginMarkedContent, save, transform, drawForm, restore, endMarkedContent
twoUp(source) This one 2-up imposition

With PdfEditor, Stamper, Pages, InvoiceBatches, Splitting and Layers, the com.invoicelab.editing package now covers almost all the usual modifications to existing documents.

Common Mistakes and Tips

  • Not closing the Overlay. The files it opens on its own (set...File, the overlay map) stay open until close(), which also closes the documents you passed in with set...PDF. Create it in a try-with-resources outside PdfEditor.edit, so that it's closed after saving.
  • Passing null to overlay(...). If you don't use per-page overlays, pass an empty map (new HashMap<>()).
  • Importing templates created in memory without saving them. Their subset fonts aren't finished. Save to a byte[] and reload, as in designStamp.
  • Calling importPageAsForm inside the loop. You'd create one form per page and lose the benefit of reusing it.
  • Forgetting the /BBox. Whatever sticks out of the form is clipped without warning.
  • Unbalanced beginMarkedContent and endMarkedContent. Marked content must be opened and closed in the same stream and properly nested; otherwise some viewers show or hide content they shouldn't.
  • Using appendFormAsLayer in a loop with the same name. It throws IllegalArgumentException: create the group once with Layers.group and use Layers.drawInLayer.
  • Relying on optional content to hide information. Hidden layers are still in the file and can be switched on or extracted.
  • Tip: transparency, blend modes and optional content are restricted in PDF/A. If invoices have to be archived as PDF/A (module 8), check what the chosen conformance level allows.

Exercises

Exercise 1. Marketing has decided that the letterhead should only appear on the first page of each invoice. Modify the letterhead example to use the overlay(...) map instead of setDefaultOverlayFile.

Exercise 2. Generalise twoUp into nUp(PDDocument source, int columns, int rows, PDRectangle sheet), which distributes the pages in a grid of columns × rows cells on sheets of the given size, filling row by row from top to bottom. Try it with the batch in 2 × 2 on portrait A4.

Exercise 3. Add the «DRAFT» watermark from lesson 04-02 to F-2026-0001, but on a layer called "DRAFT" that the user can hide, the same one on every page. Hint: generate the mark in an auxiliary document with Stamper.watermark, import it with importPageAsForm and draw it with Layers.drawInLayer.

Solutions

Solution 1.

try (Overlay overlay = new Overlay()) {
    overlay.setOverlayPosition(Overlay.Position.BACKGROUND);
    PdfEditor.edit(Path.of("output/F-2026-0001.pdf"), Path.of("output/F-2026-0001-letterhead-first.pdf"),
            PdfEditor.Mode.FULL, invoice -> {
                overlay.setInputPDF(invoice);
                overlay.overlay(Map.of(1, "output/letterhead-nebula.pdf"));   // page 1 only
            });
}

The map keys are 1-based page numbers. The files in the map are opened by the Overlay itself (and closed in close()), so the outer try-with-resources is still necessary. The invoice's second page ends up without the strip or the registration details. An equivalent alternative is setFirstPageOverlayFile("output/letterhead-nebula.pdf").

Solution 2.

public static PDDocument nUp(PDDocument source, int columns, int rows, PDRectangle sheet) throws IOException {
    PDDocument target = new PDDocument();
    try {
        LayerUtility layers = new LayerUtility(target);
        float cellWidth = sheet.getWidth() / columns;
        float cellHeight = sheet.getHeight() / rows;
        int perSheet = columns * rows;
        for (int i = 0; i < source.getNumberOfPages(); i += perSheet) {
            PDPage page = new PDPage(sheet);
            target.addPage(page);
            try (PDPageContentStream content = new PDPageContentStream(target, page)) {
                for (int k = 0; k < perSheet && i + k < source.getNumberOfPages(); k++) {
                    PDFormXObject form = layers.importPageAsForm(source, i + k);
                    PDRectangle box = form.getBBox();
                    float factor = Math.min(cellWidth / box.getWidth(), cellHeight / box.getHeight());
                    int column = k % columns;
                    int row = k / columns;                        // row 0 = the top one
                    float x = column * cellWidth + (cellWidth - box.getWidth() * factor) / 2;
                    float y = sheet.getHeight() - (row + 1) * cellHeight
                            + (cellHeight - box.getHeight() * factor) / 2;
                    content.saveGraphicsState();
                    content.transform(new Matrix(factor, 0, 0, factor, x, y));
                    content.drawForm(form);
                    content.restoreGraphicsState();
                }
            }
        }
        return target;
    } catch (IOException | RuntimeException e) {
        target.close();
        throw e;
    }
}

k % columns and k / columns turn position k within the sheet into a column and a row. Since the PDF coordinate origin is at the bottom, row 0 (the top one) has its lower edge at sheet.getHeight() - cellHeight. With the 14-page batch in 2 × 2 you get 4 sheets, with the pages shrunk to 50%. twoUp(source) is equivalent to nUp(source, 2, 1, landscapeSheet).

Solution 3.

// 1) Watermark on a blank A4 page of an auxiliary document
byte[] mark;
try (PDDocument auxiliary = new PDDocument()) {
    auxiliary.addPage(new PDPage(PDRectangle.A4));
    new Stamper(auxiliary).watermark("DRAFT", false);
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    auxiliary.save(output);                                 // completes the font subset
    mark = output.toByteArray();
}
// 2) Import it once and draw it on a single layer
try (PDDocument template = Loader.loadPDF(mark)) {
    PdfEditor.edit(Path.of("output/F-2026-0001.pdf"), Path.of("output/F-2026-0001-draft-layer.pdf"),
            PdfEditor.Mode.FULL, document -> {
                PDFormXObject form = new LayerUtility(document).importPageAsForm(template, 0);
                PDOptionalContentGroup draft = Layers.group(document, "DRAFT", true);
                Stamper stamper = new Stamper(document);
                for (PDPage page : document.getPages()) {
                    stamper.stamp(page, AppendMode.APPEND,
                            (content, visible) -> Layers.drawInLayer(content, draft, form, new Matrix()));
                }
            });
}

The template is a full A4 page with the translucent mark, so it's drawn without any offset (new Matrix() is the identity) on A4 pages. The viewer's layers panel shows a single "DRAFT" layer that hides the mark on both pages. If you had used appendFormAsLayer in the loop, you'd need a different name per page ("DRAFT (page 1)", "DRAFT (page 2)"…) and the user would have to hide them one by one.

Conclusion

You now know how to overlay documents and work with reusable content. Form XObjects let you define something once and draw it many times; Overlay uses them to put one PDF on top of or underneath another (marketing's letterhead, per page or for the whole document), and LayerUtility.importPageAsForm lets you turn any page into a form in order to create reusable stamps or impose several pages on one sheet. With optional content groups you've created layers that the user can switch on ("Original" and "Customer copy") and a mark that only appears when printing, and you've seen that neither layers nor the CropBox really hide information.

There's one aspect of existing documents that isn't visible on the page but matters a great deal: metadata. In the next lesson, which closes the module, we'll read and write the document information dictionary and the XMP metadata of the invoices, keep them in sync, configure the language and the viewer preferences, and learn how to clean up metadata before publishing a document.

PDF Generation and Editing with Apache PDFBox

Module 1: PDF and PDFBox Fundamentals

Module 2: Generating Content

Module 3: Business Documents

Module 4: Editing Existing PDFs

Module 5: AcroForm Forms

Module 6: Extraction and Analysis

Module 7: Security and Digital Signatures

Module 8: PDFBox in Production

© Copyright 2026. All rights reserved