In the previous lesson we marked invoice F-2026-0001 as paid with an invisible key in the catalog. Now we want it to show: a «PAID» stamp with the payment date on the invoice that has already been issued, a «DRAFT» watermark on every page of a document and, for papers that come from outside, a receipt registry stamp and sequential page numbering. All of this boils down to the same thing: adding a new content stream to a page that already has content. It sounds simple, and with your own documents it is; with third-party documents real pitfalls appear (transformations left active, offset boxes, rotated pages) that you'll learn to neutralise. The result will be the Stamper class, in the com.invoicelab.editing package.
Contents
- How content is added to an existing page
AppendMode: on top, underneath or instead ofresetContext: why it is crucial with other people's documents- Offset boxes and the page's
/Rotate - Fonts in existing documents
- The
Stamperclass - «PAID» stamp with the payment date
- «DRAFT» watermark: underneath or on top
- Third-party documents: receipt registry and Bates numbering
- The example program
How content is added to an existing page
Remember from lesson 01-03 that a page has a /Contents entry that can be a stream or an array of streams. When there are several, the viewer executes them in order, as if they were a single one. That's the key: to stamp something you don't need to understand or rewrite the original content; you just add one more stream to the array.
flowchart LR
subgraph Before
C1["/Contents 12 0 R<br/>(invoice content)"]
end
subgraph After["After APPEND with resetContext"]
direction LR
Q1["new stream:<br/>q"] --> C2["12 0 R<br/>(original content)"] --> N["new stream:<br/>Q + stamp"]
end
Before --> After
You already used this technique in lesson 03-02 for the «Page X of N» footer. There the page was ours; now the document comes from disk and may have been produced by any program.
The constructor we'll always use is the five-parameter one:
new PDPageContentStream(document, page, AppendMode.APPEND, true, true)
// mode compress resetContextAppendMode: on top, underneath or instead of
| Mode | What it does with /Contents |
Visual result | Typical use |
|---|---|---|---|
APPEND |
Adds the new stream at the end | The new content is painted on top | Stamps, numbering, translucent watermarks |
PREPEND |
Adds the new stream at the beginning | The new content ends up underneath | Backgrounds, "paper" watermarks |
OVERWRITE |
Replaces all the content | What was there disappears | Almost never with existing documents |
OVERWRITEis the mode of the two-parameter constructornew PDPageContentStream(document, page). If you use it on a loaded invoice, the page ends up blank except for what you draw. It is the most destructive mistake in this module.- With
PREPEND, your stream runs before the original one. The original content expects to find the initial graphics state (no transformations, black colour…), so your drawing must leave the state as it found it: everything betweensaveGraphicsState()andrestoreGraphicsState(). compress = truecompresses the new stream with Flate. Set it tofalsewhen you want to read your stamp in PDFDebugger (lesson 01-05).
resetContext: why it is crucial with other people's documents
A well-written content stream leaves the graphics state as it found it. But nothing forces it to: many generators apply a transformation at the start (for example, a scale or a change of origin) and never undo it, because their document didn't need to. If you append your stream after it, you inherit that transformation.
To check this, the SupplierDocument example simulates the PDF of a fictional supplier, "Fictional Supplies Inc.", which does exactly that: it scales everything by half and doesn't restore the state. Then we add two identical rectangles at positions (400, 600)/(400, 700), one without and one with resetContext:
PDPage page = document.getPage(0);
// Without resetContext: inherits the 0.5 scale left behind by the supplier
try (PDPageContentStream cs = new PDPageContentStream(document, page, AppendMode.APPEND, true, false)) {
cs.addRect(400, 600, 150, 60);
cs.setNonStrokingColor(Color.RED);
cs.fill();
}
// With resetContext: clean graphics state
try (PDPageContentStream cs = new PDPageContentStream(document, page, AppendMode.APPEND, true, true)) {
cs.addRect(400, 700, 150, 60);
cs.setNonStrokingColor(Color.GREEN);
cs.fill();
}Result: the green rectangle appears at the top right at its real size; the red one appears at half size and at (200, 300), in the middle of the page. With a real stamp, «PAID» would come out tiny and out of place only on certain suppliers' invoices, a bug that is hard to diagnose.
What exactly does resetContext = true do? You saw it in the diagram in the first section:
- It creates a minimal stream with the
qoperator (save state) and puts it first in the array. - It writes
Q(restore state) at the beginning of your stream.
That way all the original content is enclosed in q … Q and your drawing starts with the initial graphics state, whatever mess the original left behind. It only has an effect with APPEND; with PREPEND your stream comes first, so it inherits nothing.
InvoiceLab rule: always
resetContext = truewhen adding content to an existing page. It costs nothing and prevents the most baffling bugs.
Offset boxes and the page's /Rotate
resetContext cleans up the graphics state, but two properties of the page still affect where your drawing appears. You met them in lesson 02-01:
- CropBox with an origin other than
(0, 0). What is visible starts at the CropBox's(getLowerLeftX(), getLowerLeftY()). If you place the stamp "8 mm from the left edge" withx = mm(8), in a document whose visible area starts atx = 20the stamp will end up almost cut off. /Rotate. The page is displayed rotated 90, 180 or 270 degrees clockwise, but the content's coordinate system doesn't rotate. A stamp drawn without compensating appears sideways or upside down.
The solution is a single initial transformation that maps an "as seen" coordinate system (origin at the bottom left of the visible area, X axis pointing to the right of what the user sees) onto the real system of the page. With a CropBox of origin (x, y), width W and height H:
/Rotate |
Visible size | Matrix [a b c d e f] |
|---|---|---|
| 0 | W × H |
[1 0 0 1 x y] (translation only) |
| 90 | H × W |
[0 1 -1 0 x+W y] |
| 180 | W × H |
[-1 0 0 -1 x+W y+H] |
| 270 | H × W |
[0 -1 1 0 x y+H] |
The 90-degree row is the same one you used in 02-01 to write horizontally on a page with /Rotate 90, now with the CropBox offset. To check a row, take the visible bottom-left corner (0, 0): with /Rotate 90 it must correspond to the bottom-right corner of the unrotated CropBox, (x+W, y), because when the page is rotated 90 degrees clockwise that corner ends up at the bottom left. And that's exactly what the matrix gives: e = x+W, f = y.
Fonts in existing documents
To write «PAID» you need a font in the open document. You have two options, and only one is good:
| Option | Problem |
|---|---|
| Reuse a font that is already in the page resources | It's almost always a subset: it only contains the glyphs the original used. If the invoice had no capital "D", «PAID» would come out with gaps. Besides, you don't know which encoding it uses. |
| Load a new font into the document | None: this is what we do. |
InvoiceLabFonts works on any PDDocument, including a loaded one: new InvoiceLabFonts(document) embeds DejaVu Sans with subsetting, and PDFBox builds the subset when saving (with both save and saveIncremental). The page resources receive a new name (/F3, /F4…) that doesn't clash with the existing ones, because PDResources.add always picks a free key.
Remember the rules from lesson 02-03: one InvoiceLabFonts instance per document, and sanitize for any text coming from outside.
The Stamper class
We bring everything above together in one class. Its central method, stamp, opens the stream with the safe parameters, applies the "as seen" matrix and runs the drawing we pass to it. The specific stamps are built on top of it.
package com.invoicelab.editing;
import com.invoicelab.pdf.Alignment;
import com.invoicelab.pdf.NebulaColors;
import com.invoicelab.pdf.Formats;
import com.invoicelab.pdf.InvoiceLabFonts;
import com.invoicelab.pdf.Shapes;
import com.invoicelab.pdf.Measures;
import com.invoicelab.pdf.TextMetrics;
import java.awt.Color;
import java.io.IOException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.PDPageContentStream.AppendMode;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.graphics.state.PDExtendedGraphicsState;
import org.apache.pdfbox.util.Matrix;
/** Stamps seals, watermarks and numbering onto the pages of an existing PDF. */
public final class Stamper {
/** Green used for payment stamps. */
public static final Color PAID_GREEN = new Color(0x1B, 0x7F, 0x3B);
private static final DateTimeFormatter DATE_TIME = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm");
/** What gets drawn: receives the content stream already positioned and the page size as seen. */
@FunctionalInterface
public interface Drawing {
void draw(PDPageContentStream content, PDRectangle visible) throws IOException;
}
private final PDDocument document;
private final InvoiceLabFonts fonts;
private PDExtendedGraphicsState translucent; // created once per document
public Stamper(PDDocument document) {
this.document = document;
this.fonts = new InvoiceLabFonts(document);
}
/** Page rotation normalised to 0, 90, 180 or 270. */
public static int rotation(PDPage page) {
return ((page.getRotation() % 360) + 360) % 360;
}
/** Width and height of the visible area (CropBox) as the viewer shows it, with origin (0, 0). */
public static PDRectangle visible(PDPage page) {
PDRectangle box = page.getCropBox();
boolean rotated = rotation(page) == 90 || rotation(page) == 270;
return rotated ? new PDRectangle(box.getHeight(), box.getWidth())
: new PDRectangle(box.getWidth(), box.getHeight());
}
/**
* Matrix that maps "visible" coordinates (origin at the bottom left of what is seen,
* unrotated) onto the real coordinate system of the page.
*/
public static Matrix visibleMatrix(PDPage page) {
PDRectangle box = page.getCropBox();
float x = box.getLowerLeftX();
float y = box.getLowerLeftY();
float width = box.getWidth();
float height = box.getHeight();
switch (rotation(page)) {
case 90: return new Matrix(0, 1, -1, 0, x + width, y);
case 180: return new Matrix(-1, 0, 0, -1, x + width, y + height);
case 270: return new Matrix(0, -1, 1, 0, x, y + height);
default: return Matrix.getTranslateInstance(x, y);
}
}
/**
* Opens a new stream on the page (APPEND = on top, PREPEND = underneath), applies the
* "visible" system and runs the drawing inside a save/restore.
*/
public void stamp(PDPage page, AppendMode mode, Drawing drawing) throws IOException {
try (PDPageContentStream content = new PDPageContentStream(document, page, mode, true, true)) {
content.saveGraphicsState();
content.transform(visibleMatrix(page));
drawing.draw(content, visible(page));
content.restoreGraphicsState();
}
}
// ... specific stamps: shown in the following sections ...
private PDExtendedGraphicsState translucent() {
if (translucent == null) {
translucent = Shapes.opacity(0.8f);
}
return translucent;
}
}Key points:
rotationnormalises the value:/Rotatecan be-90or450in real documents, and those are equivalent to270and90. The double modulo turns any integer into 0, 90, 180 or 270.visiblereturns aPDRectanglewith origin(0, 0)and the dimensions of what the user sees: if the page is rotated 90 or 270 degrees, width and height are swapped.visibleMatriximplements the table from the previous section.Matrix.getTranslateInstance(x, y)is the pure translation matrix.stampreceives aDrawing(another functional interface, likePdfEditor.Change). It opens the stream withcompressandresetContextset totrue, saves the state, applies the matrix and calls the drawing. The finalrestoreGraphicsState()is essential withPREPEND: it leaves a clean state for the original content that follows.translucent()creates the opacity state withShapes.opacity(lesson 02-05) the first time it's needed and then reuses it: that way the document only receives oneExtGStateeven if we stamp a hundred pages.- Inside a
Drawingyou think as in module 2:(0, 0)is the visible bottom-left corner andvisible.getWidth()/getHeight()are its dimensions. No CropBox, no rotations.
«PAID» stamp with the payment date
The stamp imitates a rubber stamp: a double rounded border, a large «PAID» text and the payment date underneath, rotated 12 degrees and slightly translucent so that the text below can still be made out.
/** Rotated «PAID» stamp with the payment date, in the top right area of the page. */
public void paidStamp(PDPage page, LocalDate paymentDate) throws IOException {
PDFont bold = fonts.bold();
PDFont regular = fonts.regular();
String date = "Paid on " + Formats.date(paymentDate);
float width = Measures.mm(58);
float height = Measures.mm(22);
stamp(page, AppendMode.APPEND, (content, visible) -> {
// Centre of the stamp: 45 mm from the right and 75 mm from the top
float cx = visible.getWidth() - Measures.mm(45);
float cy = visible.getHeight() - Measures.mm(75);
content.setGraphicsStateParameters(translucent());
content.transform(Matrix.getRotateInstance(Math.toRadians(12), cx, cy));
// From here on (0, 0) is the centre of the stamp
Shapes.drawBox(content, -width / 2, -height / 2, width, height, Measures.mm(3),
null, PAID_GREEN, 2.2f);
Shapes.drawBox(content, -width / 2 + 3, -height / 2 + 3, width - 6, height - 6, Measures.mm(2),
null, PAID_GREEN, 0.6f);
content.setNonStrokingColor(PAID_GREEN);
TextMetrics.writeAligned(content, bold, 24, "PAID", 0, -Measures.mm(1.5f), Alignment.CENTER);
TextMetrics.writeAligned(content, regular, 8.5f, date, 0, -height / 2 + Measures.mm(3.2f),
Alignment.CENTER);
});
}- The fonts are requested outside the lambda: that way a failure loading them happens before the stream is opened.
Matrix.getRotateInstance(angle, cx, cy)rotates and translates at the same time: after applying it, the origin is at the centre of the stamp. That's why the boxes start at-width / 2, -height / 2: they are centred around the origin, and the rotation happens around the centre of the stamp.Shapes.drawBox(..., fill = null, border = PAID_GREEN, ...)draws only the outline; the second box, 3 points further in and with a thin line, gives the rubber-stamp effect.writeAligned(..., 0, y, CENTER)centres each text onx = 0, the axis of the stamp.- The 80 % opacity is applied once and affects everything that follows inside
stamp'ssave/restore.
On the 30-line invoice, the stamp sits over the customer box, on the right, without covering any amount.
«DRAFT» watermark: underneath or on top
In lesson 02-05 you drew a watermark while creating a document. Now we add it to every page of an existing PDF, and you have to choose between putting it underneath or on top of the content:
/**
* Diagonal watermark on ALL pages.
* underneath = true → PREPEND (below the content, opaque light grey);
* underneath = false → APPEND (on top, translucent).
*/
public void watermark(String text, boolean underneath) throws IOException {
for (PDPage page : document.getPages()) {
watermark(page, text, underneath);
}
}
/** Diagonal watermark on a single page. */
public void watermark(PDPage page, String text, boolean underneath) throws IOException {
PDFont bold = fonts.bold();
String clean = InvoiceLabFonts.sanitize(bold, text);
AppendMode mode = underneath ? AppendMode.PREPEND : AppendMode.APPEND;
stamp(page, mode, (content, visible) -> {
float w = visible.getWidth();
float h = visible.getHeight();
double angle = Math.atan2(h, w); // page diagonal
float diagonal = (float) Math.hypot(w, h);
// Size so that the text takes up 70 % of the diagonal
float size = 0.70f * diagonal / TextMetrics.width(bold, 1, clean);
if (underneath) {
content.setNonStrokingColor(new Color(0xE6, 0xE6, 0xE6));
} else {
content.setGraphicsStateParameters(translucent());
content.setNonStrokingColor(NebulaColors.TEXT_GREY);
}
content.transform(Matrix.getRotateInstance(angle, w / 2, h / 2));
float baseY = -TextMetrics.capHeight(bold, size) / 2;
TextMetrics.writeAligned(content, bold, size, clean, 0, baseY, Alignment.CENTER);
});
}- Two versions:
watermark(text, underneath)walks through every page and delegates towatermark(page, text, underneath), which marks a single one. Having the per-page version lets you, for example, mark only the copies within a document (we'll do this in 04-03). Math.atan2(h, w)is the angle of the page diagonal (about 55 degrees on portrait A4). Using it instead of a fixed 45 makes the mark run from corner to corner on landscape pages too.- The size is calculated:
width(bold, 1, text)measures the text at size 1; dividing 70 % of the diagonal by that measurement gives the size that makes the text take up exactly that space, whether it's «DRAFT» or «COPY». baseY = -capHeight / 2vertically centres the text (all capitals) on the diagonal.- Because the loop walks through
document.getPages(), each page receives its own matrix: a document mixing portrait and landscape pages works without changes.
Applying both variants to F-2026-0001 shows the difference:
PREPEND (underneath) |
APPEND (on top, translucent) |
|
|---|---|---|
| Document readability | Perfect: the content is painted on top | Good if the opacity is low |
| Watermark visibility | Disappears under opaque fills: the customer box, the zebra rows and the table header cover it | Always visible, over everything |
| Can be removed by cropping | Yes, by covering it with white rectangles | Harder |
| Recommended colour | Very light opaque grey | Medium grey with 10-30 % opacity |
The practical lesson: PREPEND only works well on documents without opaque backgrounds (letters, text-only contracts). Our invoices have coloured boxes, so for them APPEND with transparency is the better choice. In the exercises you'll see a third option using blend modes.
Third-party documents: receipt registry and Bates numbering
Nebula Distribution receives delivery notes and invoices from suppliers every day. Two common operations:
- Receipt registry stamp: a box with the registry number and the date and time of receipt, like the rubber stamp of a registry office.
- Bates numbering: a unique, sequential identifier on every page (
NEB-000001,NEB-000002…), which carries on from one document to the next. It's common in law firms and audits for citing any page unambiguously.
/**
* Bates numbering: a sequential identifier (PREFIX-000001...) at the bottom right of every page.
* Returns the next free number, so the series can continue in the next document.
*/
public int batesNumber(String prefix, int first) throws IOException {
PDFont font = fonts.bold();
int number = first;
for (PDPage page : document.getPages()) {
String code = String.format("%s-%06d", prefix, number++);
stamp(page, AppendMode.APPEND, (content, visible) -> {
float size = 8;
float textWidth = TextMetrics.width(font, size, code);
float margin = Measures.mm(6);
float x = visible.getWidth() - margin - textWidth;
float y = margin; // text baseline
float height = TextMetrics.capHeight(font, size);
// White background with a border so it can be read over any content
Shapes.drawBox(content, x - 3, y - 3, textWidth + 6, height + 6, 0, Color.WHITE,
Color.BLACK, 0.5f);
content.setNonStrokingColor(Color.BLACK);
TextMetrics.writeAligned(content, font, size, code, x, y, Alignment.LEFT);
});
}
return number;
}%06dpads with zeros up to six digits:NEB-000001. That way the codes also sort correctly as text.codeis calculated outside the lambda: variables used by a lambda must be effectively final, andnumberchanges on every iteration.- The white background guarantees legibility even if the corner of someone else's document has content in it. That's the reason for using
APPEND. - The method returns the next free number so the series can continue in the next document of the batch.
The registry stamp follows the same pattern (a white box with a corporate blue border and four centred lines) in the visible top-left corner of the first page:
/** Receipt registry stamp in the top-left corner of the first page. */
public void receiptStamp(String registryNumber, LocalDateTime moment) throws IOException {
PDFont bold = fonts.bold();
PDFont regular = fonts.regular();
String[] lines = {
"Nebula Distribution Ltd.",
"No. " + registryNumber,
DATE_TIME.format(moment) };
stamp(document.getPage(0), AppendMode.APPEND, (content, visible) -> {
float width = Measures.mm(52);
float height = Measures.mm(19);
float x = Measures.mm(8);
float y = visible.getHeight() - Measures.mm(8) - height;
Shapes.drawBox(content, x, y, width, height, Measures.mm(1.5f), Color.WHITE, NebulaColors.BLUE, 1.2f);
content.setNonStrokingColor(NebulaColors.BLUE);
float cx = x + width / 2;
float line = y + height - Measures.mm(5);
TextMetrics.writeAligned(content, bold, 8, "RECEIPT REGISTRY", cx, line, Alignment.CENTER);
for (String text : lines) {
line -= Measures.mm(3.8f);
TextMetrics.writeAligned(content, regular, 7.5f, text, cx, line, Alignment.CENTER);
}
});
}Notice that x = Measures.mm(8) works even though the supplier's CropBox starts at (20, 30): stamp has already moved the origin to the visible corner.
The example program
First we generate the supplier's "difficult" PDF with SupplierDocument (in com.invoicelab.examples): three A4 pages with the CropBox at (20, 30, 555 × 782), the second one with /Rotate 90 and a content stream that applies transform(new Matrix(0.5f, 0, 0, 0.5f, 0, 0)) without restoring it. Then:
package com.invoicelab.examples;
import com.invoicelab.editing.PdfEditor;
import com.invoicelab.editing.Stamper;
import java.io.IOException;
import java.nio.file.Path;
import java.time.LocalDate;
import java.time.LocalDateTime;
public class StampDocuments {
public static void main(String[] args) throws IOException {
// 1) PAID stamp on the first page of the issued invoice (incremental: preserves the original)
PdfEditor.edit(Path.of("output/F-2026-0001.pdf"), Path.of("output/F-2026-0001-paid.pdf"),
PdfEditor.Mode.INCREMENTAL,
document -> new Stamper(document)
.paidStamp(document.getPage(0), LocalDate.of(2026, 2, 10)));
// 2) DRAFT watermark, underneath and on top, on every page
PdfEditor.edit(Path.of("output/F-2026-0001.pdf"), Path.of("output/F-2026-0001-draft-under.pdf"),
PdfEditor.Mode.FULL, document -> new Stamper(document).watermark("DRAFT", true));
PdfEditor.edit(Path.of("output/F-2026-0001.pdf"), Path.of("output/F-2026-0001-draft-over.pdf"),
PdfEditor.Mode.FULL, document -> new Stamper(document).watermark("DRAFT", false));
// 3) Supplier document: receipt registry + Bates numbering
PdfEditor.edit(Path.of("output/supplier-AP-7731.pdf"), Path.of("output/supplier-AP-7731-registered.pdf"),
PdfEditor.Mode.FULL, document -> {
Stamper stamper = new Stamper(document);
stamper.receiptStamp("2026/000123", LocalDateTime.of(2026, 2, 12, 9, 41));
int next = stamper.batesNumber("NEB", 1);
System.out.println("Next free Bates number: " + next);
});
System.out.println("Done.");
}
}- The «PAID» stamp is saved in incremental mode: the invoice as it was issued is still inside the file, and the stamp is a later revision (exactly what an auditor would want).
- The watermarks are saved in full mode: they are working documents and we don't need the history.
- In
supplier-AP-7731-registered.pdf, the stamp and the Bates codes appear at their real size despite the scale left behind by the supplier (thanks toresetContext), inside the visible area (thanks to the CropBox) and horizontally even on the landscape page (thanks to/Rotate).
Common Mistakes and Tips
- Using the two-parameter constructor.
new PDPageContentStream(document, page)usesOVERWRITE: it wipes the page. With existing documents, always use the five-parameter one (orStamper.stamp). resetContext = falsewith third-party documents. It will work with your own PDFs and fail with some suppliers' PDFs. Don't take the risk.- Forgetting
restoreGraphicsStatewithPREPEND. Your transformation or colour would apply to the original content, which would appear shifted or tinted. - Ignoring
/Rotate. Always test with at least one rotated document. A stamp that is "sideways" only on some pages is a sign that the visible matrix is missing. - Reusing the document's fonts. They're subsets; load your own with
InvoiceLabFonts. - Creating the
PDExtendedGraphicsStateinside the loop. Each call toShapes.opacitycreates a new object that ends up in the resources of every page. Create it once per document, astranslucent()does. - Opening two
PDPageContentStreaminstances on the same page at the same time. Open, draw and close; then the next one.stampguarantees this with itstry. - Tip: watermarks and stamps drawn this way are page content. If you need the user to be able to hide them, or have them appear only when printing, you'll see optional content in lesson 04-05; and if you need a stamp that can be moved or deleted in the viewer, that's an annotation (lesson 06-05).
Exercises
Exercise 1. Generalise the stamp: create public void rubberStamp(PDPage page, String title, String detail, Color color) with the same design as paidStamp, rewrite paidStamp to use it and add voidStamp(PDPage page, String reason) in red.
Exercise 2. You've seen that the watermark underneath disappears under the fills and that the one on top "washes out" the colours. There's a third way: drawing it on top with the multiply blend mode (BlendMode.MULTIPLY), which darkens what lies beneath without covering it, like a highlighter pen. Write a program that, using Stamper.stamp, puts «DRAFT» in light pink (#F2C6C6) with that mode on every page of F-2026-0001.
Exercise 3. Write a program that processes all the .pdf files in the output/incoming/ folder in alphabetical order: it gives each one a registry stamp (2026/000124, 2026/000125…) with the current date and time and a Bates numbering that is continuous across documents, and saves it incrementally into output/registered/ with the same name.
Solutions
Solution 1.
public void rubberStamp(PDPage page, String title, String detail, Color color) throws IOException {
PDFont bold = fonts.bold();
PDFont regular = fonts.regular();
String cleanTitle = InvoiceLabFonts.sanitize(bold, title);
String cleanDetail = InvoiceLabFonts.sanitize(regular, detail);
float width = Measures.mm(58);
float height = Measures.mm(22);
stamp(page, AppendMode.APPEND, (content, visible) -> {
float cx = visible.getWidth() - Measures.mm(45);
float cy = visible.getHeight() - Measures.mm(75);
content.setGraphicsStateParameters(translucent());
content.transform(Matrix.getRotateInstance(Math.toRadians(12), cx, cy));
Shapes.drawBox(content, -width / 2, -height / 2, width, height, Measures.mm(3), null, color, 2.2f);
Shapes.drawBox(content, -width / 2 + 3, -height / 2 + 3, width - 6, height - 6, Measures.mm(2),
null, color, 0.6f);
content.setNonStrokingColor(color);
TextMetrics.writeAligned(content, bold, 24, cleanTitle, 0, -Measures.mm(1.5f), Alignment.CENTER);
TextMetrics.writeAligned(content, regular, 8.5f, cleanDetail, 0, -height / 2 + Measures.mm(3.2f),
Alignment.CENTER);
});
}
public void paidStamp(PDPage page, LocalDate paymentDate) throws IOException {
rubberStamp(page, "PAID", "Paid on " + Formats.date(paymentDate), PAID_GREEN);
}
public void voidStamp(PDPage page, String reason) throws IOException {
rubberStamp(page, "VOID", reason, new Color(0xB0, 0x1E, 0x1E));
}Since the title and the detail now come from outside, they are passed through sanitize. A long reason ("Replaced by corrective invoice R-2026-0003") wouldn't fit in 58 mm: you could shorten it with TextMetrics.truncateWithEllipsis (lesson 02-04).
Solution 2.
PdfEditor.edit(Path.of("output/F-2026-0001.pdf"), Path.of("output/F-2026-0001-draft-multiply.pdf"),
PdfEditor.Mode.FULL, document -> {
Stamper stamper = new Stamper(document);
PDFont bold = new InvoiceLabFonts(document).bold();
PDExtendedGraphicsState multiply = new PDExtendedGraphicsState();
multiply.setBlendMode(BlendMode.MULTIPLY); // org.apache.pdfbox.pdmodel.graphics.blend
for (PDPage page : document.getPages()) {
stamper.stamp(page, AppendMode.APPEND, (content, visible) -> {
float w = visible.getWidth();
float h = visible.getHeight();
content.setGraphicsStateParameters(multiply);
content.setNonStrokingColor(new Color(0xF2, 0xC6, 0xC6));
content.transform(Matrix.getRotateInstance(Math.atan2(h, w), w / 2, h / 2));
TextMetrics.writeAligned(content, bold, 110, "DRAFT", 0, -40, Alignment.CENTER);
});
}
});With multiply, the resulting colour is the product of the two colours: on white it looks pink, on black text it stays black and on the blue of the header it shows as a slightly darker blue. The mark is visible everywhere and doesn't reduce the contrast of the text. The ExtGState is created once, outside the loop. (To keep things simple, the size 110 and the offset -40 are fixed; you can calculate them as in watermark.) Bear in mind that blend modes are transparency: PDF/A-1 doesn't allow them (module 8).
Solution 3.
Path incoming = Path.of("output/incoming");
Path registered = Path.of("output/registered");
List<Path> pdfs;
try (Stream<Path> files = Files.list(incoming)) {
pdfs = files.filter(p -> p.getFileName().toString().toLowerCase().endsWith(".pdf"))
.sorted()
.toList();
}
int[] nextBates = { 1 };
int entry = 124;
for (Path pdf : pdfs) {
String number = String.format("2026/%06d", entry++);
PdfEditor.edit(pdf, registered.resolve(pdf.getFileName()), PdfEditor.Mode.INCREMENTAL, document -> {
Stamper stamper = new Stamper(document);
stamper.receiptStamp(number, LocalDateTime.now());
nextBates[0] = stamper.batesNumber("NEB", nextBates[0]);
});
System.out.println(pdf.getFileName() + " → entry " + number + ", next Bates " + nextBates[0]);
}With the supplier's PDF (3 pages) and an invoice (2 pages) in the folder:
Files.listreturns aStreamthat has to be closed: that's why it goes inside atry.- The single-element array
nextBatesis a trick for modifying a value from inside the lambda (which can only capture effectively final variables). A cleaner alternative is a small counter object. - The incremental save makes sense here: it preserves the document exactly as it arrived, which may matter if the supplier signed it.
- In a real system, the registry and Bates counters would come from a database so that numbers aren't repeated between runs.
Conclusion
You now know how to add content safely to any existing page: APPEND to put it on top, PREPEND to put it underneath (wrapped in save/restore), and never the OVERWRITE of the short constructor. You understand why resetContext is essential with other people's documents, how to compensate for an offset CropBox and for /Rotate with a single matrix, and why you need to load your own fonts into the open document. The Stamper class wraps all of this up and offers the «PAID» stamp, the watermark in two variants, the receipt registry stamp and Bates numbering.
So far we've drawn on the pages that were already there. In the next lesson we'll manipulate the pages themselves: inserting, removing, rotating, reordering, duplicating, importing them from another document and cropping or scaling them, with cases such as adding the general terms and conditions at the end of an issued invoice.
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
