Add watermarks, headers, footers and Bates numbers
You’ll mark every page of a report with a faint CONFIDENTIAL, the file’s name and date, “Page 1 of 2” and a Bates number. You need this for a legal production, a review copy, or a menu item that stamps a whole document.
Like added text, a mark becomes part of the page: it prints and every reader draws it. One edit marks many pages, so you name the pages, counted from 0:
// Put the same marks on every page of a document: a hideable CONFIDENTIAL watermark, a header with// the file's name and the date, a footer that numbers the pages, and a Bates number in the corner// of each page.//// The marks become part of each page: they print and every reader draws them. The watermark sits// in an optional content group, so a reader's layers panel can switch it off, and in a tagged file// like this PDF/A-2 and PDF/UA-1 archive every mark is an artifact that screen readers skip. A header's `{page}` and// `{pages}` are filled when the edit is applied; the Bates numbers count from where you say// (number a second file from where the first ended). The marks stay changeable after a save:// `doc.content.pageMarks(index)` lists them by the IDs below.import { Document } from "@laminapdf/sdk";
/** * The document with its pages marked, saved incrementally, all in the font `font` (a TrueType or * OpenType file), which PDF/A and PDF/UA files need embedded. `at` is when the marks were made, as a * PDF date; `file` and `date` are what the header's `{file}` and `{date}` stand for, as you want * them written. */export function addPageMarks( bytes: Uint8Array, font: Uint8Array, file: string, date: string, at: string,): Uint8Array<ArrayBuffer> { using doc = Document.open(bytes); const fonts = [doc.addBlob(font)]; // Every page, counted from 0. const pages = Array.from({ length: doc.pageCount }, (_, i) => i);
// A red CONFIDENTIAL across each page, turned 45 degrees and faint, which a reader can hide. doc.content.addWatermark(pages, { id: "confidential", mark: { text: { text: "CONFIDENTIAL", fonts, size: 90, color: [0.8, 0.1, 0.1] } }, opacity: 0.2, angle: 45, hideable: true, modified: at, });
// The file's name and the date at the top right, and the page's number at the bottom centre, // clear of this report's own header at the top left and page number at the bottom right: slots in // the order top left, centre, right, then bottom left, centre, right. doc.content.setHeaderFooter(pages, { id: "folio", slots: [null, null, "{file} · {date}", null, "Page {page} of {pages}", null], fonts, size: 9, color: [0.35], date, file, modified: at, });
// ACME-000101, ACME-000102 and on, at the bottom left. doc.content.applyBates(pages, { id: "bates", prefix: "ACME-", start: 101, digits: 6, slot: "bottomLeft", fonts, size: 9, modified: at, });
return doc.save({ mode: "incremental" });}//! Put the same marks on every page of a document: a hideable CONFIDENTIAL watermark, a header//! with the file's name and the date, a footer that numbers the pages, and a Bates number in the//! corner of each page.//!//! The marks become part of each page: they print and every reader draws them. The watermark sits//! in an optional content group, so a reader's layers panel can switch it off, and in a tagged//! file like this PDF/A-2 and PDF/UA-1 archive every mark is an artifact that screen readers skip.//! The font is embedded, as both standards need. A header's `{page}`//! and `{pages}` are filled when the edit is applied; the Bates numbers count from where you say//! (number a second file from where the first ended). The marks stay changeable after a save://! [`Document::page_marks`] lists them by the IDs below.//!//! ```sh//! cargo run -p laminapdf --example add_page_marks -- in.pdf font.ttf <time> [out-dir] # the time as a PDF date//! ```
use std::error::Error;use std::path::PathBuf;
use laminapdf::{ AnnotColor, AnnotFont, ContentId, Document, MarkContent, Op, Opacity, OpenOptions, PdfDate, SaveMode, SaveOptions, Slot,};
fn main() -> Result<(), Box<dyn Error>> { let mut args = std::env::args().skip(1); let usage = "usage: add_page_marks in.pdf font.ttf <time> [out-dir]"; let input = PathBuf::from(args.next().ok_or(usage)?); let font = std::fs::read(args.next().ok_or(usage)?)?; // When the marks were made, which your app takes from its clock. let at: PdfDate = args.next().ok_or(usage)?.parse()?; let out = PathBuf::from(args.next().unwrap_or_else(|| "target/examples-out".into())); std::fs::create_dir_all(&out)?; let marked = add_page_marks(std::fs::read(&input)?, font, "archive.pdf", "27 Nov 2026", at)?; std::fs::write(out.join("add_page_marks.pdf"), marked)?; Ok(())}
/// The document with its pages marked, saved incrementally, all in the font `font` (a TrueType/// or OpenType file), which PDF/A and PDF/UA files need embedded. `file` and `date` are what the/// header's `{file}` and `{date}` stand for, as you want them written.pub(crate) fn add_page_marks( bytes: Vec<u8>, font: Vec<u8>, file: &str, date: &str, at: PdfDate,) -> Result<Vec<u8>, Box<dyn Error>> { let mut doc = Document::open_bytes(bytes, OpenOptions::new())?; let fonts = vec![AnnotFont::Font(doc.add_blob(font))]; let id = |name: &str| ContentId::new(name).ok_or("an ID is ASCII letters, digits, '-', '_' or '.'"); // Every page, counted from 0. let pages: Vec<u32> = (0..doc.page_count()?).collect();
// A red CONFIDENTIAL across each page, turned 45 degrees and faint, which a reader can hide. let text = MarkContent::Text { text: "CONFIDENTIAL".into(), fonts: fonts.clone(), size: 90.0, color: Some(AnnotColor::Rgb(0.8, 0.1, 0.1)), }; let watermark = doc .watermark(&pages, id("confidential")?, text, at)? .with_opacity(Opacity::new(0.2).ok_or("an opacity is from 0 to 1")?) .with_angle(45.0) .hideable();
// The file's name and the date at the top right, and the page's number at the bottom centre: // slots in the order top left, centre, right, then bottom left, centre, right. let mut slots: [Option<String>; 6] = Default::default(); slots[2] = Some("{file} \u{b7} {date}".into()); slots[4] = Some("Page {page} of {pages}".into()); let folio = doc .header_footer(&pages, id("folio")?, slots, at)? .with_fonts(fonts.clone(), 9.0) .with_color(AnnotColor::Gray(0.35)) .with_fields(date, file);
// ACME-000101, ACME-000102 and on, at the bottom left. let numbers = doc .bates(&pages, id("bates")?, 101, Slot::BottomLeft, at)? .with_text("ACME-", 6, "") .with_fonts(fonts, 9.0);
doc.apply(vec![Op::from(watermark), Op::from(folio), Op::from(numbers)])?; let options = SaveOptions::new().with_mode(SaveMode::Incremental); Ok(doc.save(&options)?.bytes)}
The result is the original bytes, unchanged, followed by one revision. The watermark sits in a layer, so a reader’s layers panel can switch it off.
How it works
Section titled “How it works”- Watermarks and backgrounds: a watermark is drawn in front of each page’s content and a background behind it. Each shows text, centred on the page and turned by
angledegrees counterclockwise, or an image: a watermark shows it whole inside most of the page, a background covers the page with it. Add an image’s bytes withaddBlobfirst. - Fields: a header or footer slot’s text may hold
{page},{pages},{label}(the page’s label, else its number),{date}and{file}. You give{date}and{file}as text, so the same call writes the same bytes everywhere.{{and}}are braces. The fields are filled when you apply the edit, so a page you move later keeps its number: apply the mark again withupdatePageMarkto number it afresh. - Slots: a header and footer has six slots in the order top left, centre, right, then bottom left, centre, right. Each is one line, left, centred or right aligned, between the margins (36 points unless you say otherwise). The three slots on an edge overlap, so a long text runs past its third of the page.
- Bates numbers:
startis the first page’s number, and each page after it counts one more, in the order you name the pages. To number a second file where the first ended, apply the edit to it with the nextstart. The number is padded with zeros todigits, 6 unless you say otherwise (0 for none); a wider number is not cut. - Fonts: as for added text,
fontsis the font, then its fallbacks, in Helvetica when absent. A font you give by its bytes is embedded once for the whole mark, as one subset of the glyphs every page uses, however many pages differ in their text (page numbers, Bates numbers). Helvetica, Times and Courier need no bytes. - Tagging: in a tagged file every mark is an artifact: a watermark, a background, a header, a footer or a Bates number. Screen readers skip it, and it joins no structure. A mark with text in both bands is pagination on the page, with its header part and its footer part each an artifact of its own.
- Finding them again: Lamina PDF stores each mark’s ID and what it says with the mark. After a save and a reopen,
content.pageMarks(index)lists a page’s marks,content.updatePageMark(pages, id, mark, modified)replaces one on the pages you name, andcontent.deletePageMark(pages, id)takes it off. An incremental save keeps the earlier revisions, and the mark stays in them.
What to change
Section titled “What to change”- Opacity and angle:
opacityis from 0 to 1 andanglefrom -360 to 360 degrees. - A layer a reader can hide:
hideable: trueputs the mark in an optional content group, so a reader’s layers panel can switch it off. Deleting the mark from the last page that has it takes the layer out of the file. A PDF/A-1 file can’t hold layers:doc.plan()warns withpdfa-optional-content. - A different mark of the same kind:
updatePageMarktakes the new mark as{ watermark },{ background },{ headerFooter }or{ bates }; a mark of another kind fails withinvalid-op, and a page without the mark withunknown-page-mark. - Colour and margins:
coloris a gray, RGB or CMYK array, andmarginsis{ top, right, bottom, left }in points. - A signed file: like every change to a page, a mark breaks a certified file’s signature, and an approval-signed file takes it in a revision after the signature.
- A PDF/A file: Helvetica, Times and Courier aren’t embedded, which PDF/A forbids, so
doc.plan()warns withpdfa-font-not-embedded. Give the mark a font by its bytes instead.
Next: add text to a page in the same way.