Create PDFs, on one page
This page shows every Create PDFs page in order. Read offline lists every section and the whole guide as one PDF.
Text and fonts
You’ll draw text on a page: single lines, and paragraphs that wrap to fit a box, in any script and direction. You need this whenever a PDF holds words, from a one-line label to a report in five languages.
Text needs the text module: init({ text: true }) or loadText() in TypeScript, and the default text feature in Rust.
Pick a font
Section titled “Pick a font”Lamina PDF draws with two kinds of font:
- The standard 14 fonts (
Font.standard("Helvetica"),Standard14::Helveticain Rust) need no font file and aren’t embedded, because every PDF reader has them. They cover Latin text only, without shaping. - Your own fonts (
Font.fromBytes(bytes): TrueType, OpenType or a font collection) handle any script. Lamina PDF shapes their text, so letters join and ligatures form, and embeds only the glyphs you draw.
A font is embedded once per document, however many Font objects name it.
Draw a line or a paragraph
Section titled “Draw a line or a paragraph”surface.text(str, { font, size, at }) draws one line, with at[1] its baseline. surface.textBox(str, { font, size, box, direction, align }) wraps a paragraph to fit its box and lays out each line’s words in display order, so right-to-left text reads correctly. When the text doesn’t fit, it reports overflow.
This example draws five scripts (Latin with ligatures, Arabic, Devanagari, Hebrew and Chinese), each in its own embedded font:
// Five scripts on one page, each as a single line and as a wrapped paragraph. The scripts are// Latin, Arabic and Hebrew (right to left), Devanagari and simplified Chinese; each is shaped and// bidi-resolved, and each paragraph wraps in a text box. Each script needs a font that covers it,// such as the Noto fonts (OFL).import { Builder, type BuilderOptions, type Direction, Font } from "@laminapdf/sdk";
/** Each script's line, its paragraph and the paragraph's direction, in the order of the fonts. */export const SCRIPTS: readonly (readonly [line: string, paragraph: string, direction: Direction])[] = [ [ "Latin: the office staff fill the affine waffle flask", "A paragraph breaks at spaces and fits the width of its box, line by line.", "ltr", ], ["مرحبا بالعالم السلام عليكم", "مرحبا بالعالم السلام عليكم مرحبا بالعالم السلام عليكم", "rtl"], ["नमस्ते दुनिया। हिन्दी पाठ का परीक्षण", "नमस्ते दुनिया। हिन्दी पाठ का परीक्षण नमस्ते दुनिया।", "ltr"], ["שלום עולם וברוכים הבאים", "שלום עולם וברוכים הבאים שלום עולם וברוכים הבאים", "rtl"], ["你好世界,这是中文字体子集测试。", "你好世界,这是中文字体子集测试。你好世界,这是中文。", "ltr"],];const MARGIN = 56;const FIRST_BASELINE = 80;/** The distance from one script's line to the next one's. */const SCRIPT_HEIGHT = 140;/** The paragraph's box: this far below the line, this wide and this tall. */const PARAGRAPH_DROP = 14;const PARAGRAPH_WIDTH = 220;const PARAGRAPH_HEIGHT = 100;
/** * The document's bytes. Needs `init({ text: true })`. * * @param fonts - one font file per script, in the order of {@link SCRIPTS}. * @param options - can fix the file ID, the producer and the creation date. */export function multilingual(fonts: readonly Uint8Array[], options: BuilderOptions = {}): Uint8Array<ArrayBuffer> { if (fonts.length !== SCRIPTS.length) throw new Error(`${SCRIPTS.length} fonts, one per script, are needed`); using b = new Builder(options); const loaded = fonts.map((bytes) => Font.fromBytes(bytes)); for (const font of loaded) b.font(font); const page = b.page("A4"); const s = page.surface(); SCRIPTS.forEach(([line, paragraph, direction], row) => { const font = loaded[row]; if (font === undefined) return; const y = FIRST_BASELINE + SCRIPT_HEIGHT * row; s.text(line, { font, size: 16, at: [MARGIN, y] }); // A narrow box breaks the paragraph into lines; right-to-left paragraphs start at the right. const box = [MARGIN, y + PARAGRAPH_DROP, PARAGRAPH_WIDTH, PARAGRAPH_HEIGHT] as const; s.textBox(paragraph, { font, size: 12, box, direction, align: "start" }); }); page.finish(); using doc = b.finish(); return doc.save();}//! Five scripts on one page, each as a single line and as a wrapped paragraph.//!//! The scripts are Latin, Arabic and Hebrew (right to left), Devanagari and simplified Chinese;//! each is shaped and bidi-resolved, and each paragraph wraps in a text box. Each script needs a//! font that covers it, such as the Noto fonts (OFL).//!//! ```sh//! cargo run -p laminapdf --example multilingual -- latin.ttf arabic.ttf devanagari.ttf hebrew.ttf chinese.otf//! ```
use std::error::Error;use std::path::PathBuf;
use laminapdf::{ Alignment, BuildOptions, Builder, Direction, PageSize, PointPt, Pt, RectPt, SaveOptions, TextBoxOptions,};
/// Each script's line, its paragraph and the paragraph's direction, in the order of the fonts.const SCRIPTS: [(&str, &str, Direction); 5] = [ ( "Latin: the office staff fill the affine waffle flask", "A paragraph breaks at spaces and fits the width of its box, line by line.", Direction::LeftToRight, ), ( "مرحبا بالعالم السلام عليكم", "مرحبا بالعالم السلام عليكم مرحبا بالعالم السلام عليكم", Direction::RightToLeft, ), ( "नमस्ते दुनिया। हिन्दी पाठ का परीक्षण", "नमस्ते दुनिया। हिन्दी पाठ का परीक्षण नमस्ते दुनिया।", Direction::LeftToRight, ), ( "שלום עולם וברוכים הבאים", "שלום עולם וברוכים הבאים שלום עולם וברוכים הבאים", Direction::RightToLeft, ), ( "你好世界,这是中文字体子集测试。", "你好世界,这是中文字体子集测试。你好世界,这是中文。", Direction::LeftToRight, ),];const MARGIN: f64 = 56.0;const FIRST_BASELINE: f64 = 80.0;/// The distance from one script's line to the next one's.const SCRIPT_HEIGHT: f64 = 140.0;/// The paragraph's box: this far below the line, this wide and this tall.const PARAGRAPH_DROP: f64 = 14.0;const PARAGRAPH_WIDTH: f64 = 220.0;const PARAGRAPH_HEIGHT: f64 = 100.0;
fn main() -> Result<(), Box<dyn Error>> { let mut args: Vec<String> = std::env::args().skip(1).collect(); let out = PathBuf::from(if args.len() > SCRIPTS.len() { args.remove(SCRIPTS.len()) } else { "target/examples-out".into() }); let fonts = args.iter().map(std::fs::read).collect::<Result<Vec<_>, _>>()?; std::fs::create_dir_all(&out)?; std::fs::write(out.join("multilingual.pdf"), build(BuildOptions::new(), fonts)?)?; Ok(())}
/// The document's bytes, with one font per script in `fonts` (in the order of [`SCRIPTS`])./// `options` can fix the file ID, the producer and the creation date.pub(crate) fn build(options: BuildOptions, fonts: Vec<Vec<u8>>) -> Result<Vec<u8>, Box<dyn Error>> { if fonts.len() != SCRIPTS.len() { return Err(format!("{} fonts, one per script, are needed", SCRIPTS.len()).into()); } let mut b = Builder::new(options); let fonts = fonts .into_iter() .map(|bytes| b.font_bytes(bytes)) .collect::<Result<Vec<_>, _>>()?; let mut page = b.page(PageSize::A4); let s = page.surface(); for (row, ((line, paragraph, direction), font)) in (0_u32..).zip(SCRIPTS.iter().zip(&fonts)) { let y = FIRST_BASELINE + SCRIPT_HEIGHT * f64::from(row); s.text(line, font, Pt::new(16.0), PointPt::from_points(MARGIN, y))?; // A narrow box breaks the paragraph into lines; right-to-left paragraphs start at the right. let options = TextBoxOptions::new() .with_direction(*direction) .with_align(Alignment::Start); let area = RectPt::from_points(MARGIN, y + PARAGRAPH_DROP, PARAGRAPH_WIDTH, PARAGRAPH_HEIGHT); s.text_box(paragraph, font, Pt::new(12.0), area, &options)?; } page.finish()?; let mut doc = b.finish()?; Ok(doc.save(&SaveOptions::new())?.bytes)}
See the output. Text extracted from it, with pdf.js, pypdf or pdftotext, equals the input strings, ligatures included.
When a font can’t draw the text
Section titled “When a font can’t draw the text”- A missing character: text a font can’t encode fails with
missing-glyph, never with a blank box. - Too many letters for a standard 14 font: a standard 14 font holds at most 37 distinct letters beyond its Western European set (WinAnsi); one more fails with
encoding-full. Use your own font instead. - A font that may not be embedded: a font whose licence bits forbid embedding (restricted, or bitmap only) fails with
font-not-embeddable. In Rust,EmbedPolicy::Overrideembeds it anyway, if you hold the rights. A font marked “no subsetting” is embedded whole.
Next: shapes, colour and images.
Shapes, colour and images
You’ll draw lines, shapes and images on a page, in colour and with transparency. You need this for anything visual in a PDF: a logo, a chart, the rules of a table or a photo.
Shapes and images need only the base module (init()).
Draw a shape
Section titled “Draw a shape”surface.path(p => …) returns the shape unpainted. Paint it with fill, stroke or fillStroke, or call clip to limit what comes after to its inside. A value that makes no shape, such as NaN or a negative line width, fails page.finish() with invalid-geometry.
Colour it
Section titled “Colour it”A colour is gray [g], RGB [r, g, b], CMYK [c, m, y, k] or hex. Opacity and blend modes set how a drawing mixes with what’s already on the page: in the example, multiply darkens where a shape overlaps what’s below it.
Place an image
Section titled “Place an image”Image.jpeg(bytes)embeds a JPEG as it is, without decoding it.Image.png(bytes)keeps the PNG’s transparency.Image.rgba(width, height, pixels)takes raw pixels.
Move, turn and scale
Section titled “Move, turn and scale”A Matrix rotates, scales or moves what you draw. It works in page space, like every other position.
This example draws rectangles, circles, curves and dashed strokes in several colours, with transparency, a clip and a rotation, and places a JPEG and a transparent image:
// Images and vector graphics on one A4 page. It draws shapes and a dashed Bézier curve in gray,// RGB, CMYK and hex colour, overlaps two translucent discs with a blend mode, clips a JPEG to an// ellipse and rotates an RGBA image with a soft mask. Needs only the base module.import { Builder, type BuilderOptions, Image, Matrix, type Surface } from "@laminapdf/sdk";
/** The RGBA gradient's side, in pixels. */const GLOW_SIDE = 16;
/** * The document's bytes, with `photo` (a JPEG) on the page. * * @param options - can fix the file ID, the producer and the creation date. */export function imagesAndVectors(photo: Uint8Array, options: BuilderOptions = {}): Uint8Array<ArrayBuffer> { using b = new Builder(options); const jpeg = Image.jpeg(photo); const glow = Image.rgba(GLOW_SIDE, GLOW_SIDE, gradient()); const page = b.page("A4"); const s = page.surface(); shapes(s); overlappingDiscs(s); images(s, jpeg, glow); page.finish(); using doc = b.finish(); return doc.save();}
/** A square gradient whose alpha falls off towards the right. */function gradient(): Uint8Array { const out = new Uint8Array(GLOW_SIDE * GLOW_SIDE * 4); for (let y = 0; y < GLOW_SIDE; y++) { for (let x = 0; x < GLOW_SIDE; x++) out.set([x * 16, y * 16, 200, 255 - x * 15], (y * GLOW_SIDE + x) * 4); } return out;}
/** A rectangle, a circle and a dashed, round-capped Bézier curve. */function shapes(s: Surface): void { s.fillColor([0.9, 0.3, 0.2]) .path((p) => p.rect([56, 56, 160, 100])) .fill(); s.fillColor([0.8, 0.1, 0, 0]) .path((p) => p.circle([330, 106], 50)) .fill(); s.strokeColor("#2a9d8f") .path((p) => p.moveTo(56, 220).cubicTo(180, 140, 300, 300, 539, 200)) .stroke({ width: 3, cap: "round", dash: [12, 8] });}
/** Two translucent discs, the second multiplied onto the first. */function overlappingDiscs(s: Surface): void { s.save().opacity(0.6, 1).fillColor([0.3]); s.path((p) => p.circle([120, 330], 60)).fill(); s.blendMode("multiply").fillColor([1, 0.8, 0]); s.path((p) => p.circle([190, 330], 60)) .fill() .restore();}
/** The photo clipped to an ellipse, and the gradient rotated by 30 degrees. */function images(s: Surface, photo: Image, glow: Image): void { s.save() .path((p) => p.ellipse([300, 270, 239, 120])) .clip(); s.image(photo, [300, 250, 239, 160]).restore(); s.save().transform(Matrix.after(Matrix.translate(150, 520), Matrix.rotate(30))); s.image(glow, [-60, -60, 120, 120]).restore();}//! Images and vector graphics on one A4 page.//!//! It draws shapes and a dashed Bézier curve in gray, RGB, CMYK and hex colour, overlaps two//! translucent discs with a blend mode, clips a JPEG to an ellipse and rotates an RGBA image//! with a soft mask.//!//! ```sh//! cargo run -p laminapdf --example images_and_vectors -- photo.jpg [out-dir] # writes images_and_vectors.pdf//! ```
use std::error::Error;use std::path::PathBuf;
use laminapdf::{ BlendMode, BuildOptions, Builder, Color, Dash, FillRule, Image, LineCap, Matrix, PageSize, PathBuilder, PointPt, Pt, RectPt, SaveOptions, StrokeStyle, Surface,};
/// The RGBA gradient's side, in pixels.const GLOW_SIDE: u8 = 16;
fn main() -> Result<(), Box<dyn Error>> { let mut args = std::env::args().skip(1); let photo = std::fs::read(args.next().ok_or("usage: images_and_vectors <photo.jpg> [out-dir]")?)?; let out = PathBuf::from(args.next().unwrap_or_else(|| "target/examples-out".into())); std::fs::create_dir_all(&out)?; std::fs::write(out.join("images_and_vectors.pdf"), build(BuildOptions::new(), photo)?)?; Ok(())}
/// The document's bytes, with `photo` (a JPEG) on the page. `options` can fix the file ID, the/// producer and the creation date.pub(crate) fn build(options: BuildOptions, photo: Vec<u8>) -> Result<Vec<u8>, Box<dyn Error>> { let mut b = Builder::new(options); let photo = Image::jpeg(photo)?; let glow = Image::rgba(u32::from(GLOW_SIDE), u32::from(GLOW_SIDE), &gradient())?; let mut page = b.page(PageSize::A4); let s = page.surface(); shapes(s)?; overlapping_discs(s); images(s, &photo, &glow); page.finish()?; let mut doc = b.finish()?; Ok(doc.save(&SaveOptions::new())?.bytes)}
/// A square gradient whose alpha falls off towards the right.fn gradient() -> Vec<u8> { (0..GLOW_SIDE) .flat_map(|y| (0..GLOW_SIDE).flat_map(move |x| [x * 16, y * 16, 200, 255 - x * 15])) .collect()}
/// A rectangle, a circle and a dashed, round-capped Bézier curve.fn shapes(s: &mut Surface) -> Result<(), Box<dyn Error>> { let at = PointPt::from_points; s.fill_color(Color::rgb(0.9, 0.3, 0.2)) .path(|p| _ = p.rect(RectPt::from_points(56.0, 56.0, 160.0, 100.0))) .fill(FillRule::NonZero); s.fill_color(Color::cmyk(0.8, 0.1, 0.0, 0.0)) .path(|p| _ = p.circle(at(330.0, 106.0), Pt::new(50.0))) .fill(FillRule::NonZero); let dashed = StrokeStyle { width: Pt::new(3.0), cap: LineCap::Round, dash: Some(Dash::new(vec![12.0, 8.0], 0.0)), ..StrokeStyle::default() }; s.stroke_color(Color::hex("#2a9d8f")?) .path(|p| { p.move_to(at(56.0, 220.0)) .cubic_to(at(180.0, 140.0), at(300.0, 300.0), at(539.0, 200.0)); }) .stroke(&dashed); Ok(())}
/// Two translucent discs, the second multiplied onto the first.fn overlapping_discs(s: &mut Surface) { let disc = |x: f64| move |p: &mut PathBuilder| _ = p.circle(PointPt::from_points(x, 330.0), Pt::new(60.0)); s.save().opacity(0.6, 1.0).fill_color(Color::gray(0.3)); s.path(disc(120.0)).fill(FillRule::NonZero); s.blend_mode(BlendMode::Multiply).fill_color(Color::rgb(1.0, 0.8, 0.0)); s.path(disc(190.0)).fill(FillRule::NonZero).restore();}
/// The photo clipped to an ellipse, and the gradient rotated by 30 degrees.fn images(s: &mut Surface, photo: &Image, glow: &Image) { s.save() .path(|p| _ = p.ellipse(RectPt::from_points(300.0, 270.0, 239.0, 120.0))) .clip(FillRule::NonZero); s.image(photo, RectPt::from_points(300.0, 250.0, 239.0, 160.0)) .restore(); let placement = Matrix::translate(150.0, 520.0).after(&Matrix::rotate(30.0)); s.save().transform(placement); s.image(glow, RectPt::from_points(-60.0, -60.0, 120.0, 120.0)).restore();}
Next: links, outlines and metadata.
Links, outlines and metadata
You’ll make a document readers can find their way around: links between pages and to the web, an outline (the bookmarks panel), page numbers that read i, ii, 1, 2, and a title. You need this for any document longer than a page or two.
Link to a page or the web
Section titled “Link to a page or the web”surface.link(rect, target, contents) makes a clickable area. The target is a web address ({ type: "uri" }), a page ({ type: "page", index }) or a named destination ({ type: "named", name }). A text run takes a link option too. The builder checks every target when it finishes: a missing page fails with page-index-out-of-range, and a missing name with unknown-destination.
builder.destination(name, index) names a page, so links can point to it by name.
Add an outline and page labels
Section titled “Add an outline and page labels”- Outline:
builder.outline([...])builds the bookmarks a viewer shows beside the pages, with nested entries, colour, bold, italic andopen(an entry shown expanded). - Page labels:
builder.pageLabels([{ start, style }])sets the page numbers a viewer shows. The example below uses roman numerals for the front matter, then decimal from page 3. - Viewer preferences: for example,
pageMode: "outlines"opens the file with the outline showing.
Set the metadata
Section titled “Set the metadata”builder.metadata({ title, author, … }) sets the document’s title, author and the rest (see Details).
This example builds four pages that link to each other and to the web, with an outline, page labels and the outline shown on open. It draws its labels as text, so it needs the text module. It sets no metadata (Edit a PDF does). The example:
// Links and outlines: four A5 pages joined by links, bookmarks and page labels. The title page// links to a website, to a page and through a named destination; every other page has a linked// text run back to it. The outline is nested and shown when the file opens.import { Builder, type BuilderOptions, Font, type LinkTarget, type Surface } from "@laminapdf/sdk";
const TITLES = ["Title page", "Contents", "Chapter 1", "Chapter 2"] as const;const MARGIN = 36;const TITLE_BASELINE = 60;const TITLE_SIZE = 18;const LINK_SIZE = 12;/** The baselines of the title page's three links. */const LINK_BASELINES = [100, 125, 150] as const;/** A link's clickable box: this wide, this tall, starting this far above the baseline. */const LINK_WIDTH = 220;const LINK_HEIGHT = 20;const LINK_RISE = 15;
/** * The document's bytes. Needs `init({ text: true })`. * * @param options - can fix the file ID, the producer and the creation date. */export function linksAndOutlines(options: BuilderOptions = {}): Uint8Array<ArrayBuffer> { using b = new Builder(options); const font = Font.standard("Helvetica"); b.font(font); b.destination("chapter-2", 3); TITLES.forEach((title, index) => { const page = b.page("A5"); const s = page.surface(); s.text(title, { font, size: TITLE_SIZE, at: [MARGIN, TITLE_BASELINE] }); if (index === 0) titlePageLinks(s, font); else { const link = { target: { type: "page", index: 0 }, contents: "Title page" } as const; s.text("Back to the title page", { font, size: LINK_SIZE, at: [MARGIN, 100], fill: [0, 0.2, 0.8], link }); } page.finish(); }); navigation(b); using doc = b.finish(); return doc.save();}
/** The title page's links: to a website, to a page, and to a named destination. */function titlePageLinks(s: Surface, font: Font): void { const links: readonly (readonly [label: string, target: LinkTarget, contents?: string])[] = [ ["Visit example.com", { type: "uri", uri: "https://example.com/" }, "Example"], ["Go to chapter 1", { type: "page", index: 2 }], ["Go to chapter 2 (named)", { type: "named", name: "chapter-2" }], ]; links.forEach(([label, target, contents], i) => { const baseline = LINK_BASELINES[i] ?? 0; s.text(label, { font, size: LINK_SIZE, at: [MARGIN, baseline] }); s.link([MARGIN, baseline - LINK_RISE, LINK_WIDTH, LINK_HEIGHT], target, contents); });}
/** The outline (bookmarks), the page labels, and the viewer opening with the outline shown. */function navigation(b: Builder): void { b.outline([ { title: "Title page", target: { type: "page", index: 0 } }, { title: "Contents", target: { type: "page", index: 1 }, color: [0, 0, 0.6] }, { title: "Chapters", open: true, bold: true, children: [ { title: "Chapter 1", target: { type: "page", index: 2 } }, { title: "Chapter 2", target: { type: "named", name: "chapter-2" }, italic: true }, ], }, ]); b.pageLabels([ { start: 0, style: "lowerRoman" }, { start: 2, style: "decimal" }, ]).viewerPreferences({ pageMode: "outlines" });}//! Links and outlines: four A5 pages joined by links, bookmarks and page labels.//!//! The title page has a URI link, a link to a page and one through a named destination; every//! other page has a linked text run back to it. The outline (bookmarks) is nested and open in//! the viewer, and the pages are labelled i, ii, 1, 2.//!//! ```sh//! cargo run -p laminapdf --example links_and_outlines -- [out-dir] # writes <out-dir>/links_and_outlines.pdf//! ```
use std::error::Error;use std::path::PathBuf;
use laminapdf::{ BuildOptions, Builder, Color, Fit, FontHandle, LabelStyle, LinkTarget, OutlineEntry, PageLabel, PageMode, PageSize, PointPt, Pt, RectPt, SaveOptions, Standard14, Surface, ViewerPreferences,};
const TITLES: [&str; 4] = ["Title page", "Contents", "Chapter 1", "Chapter 2"];const MARGIN: f64 = 36.0;const TITLE_AT: PointPt = PointPt::from_points(MARGIN, 60.0);const BACK_AT: PointPt = PointPt::from_points(MARGIN, 100.0);const TITLE_SIZE: Pt = Pt::new(18.0);const LINK_SIZE: Pt = Pt::new(12.0);/// The baselines of the title page's three links.const LINK_BASELINES: [f64; 3] = [100.0, 125.0, 150.0];/// A link's clickable box: this wide, this tall, starting this far above the baseline.const LINK_WIDTH: f64 = 220.0;const LINK_HEIGHT: f64 = 20.0;const LINK_RISE: f64 = 15.0;
fn main() -> Result<(), Box<dyn Error>> { let out = PathBuf::from(std::env::args().nth(1).unwrap_or_else(|| "target/examples-out".into())); std::fs::create_dir_all(&out)?; std::fs::write(out.join("links_and_outlines.pdf"), build(BuildOptions::new())?)?; Ok(())}
/// The document's bytes. `options` can fix the file ID, the producer and the creation date.pub(crate) fn build(options: BuildOptions) -> Result<Vec<u8>, Box<dyn Error>> { let mut b = Builder::new(options); let helvetica = b.standard_font(Standard14::Helvetica)?; b.destination("chapter-2", 3, Fit::Page); for (index, title) in (0_u32..).zip(TITLES) { let mut page = b.page(PageSize::A5); let s = page.surface(); s.text(title, &helvetica, TITLE_SIZE, TITLE_AT)?; if index == 0 { title_page_links(s, &helvetica)?; } else { s.text("Back to the title page", &helvetica, LINK_SIZE, BACK_AT)? .fill(Color::rgb(0.0, 0.2, 0.8)) .link(LinkTarget::page(0), Some("Title page".into())); } page.finish()?; } navigation(&mut b)?; let mut doc = b.finish()?; Ok(doc.save(&SaveOptions::new())?.bytes)}
/// The title page's links: to a website, to a page, and to a named destination.fn title_page_links(s: &mut Surface, font: &FontHandle) -> Result<(), Box<dyn Error>> { let site = LinkTarget::Uri("https://example.com/".into()); let links = [ ("Visit example.com", site, Some("Example")), ("Go to chapter 1", LinkTarget::page(2), None), ("Go to chapter 2 (named)", LinkTarget::Named("chapter-2".into()), None), ]; for ((label, target, contents), baseline) in links.into_iter().zip(LINK_BASELINES) { s.text(label, font, LINK_SIZE, PointPt::from_points(MARGIN, baseline))?; let area = RectPt::from_points(MARGIN, baseline - LINK_RISE, LINK_WIDTH, LINK_HEIGHT); s.link(area, target, contents.map(String::from)); } Ok(())}
/// The outline (bookmarks), the page labels, and the viewer opening with the outline shown.fn navigation(b: &mut Builder) -> Result<(), Box<dyn Error>> { b.outline(vec![ OutlineEntry::new("Title page", LinkTarget::page(0)), OutlineEntry::new("Contents", LinkTarget::page(1)).with_color(0.0, 0.0, 0.6), OutlineEntry::heading("Chapters") .open(true) .bold() .with_child(OutlineEntry::new("Chapter 1", LinkTarget::page(2))) .with_child(OutlineEntry::new("Chapter 2", LinkTarget::Named("chapter-2".into())).italic()), ])?; b.page_labels(vec![ PageLabel::new(0, Some(LabelStyle::LowerRoman)), PageLabel::new(2, Some(LabelStyle::Decimal)), ]) .viewer_preferences(ViewerPreferences::default().with_page_mode(PageMode::Outlines)); Ok(())}




Next: accessible PDFs.
Pages that flow
This guide lays out a document whose length you don’t know in advance, such as a report or a contract. You give Lamina PDF blocks and a page template, and it makes as many pages as they need, with a header and a footer on each.
It keeps headings with their text and never leaves a single line of a paragraph alone at a page’s foot or head, and it tags the result so screen readers can follow it. In Rust you build the blocks with types such as Flow, Paragraph and Table. In TypeScript you give it the same document as plain objects, or as Markdown; the JSON section explains the format.
The example
Section titled “The example”The example builds a 13-page report: a cover with a contents page, then five sections of headings, paragraphs, a footnote, a bulleted list and a photo. One paragraph is in Arabic and one in Hindi, and each is split by a page break. Every page after the cover names its section in the header and says “Page 3 of 13” in the footer, and every section has a bookmark. The report is built under PDF/UA-1, the accessibility standard, so the build fails if the output breaks one of its rules.
The TypeScript version describes the same report in plain objects, in the laminapdf.document/1 format, with a named style for each kind of text. It passes the fonts and the photo beside the document, by the names the document uses. Both languages write the same bytes:
// A report that flows across pages: a cover with a contents page, then sections whose// paragraphs break between pages, footnotes at the foot of their page, the section's title in// a running header and "Page X of Y" in the footer.//// Lines split with at least two at a page's foot and head, headings stay with what follows, and the// photo moves whole. The document is plain objects; its fonts and photo come beside it by name.import { type BlockSpec, Builder, type BuilderOptions, type FlowDocument, Font, Image } from "@laminapdf/sdk";
const TITLE = "Reading files offline: a year of the reader";const ARABIC = "يعمل القارئ دون اتصال بالشبكة، فتُفتح الملفات وتُقرأ وتُبحث على الجهاز نفسه، ولا يغادر أي منها الحاسوب.";const HINDI = "नमस्ते दुनिया। हिन्दी पाठ का परीक्षण।";const TOPICS = ["Opening files", "Search", "Printing", "Signing", "What comes next"];const PHOTO_WIDTH = 200;const PARAGRAPH_SPACE = 8;const FOOTER = { center: "Page {page} of {pages}" };
/** The report's fonts: Latin, a collection whose second face is the bold one, Arabic and Devanagari. */export type FlowingReportFonts = Readonly<Record<"regular" | "bold" | "arabic" | "devanagari", Uint8Array>>;
/** * The report's bytes. Needs `init({ text: true })`. * * @param fonts - the fonts to set it in. * @param photo - the JPEG each section shows. * @param options - can fix the file ID, the producer and the creation date. */export function flowingReport( fonts: FlowingReportFonts, photo: Uint8Array, options: BuilderOptions = {},): Uint8Array<ArrayBuffer> { using b = new Builder({ ...options, profiles: ["PDF/UA-1"] }); b.flow(report(), { fonts: { regular: Font.fromBytes(fonts.regular), arabic: Font.fromBytes(fonts.arabic), devanagari: Font.fromBytes(fonts.devanagari), bold: Font.fromCollection(fonts.bold, 1), }, images: { photo: Image.jpeg(photo) }, }); using doc = b.finish(); return doc.save();}
/** The whole report: a cover with the contents, then a section per topic. */function report(): FlowDocument { const body = { font: "regular", size: 11, fallbacks: ["arabic", "devanagari"] }; return { schema: "laminapdf.document/1", title: TITLE, lang: "en", // The cover is a plain A5 page; the others name their section and their number. page: { size: "A5", first: { size: "A5" }, style: "small", header: { end: "{section}" }, footer: FOOTER }, styles: { body, note: { ...body, size: 9 }, arabic: { ...body, language: "ar" }, hindi: { ...body, language: "hi" }, heading: { font: "bold", size: 16 }, cover: { font: "bold", size: 24 }, small: { font: "regular", size: 9 }, }, blocks: [ { type: "paragraph", text: TITLE, style: "cover" }, { type: "paragraph", text: "A report from the reader's team." }, { type: "contents" }, { type: "pageBreak" }, ...TOPICS.flatMap(section), ], };}
/** A section: its heading, paragraphs (one in Arabic, one in Hindi), a list and a photo. */function section(topic: string, i: number): BlockSpec[] { const sentence = `The ${topic.toLowerCase()} work of the year changed how readers use the app every day. `; const note = { text: `Measured on our test files for ${topic}.`, style: "note" }; const paragraph = (repeats: number, withNote = false): BlockSpec => ({ type: "paragraph", text: sentence.repeat(repeats), spaceAfter: PARAGRAPH_SPACE, spans: withNote ? [{ note }] : null, }); const paragraphs = [paragraph(4), paragraph(5), paragraph(6), paragraph(7, true)]; const foreign: BlockSpec[] = []; // Section 2 has a paragraph in Arabic, section 4 one in Hindi. if (i === 1) foreign.push({ type: "paragraph", text: `${ARABIC} `.repeat(8).trimEnd(), style: "arabic" }); if (i === 3) foreign.push({ type: "paragraph", text: `${HINDI} `.repeat(12).trimEnd(), style: "hindi" }); const items = ["faster", "smaller", "easier to share"].map((word) => ({ text: `Files are ${word}.` })); const alt = `A photo of the team working on ${topic.toLowerCase()}`; return [ { type: "heading", level: 1, text: topic, style: "heading" }, ...paragraphs, ...foreign, { type: "list", kind: "bullet", items }, { type: "figure", image: "photo", alt, width: PHOTO_WIDTH }, ];}//! A report that flows across pages: a cover with a contents page, then sections whose//! paragraphs break between pages, footnotes at the foot of their page, the section's title in//! a running header and "Page X of Y" in the footer.//!//! Lines split with at least two at the foot and the head of a page, headings stay with what//! follows them, and the photo moves whole. The output is tagged, has bookmarks, and is checked//! against PDF/UA-1. Run it with `cargo run -p laminapdf --example flowing_report -- regular.ttf//! bold.ttc arabic.ttf devanagari.ttf photo.jpg`.
use std::error::Error;
use laminapdf::flow::{ Contents, Figure, Flow, FlowBlock, List, ListItem, ListKind, PageRegion, PageTemplate, Paragraph, ParagraphStyle, TextStyle,};use laminapdf::{BuildOptions, Builder, Font, Image, Metadata, PageSize, Profile, SaveOptions};
const TITLE: &str = "Reading files offline: a year of the reader";pub(crate) const ARABIC: &str = "يعمل القارئ دون اتصال بالشبكة، فتُفتح الملفات وتُقرأ وتُبحث على الجهاز نفسه، ولا يغادر أي منها الحاسوب.";pub(crate) const HINDI: &str = "नमस्ते दुनिया। हिन्दी पाठ का परीक्षण।";const TOPICS: [&str; 5] = ["Opening files", "Search", "Printing", "Signing", "What comes next"];
fn main() -> Result<(), Box<dyn Error>> { let paths: Vec<String> = std::env::args().skip(1).collect(); let [regular, bold, arabic, hindi, photo] = paths.as_slice() else { return Err("arguments: <regular.ttf> <bold.ttc> <arabic.ttf> <devanagari.ttf> <photo.jpg>".into()); }; let read = |path: &String| std::fs::read(path); let fonts = [read(regular)?, read(bold)?, read(arabic)?, read(hindi)?]; let pdf = build(BuildOptions::new(), fonts, std::fs::read(photo)?)?; std::fs::create_dir_all("target/examples-out")?; Ok(std::fs::write("target/examples-out/flowing_report.pdf", pdf)?)}
/// The report's bytes. `options` can fix the file ID, the producer and the creation date.pub(crate) fn build(options: BuildOptions, fonts: [Vec<u8>; 4], photo: Vec<u8>) -> Result<Vec<u8>, Box<dyn Error>> { let [regular, bold, arabic, hindi] = fonts; let mut b = Builder::new(options.with_profile(Profile::PdfUa1)); b.metadata(Metadata::default().with_title(TITLE)); b.lang("en"); let regular = b.font(Font::from_bytes(regular)?)?; let body = TextStyle::new(®ular, 11.0) .with_fallback(&b.font(Font::from_bytes(arabic)?)?) .with_fallback(&b.font(Font::from_bytes(hindi)?)?); let heading = TextStyle::new(&b.font(Font::from_collection(bold, 1)?)?, 16.0); let small = TextStyle::new(®ular, 9.0); let header = PageRegion::new().with_end("{section}"); let footer = PageRegion::new().with_center("Page {page} of {pages}"); let pages = PageTemplate::new(PageSize::A5).with_furniture(Some(header), Some(footer), &small); let (cover, team) = (heading.clone().with_size(24.0), "A report from the reader's team."); let mut flow = Flow::new(pages.with_first_page(PageTemplate::new(PageSize::A5))) .with_title(TITLE) .block(FlowBlock::Paragraph(Paragraph::plain(TITLE, &cover))) .block(FlowBlock::Paragraph(Paragraph::plain(team, &body))) .block(FlowBlock::Contents(Contents::new(&body))) .block(FlowBlock::PageBreak); let photo = Image::jpeg(photo)?; for (i, topic) in TOPICS.iter().enumerate() { flow = section(flow, i, topic, &body, &heading, &photo); } b.flow(&flow)?; Ok(b.finish()?.save(&SaveOptions::new())?.bytes)}
/// A section: its heading, paragraphs (one in Arabic, one in Hindi), a list and a photo.fn section(flow: Flow, i: usize, topic: &str, body: &TextStyle, heading: &TextStyle, photo: &Image) -> Flow { let sentence = format!( "The {} work of the year changed how readers use the app every day. ", topic.to_lowercase() ); let mut flow = flow.block(FlowBlock::Heading(1, Paragraph::plain(topic, heading))); let note = Paragraph::plain( format!("Measured on our test files for {topic}."), &body.clone().with_size(9.0), ); for n in 0..4 { let p = Paragraph::new(ParagraphStyle::new().with_space(0.0, 8.0)).text(sentence.repeat(n + 4), body); let p = if n == 3 { p.note(note.clone()) } else { p }; flow = flow.block(FlowBlock::Paragraph(p)); } let foreign = match i { 1 => Some((format!("{ARABIC} ").repeat(8).trim_end().to_owned(), "ar")), 3 => Some((format!("{HINDI} ").repeat(12).trim_end().to_owned(), "hi")), _ => None, }; if let Some((text, lang)) = foreign { let style = body.clone().with_language(lang); flow = flow.block(FlowBlock::Paragraph(Paragraph::plain(text, &style))); } let list = ["faster", "smaller", "easier to share"] .iter() .fold(List::new(ListKind::Bullet, body), |list, word| { list.item(ListItem::new(Paragraph::plain(format!("Files are {word}."), body))) }); let alt = format!("A photo of the team working on {}", topic.to_lowercase()); flow.block(FlowBlock::List(list)) .block(FlowBlock::Figure(Figure::new(photo.clone(), alt).with_width(200.0)))}













The result is thirteen A5 pages: open the reference PDF.
Blocks, styles and the template
Section titled “Blocks, styles and the template”A Flow is a list of blocks and the PageTemplate they flow through.
- Paragraphs are made of pieces of text, each in its own
TextStyle: its fonts, size, colour, language and a baseline rise for superscripts. A bold word is a piece in the bold font. A link is a piece with a target, and a line break or a footnote is a piece of its own. - Tables have header rows, body rows and footer rows; a later section covers them.
- A contents block lists the headings with their pages, and footnotes go in paragraphs; both are covered below.
- Headings run from level 1 to 6. Lists are bulleted or numbered, and an item can hold a nested list. A figure is an image with its alternate text, as wide as the page’s text column unless you give it a width.
- Spacers, page breaks and keep groups shape the layout: a spacer adds space, a page break starts a new page, and a
Keepgroup keeps its blocks on one page.
The template gives the page size, the margins, a header and a footer, and optionally a different first page, such as a cover without a header. A header or footer has three slots, at the start, centre and end of the line.
Where pages break
Section titled “Where pages break”The flow lays out every page before it draws any, and it follows these rules:
- Paragraphs split only between lines, leaving at least two lines at the foot of a page and two at the head of the next. When a page has room for only one line of a paragraph, the paragraph moves to the next page. Change the counts with
with_widows_and_orphans, or a JSON paragraph’swidowsandorphans. - A heading stays with the block after it, so a section never starts on the last line of a page. Any paragraph can do the same with
with_keep_with_next, orkeepWithNextin JSON. - Figures and keep groups move whole to the next page when they don’t fit.
- A paragraph continued on a page of another width is broken again at that width.
When blocks you asked to keep together are taller than a page, the flow splits them anyway and adds a flow-keep-broken warning to the report Builder::flow returns. A figure or a single line taller than a page fails with flow-content-too-large, since no page could hold it.
Tables across pages
Section titled “Tables across pages”A table can run over as many pages as its rows need, with its header on each page and every row whole. The second example builds a three-page invoice of 60 rows with a total at the end. Again, both languages write the same bytes:
// An invoice whose table runs over three pages: its header row repeats at the top of each// page, no row is split between pages, and the total stays on the page of the last row.//// The columns fit their widest cell, and numbers line up on the right. The document is plain// objects in the `laminapdf.document/1` format, which names its two fonts; their bytes come beside// it. The output is tagged (one `Table` element across the pages) and checked against PDF/UA-1.import { type BlockSpec, Builder, type BuilderOptions, type CellSpec, type FlowDocument, Font } from "@laminapdf/sdk";
const TITLE = "Invoice 2026-114";const PRODUCTS: readonly (readonly [string, number])[] = [ ["Paper, A4, 80 g, box of 2,500 sheets", 2_450], ["Toner cartridge, black", 6_900], ["Desk lamp with a weighted base and an adjustable arm", 4_275], ["Stapler", 1_290], ["Archive boxes, set of ten, with lids", 3_150], ["Ballpoint pens, box of fifty", 1_875],];const LINES = 60;const MARGIN = 56;const PADDING = 6;const RULE_WIDTH = 0.75;const ROW_RULE_WIDTH = 0.25;/** The frame and the rule under the header, the rules between rows, and the header row's shade. */const RULE = "#666666";const ROW_RULE = "#b3b3b3";const HEADER_SHADE = "#ebebeb";
/** * The invoice's bytes. Needs `init({ text: true })`. * * @param regular - the body's font. * @param bold - a collection whose second face (index 1) is the bold one. * @param options - can fix the file ID, the producer and the creation date. */export function flowingInvoice( regular: Uint8Array, bold: Uint8Array, options: BuilderOptions = {},): Uint8Array<ArrayBuffer> { using b = new Builder({ ...options, profiles: ["PDF/UA-1"] }); const document: FlowDocument = { schema: "laminapdf.document/1", title: TITLE, lang: "en", page: { size: "A4", margins: MARGIN, footer: { center: "{title}, page {page} of {pages}" }, style: "small" }, styles: { body: { font: "regular", size: 10 }, strong: { font: "bold", size: 10 }, title: { font: "bold", size: 18 }, small: { font: "regular", size: 8 }, }, blocks: [ { type: "heading", level: 1, text: TITLE, style: "title" }, { type: "paragraph", text: "Office supplies delivered in October, to be paid within 30 days." }, table(), ], }; b.flow(document, { fonts: { regular: Font.fromBytes(regular), bold: Font.fromCollection(bold, 1) } }); using doc = b.finish(); return doc.save();}
/** Sixty lines of products, a header row and a footer row with the total. */function table(): BlockSpec { const number = (text: string, style = "body"): CellSpec => ({ text, style, align: "end" }); const header = ["Item", "Description", "Qty", "Amount"].map( (text, i): CellSpec => ({ text, style: "strong", ...(i >= 2 ? { align: "end" } : {}) }), ); let total = 0; const rows = Array.from({ length: LINES }, (_, i) => { const [name, cents] = PRODUCTS[i % PRODUCTS.length] ?? ["", 0]; const qty = (i % 5) + 1; total += qty * cents; return { cells: [ { text: String(i + 1).padStart(3, "0") }, { text: name }, number(String(qty)), number(money(qty * cents)), ], }; }); return { type: "table", columns: ["auto", "auto", "auto", "auto"], padding: PADDING, frame: { width: RULE_WIDTH, color: RULE }, headerRule: { width: RULE_WIDTH, color: RULE }, rowRules: { width: ROW_RULE_WIDTH, color: ROW_RULE }, headerBackground: HEADER_SHADE, header: [{ cells: header }], rows, footer: [{ cells: [{ text: "Total", style: "strong", span: 3 }, number(money(total), "strong")] }], };}
function money(cents: number): string { return `${Math.floor(cents / 100)}.${String(cents % 100).padStart(2, "0")}`;}//! An invoice whose table runs over three pages: its header row repeats at the top of each//! page, no row is split between pages, and the total stays on the page of the last row.//!//! The columns fit their widest cell, and numbers line up on the right. The output is tagged//! (one `Table` element across the pages) and checked against PDF/UA-1. Run it with//! `cargo run -p laminapdf --example flowing_invoice -- regular.ttf bold.ttc`.
use std::error::Error;
use laminapdf::flow::{ ColumnWidth, Flow, FlowBlock, Margins, PageRegion, PageTemplate, Paragraph, Table, TableCell, TableRow, TableRule, TextStyle,};use laminapdf::{Alignment, BuildOptions, Builder, Color, Font, Metadata, PageSize, Profile, SaveOptions};
const TITLE: &str = "Invoice 2026-114";const PRODUCTS: [(&str, usize); 6] = [ ("Paper, A4, 80 g, box of 2,500 sheets", 2_450), ("Toner cartridge, black", 6_900), ("Desk lamp with a weighted base and an adjustable arm", 4_275), ("Stapler", 1_290), ("Archive boxes, set of ten, with lids", 3_150), ("Ballpoint pens, box of fifty", 1_875),];
fn main() -> Result<(), Box<dyn Error>> { let paths: Vec<String> = std::env::args().skip(1).collect(); let [regular, bold] = paths.as_slice() else { return Err("arguments: <regular.ttf> <bold.ttc>".into()); }; let pdf = build(BuildOptions::new(), std::fs::read(regular)?, std::fs::read(bold)?)?; std::fs::create_dir_all("target/examples-out")?; Ok(std::fs::write("target/examples-out/flowing_invoice.pdf", pdf)?)}
/// The invoice's bytes. `options` can fix the file ID, the producer and the creation date.pub(crate) fn build(options: BuildOptions, regular: Vec<u8>, bold: Vec<u8>) -> Result<Vec<u8>, Box<dyn Error>> { let mut b = Builder::new(options.with_profile(Profile::PdfUa1)); b.metadata(Metadata::default().with_title(TITLE)); b.lang("en"); let body = TextStyle::new(&b.font(Font::from_bytes(regular)?)?, 10.0); let strong = TextStyle::new(&b.font(Font::from_collection(bold, 1)?)?, 10.0); let footer = PageRegion::new().with_center("{title}, page {page} of {pages}"); let pages = PageTemplate::new(PageSize::A4) .with_margins(Margins::all(56.0)) .with_furniture(None, Some(footer), &body.clone().with_size(8.0)); let flow = Flow::new(pages) .with_title(TITLE) .block(FlowBlock::Heading( 1, Paragraph::plain(TITLE, &strong.clone().with_size(18.0)), )) .block(FlowBlock::Paragraph(Paragraph::plain( "Office supplies delivered in October, to be paid within 30 days.", &body, ))) .block(FlowBlock::Table(table(&body, &strong))); b.flow(&flow)?; Ok(b.finish()?.save(&SaveOptions::new())?.bytes)}
/// Sixty lines of products, a header row and a footer row with the total.fn table(body: &TextStyle, strong: &TextStyle) -> Table { let number = |text: String, style: &TextStyle| TableCell::plain(text, style).with_align(Alignment::End); let header = ["Item", "Description", "Qty", "Amount"] .iter() .enumerate() .fold(TableRow::new(), |row, (i, text)| { let cell = TableCell::plain(*text, strong); row.cell(if i >= 2 { cell.with_align(Alignment::End) } else { cell }) }); let mut table = Table::new([ColumnWidth::Auto; 4]) .with_padding(6.0) .with_frame(TableRule::new(0.75, Color::rgb8(0x66, 0x66, 0x66))) .with_header_rule(TableRule::new(0.75, Color::rgb8(0x66, 0x66, 0x66))) .with_row_rules(TableRule::new(0.25, Color::rgb8(0xb3, 0xb3, 0xb3))) .with_header_background(Color::rgb8(0xeb, 0xeb, 0xeb)) .header(header); let mut total = 0; for (i, (name, cents)) in PRODUCTS.iter().cycle().take(60).enumerate() { let qty = i % 5 + 1; total += qty * cents; table = table.row( TableRow::new() .cell(TableCell::plain(format!("{:03}", i + 1), body)) .cell(TableCell::plain(*name, body)) .cell(number(qty.to_string(), body)) .cell(number(money(qty * cents), body)), ); } let total_row = TableRow::new() .cell(TableCell::plain("Total", strong).with_span(3)) .cell(number(money(total), strong)); table.footer(total_row)}
fn money(cents: usize) -> String { format!("{}.{:02}", cents / 100, cents % 100)}



The result is three A4 pages: open the reference PDF.
A table follows three rules when it crosses a page:
- The header rows repeat at the top of every page the table continues on.
- A body row never splits. A row that doesn’t fit what is left of a page starts the next one, and a row taller than a page fails with
flow-content-too-large. - The footer rows stay with the last body row, so a total never starts a page alone. When the footer doesn’t fit under the last row, that row moves to the next page with the footer.
Columns get their widths once, for the whole table, so they line up from page to page. A column is Fixed (a width in points), Auto (as wide as its widest cell) or a Fraction (a share of the width the others leave). When automatic columns are too wide together, the widest ones narrow first, so a column of numbers keeps its width while the descriptions wrap.
A cell holds one or more paragraphs. with_align lines its text up at the start, centre or end (numbers at the end), and with_vertical_align places it in the row. with_span stretches a cell over several columns, as the invoice’s “Total” does. Rules come from with_frame, with_header_rule and with_row_rules, and with_header_background shades the header rows. In a JSON document, as in the TypeScript invoice, a cell takes align, valign and span. The table takes padding, frame, headerRule, rowRules and headerBackground, with colours written as #rrggbb.
Footnotes, a contents page and bookmarks
Section titled “Footnotes, a contents page and bookmarks”A footnote is part of a paragraph: Paragraph::note(body) puts a raised number where you add it and the note’s body at the foot of the same page. In JSON, a span’s note does the same. Notes are numbered 1, 2, 3 through the flow. A short rule separates them from the text above, and the page’s footer stays below them. When a line’s notes don’t fit at the foot of its page, the line moves to the next page with them.
A contents block, FlowBlock::Contents, lists the flow’s headings with the page each one starts on. Each entry is indented by its heading’s level, with dots leading to its number, and the entry links to its heading. By default it lists levels 1 and 2; Contents::with_levels changes that, as does levels in JSON. The report in the example puts its contents on the cover.
The flow can’t know the page numbers before it has laid the pages out. So it lays everything out, writes the numbers it found into the contents page, and lays out again to check them. Each entry keeps room for a number of up to four digits, so the contents page keeps its length and the second layout confirms the numbers.
Every heading also gets a bookmark. PDF readers list the bookmarks in their sidebar, nested by heading level, and each one goes to its heading. Turn them off with Flow::with_outline(false), or outline: false in JSON.
Write it in Markdown
Section titled “Write it in Markdown”You can also write the document in Markdown and let Builder::markdown turn it into blocks. Each Markdown construct becomes the block you would build by hand: a # heading becomes a heading, a list becomes a list, and a table becomes a table that runs across pages, its header row repeated on each. A link to #a-heading goes to the heading of that name, written the way GitHub writes it: lower case, with hyphens for spaces. Front matter at the top, plain key: value lines between two --- lines, sets the document’s title, language, author and subject.
The example below builds a short report from a Markdown file. It gives the fonts, the page template and a contents page in MarkdownBuildOptions, and it passes the one image the Markdown names. The builder reads no files and fetches nothing, so it leaves out an image you don’t pass and adds a markdown-image-missing warning. It leaves out raw HTML too, with markdown-html-ignored. Both warnings give the position in the Markdown, never its text.
In TypeScript, builder.markdown(text, options) takes the same options, with the fonts as Fonts and the images as Images by the name the Markdown uses. It needs the text module, init({ text: true }). Both languages write the same bytes:
// A report written in Markdown, turned into tagged pages that flow: headings, paragraphs with// emphasis, code and links, a photo, lists and a task list, a block quote, a table that runs// across pages, a code block, footnotes, and paragraphs in Arabic and Hindi.//// The front matter gives the title and language, a contents page lists the headings, and the// output meets PDF/UA-1, so every font is embedded. The builder reads no files: the fonts and the// one photo the Markdown names are passed in, and nothing is fetched.import { Builder, type BuilderOptions, Font, Image } from "@laminapdf/sdk";
/** The fonts the report is set in: Latin, a bold face, Arabic and Devanagari. */export interface ReportFonts { readonly regular: Uint8Array; /** A collection whose second face (index 1) is the bold one. */ readonly bold: Uint8Array; readonly arabic: Uint8Array; readonly devanagari: Uint8Array;}
/** * The report's bytes. Needs `init({ text: true })`. * * @param markdown - the report's Markdown. * @param fonts - the fonts to set it in. * @param photo - the JPEG the Markdown shows as `photo.jpg`. * @param options - can fix the file ID, the producer and the creation date. */export function markdownToPdf( markdown: string, fonts: ReportFonts, photo: Uint8Array, options: BuilderOptions = {},): Uint8Array<ArrayBuffer> { using b = new Builder({ ...options, profiles: ["PDF/UA-1"] }); const report = b.markdown(markdown, { fonts: { regular: Font.fromBytes(fonts.regular), bold: Font.fromCollection(fonts.bold, 1), fallbacks: [Font.fromBytes(fonts.arabic), Font.fromBytes(fonts.devanagari)], }, images: { "photo.jpg": Image.jpeg(photo) }, // A5 pages, so the table runs across two of them, with the page number in the footer. page: { size: "A5", footer: { center: "Page {page} of {pages}" }, furnitureSize: 8 }, contents: 2, }); using doc = b.finish(); const [warning] = doc.warnings; if (warning !== undefined) throw new Error(`the Markdown has something the PDF leaves out: ${warning.code}`); if (report.pages.length === 0) throw new Error("the report has no pages"); return doc.save();}//! A report written in Markdown, turned into tagged pages that flow: headings, paragraphs with//! emphasis, code and links, a photo, lists and a task list, a block quote, a table that runs//! across pages, a code block, footnotes, and paragraphs in Arabic and Hindi.//!//! The front matter gives the title and language, a contents page lists the headings, and the//! output is checked against PDF/UA-1, so every font is embedded. Run it with `cargo run -p//! laminapdf --example markdown_to_pdf -- report.md regular.ttf bold.ttc arabic.ttf//! devanagari.ttf photo.jpg`.
use std::error::Error;
use laminapdf::flow::{PageRegion, PageTemplate, TextStyle};use laminapdf::markdown::{MarkdownBuildOptions, MarkdownFonts};use laminapdf::{BuildOptions, Builder, Font, Image, PageSize, Profile, SaveOptions};
fn main() -> Result<(), Box<dyn Error>> { let paths: Vec<String> = std::env::args().skip(1).collect(); let [markdown, regular, bold, arabic, hindi, photo] = paths.as_slice() else { return Err("arguments: <report.md> <regular.ttf> <bold.ttc> <arabic.ttf> <devanagari.ttf> <photo.jpg>".into()); }; let read = |path: &String| std::fs::read(path); let fonts = [read(regular)?, read(bold)?, read(arabic)?, read(hindi)?]; let markdown = std::fs::read_to_string(markdown)?; let pdf = build(BuildOptions::new(), &markdown, fonts, read(photo)?)?; std::fs::create_dir_all("target/examples-out")?; Ok(std::fs::write("target/examples-out/markdown_to_pdf.pdf", pdf)?)}
/// The report's bytes. `options` can fix the file ID, the producer and the creation date.pub(crate) fn build( options: BuildOptions, markdown: &str, fonts: [Vec<u8>; 4], photo: Vec<u8>,) -> Result<Vec<u8>, Box<dyn Error>> { let [regular, bold, arabic, hindi] = fonts; let mut b = Builder::new(options.with_profile(Profile::PdfUa1)); let regular = b.font(Font::from_bytes(regular)?)?; let fonts = MarkdownFonts::new(®ular) .with_bold(&b.font(Font::from_collection(bold, 1)?)?) .with_fallback(&b.font(Font::from_bytes(arabic)?)?) .with_fallback(&b.font(Font::from_bytes(hindi)?)?); // A5 pages, so the table runs across two of them, with the page number in the footer. let footer = PageRegion::new().with_center("Page {page} of {pages}"); let pages = PageTemplate::new(PageSize::A5).with_furniture(None, Some(footer), &TextStyle::new(®ular, 8.0)); let options = MarkdownBuildOptions::new() .with_fonts(fonts) .with_template(pages) .with_contents(2) .with_image("photo.jpg", Image::jpeg(photo)?); let report = b.markdown(markdown, &options)?; if let Some(warning) = report.warnings.first() { return Err(format!("the Markdown has something the PDF leaves out: {}", warning.code()).into()); } Ok(b.finish()?.save(&SaveOptions::new())?.bytes)}




The result is four A5 pages: open the reference PDF.
The laminapdf command line does the same without code. It reads the images from the Markdown’s folder and the fonts from --font:
laminapdf build report.md -o report.pdf --font regular=NotoSans-Regular.ttf --profile pdf-ua-1If you pass no fonts, the builder sets the Markdown in Helvetica and Courier, two fonts every PDF reader has. They set only Latin text, and since they aren’t embedded, a PDF/UA-1 build refuses them with font-not-embedded. Pass your own fonts with MarkdownFonts for other scripts or an accessible document.
Write it as JSON
Section titled “Write it as JSON”You can also describe the document as JSON, in the format laminapdf.document/1, and lay it out with Builder::document. The JSON names what you would build by hand. A page sets the size, margins, header and footer, styles each name a font and a size, and blocks are tagged by type, such as paragraph, heading, list, table, figure and contents. Fonts and images are named in the document, and their bytes come beside it in Resources, so the JSON holds no files.
A format with a schema suits programs and language models: they write the document, and the schema checks it before anything is drawn. Lamina PDF reads only the keys the format defines. A misspelt one fails with invalid-document, whose data.pointer names the value and whose didYouMean suggests the key it was close to.
A template is the same JSON with placeholders that fill replaces from your data. $data puts in a value and $each repeats a block or table row per item, with $item for a value of the current item. $if keeps a block only when a value is there. The Fill an invoice from JSON recipe builds a two-page invoice this way.
In TypeScript, builder.flow(document, { data, fonts, images }) takes the same document as plain objects, with the fonts as Fonts and the images as Images by name. The package’s types follow the format, so your editor flags a misspelt key or an unknown block type before anything runs. Type a document as FlowDocument, and a template with placeholders as FlowTemplate. Given data, flow fills the template first. It needs the text module, init({ text: true }).
Fields in headers and footers
Section titled “Fields in headers and footers”A slot’s text can hold fields, which the flow fills in on each page:
{page}: the page’s number in the document, from 1.{pages}: the number of pages in the document once the flow’s pages are added.{section}: the title of the last level-1 heading that started on or before the page. Choose another level withwith_section_level.{title}: the title you gave the flow.
Write {{ and }} for a literal brace. {pages} is right on every page because no page is drawn until all of them are laid out.
What the flow tags
Section titled “What the flow tags”The output is tagged unless you turn tagging off with with_tagged(false). Paragraphs are P elements, headings H1 to H6, lists L with their items, figures Figure with their alternate text, and links Link. A paragraph’s language, taken from its first piece, is set on its element; a piece in another language is a Span with that language. A paragraph split across pages stays one element, so a screen reader reads it as one.
A table is one Table element however many pages it crosses, with THead, TBody and TFoot around its rows. Header cells are TH elements that head their columns, and a cell across several columns records how many it spans.
The header rows drawn again on later pages are marked as page furniture, like headers and footers, so a screen reader and Lamina PDF’s extraction read the table’s header once. The table’s rules and background are marked as decoration too.
A footnote’s number is a Reference and its body a Note with its own identifier, inside the paragraph that cites it. A contents page is a TOC element with a TOCI for each entry, each holding its links; its dots are marked as decoration.
Headers and footers are marked as page furniture rather than content: screen readers skip them, and Lamina PDF’s own extraction leaves them out of the text.
What to change
Section titled “What to change”- A cover: give the template a first page with
with_first_page, and start the body with a page break. - Another typeface for a word: add a piece of text in a
TextStylewith that font. List fallback fonts withwith_fallbackfor characters the first font lacks. - Page numbers only: pass a footer with one centre slot,
"{page}", and no header.
Next: Accessible PDFs, for what PDF/UA-1 checks and how to meet it.
Accessible PDFs
This guide builds a report that screen-reader users can read, which you need whenever a document has to meet accessibility law or a client’s accessibility policy.
What PDF/UA asks for
Section titled “What PDF/UA asks for”PDF/UA-1 (“Universal Accessibility”) is the standard for accessible PDF. A PDF/UA file is tagged: its structure tree says which content is a heading, a paragraph, a list, a table or a figure, and in what order to read it. Everything else, such as running headers and decorative rules, is marked as an artifact, which assistive technology skips. The file also needs a title, a language, alternate text for every figure, a description for every link and embedded fonts that map each glyph to characters.
Turn the profile on with one option: profiles: ["PDF/UA-1"] in TypeScript, BuildOptions::default().with_profile(Profile::PdfUa1) in Rust. Then finish() checks the rules a program can check and fails with a coded error for the first one the document breaks:
| Rule | Error |
|---|---|
| The metadata has a title | missing-title |
The document has a language (lang) |
missing-lang |
| Everything drawn is tagged or an artifact | untagged-content |
| Every figure and formula has alternate text | missing-alt-text |
Headings start at H1 and skip no level going down |
heading-level-skipped |
One unnumbered H per section, never beside H1–H6 |
unnumbered-heading-misused |
| Table cells sit in rows, rows in tables, list items in lists | invalid-structure-nesting |
Every link has a Link element and a description |
link-without-structure, link-without-contents |
| Every font is embedded (no standard 14 font) | font-not-embedded |
| Every glyph maps to Unicode | glyph-without-unicode |
| The PDF version is 1.7 or lower | profile-version-conflict |
The builder writes the rest for you. It puts the PDF/UA identifier in the document’s XMP metadata, the XML packet in the file that describes it. It also asks viewers to show the title instead of the file name, and orders links by the structure.
The example
Section titled “The example”The report below draws its running header as an artifact. Then come a heading, a paragraph, a table with header cells, a bar chart as a figure with alternate text, and a link with a description. A small line helper gives each line of text its structure element.
// An accessible report that screen readers can follow, checked against PDF/UA-1 when it is built.import { Builder, Font, type Surface, type Tag, type TagName } from "@laminapdf/sdk";
const MARGIN = 56;const ROW = 18;const COLUMN = 144;const HEADER_BASELINE = 40;const TITLE_BASELINE = 90;const TABLE_TOP = 150;const LINK_BASELINE = 400;const CHART_LEFT = 320;const CHART_BASE = 360;const BAR_WIDTH = 36;const BAR_PITCH = 50;const BODY = 11;/** The font sizes of the title and the headings; other text is `BODY`. */const SIZES: Partial<Record<TagName, number>> = { H1: 22, H2: 15 };const BLUE = [0.12, 0.47, 0.78] as const;const QUARTERS = [ ["Q1", 120], ["Q2", 135], ["Q3", 160], ["Q4", 150],] as const;const CHART_ALT = "Bar chart of sales by quarter: 120, 135, 160 and 150 thousand euros.";
/** * The report's bytes. Needs `init({ text: true })`. * * @param notoSans - the bytes of the Noto Sans font file. */export function pdfUaReport(notoSans: Uint8Array): Uint8Array<ArrayBuffer> { using b = new Builder({ profiles: ["PDF/UA-1"] }); b.metadata({ title: "Annual sales report 2026" }); b.lang("en-GB"); const font = Font.fromBytes(notoSans); b.font(font); const page = b.page("A4"); draw(page.surface(), font); page.finish(); using doc = b.finish(); return doc.save();}
/** One line of text with its baseline at `y`, as the structure element `tag`, sized by it. */function line(s: Surface, font: Font, tag: Tag, text: string, x: number, y: number): void { const size = (typeof tag === "string" ? SIZES[tag] : undefined) ?? BODY; s.tag(tag, (s) => s.text(text, { font, size, at: [x, y] }));}
function draw(s: Surface, font: Font): void { // The running header is decoration: an artifact, which screen readers skip. s.artifact("pagination", (s) => s.text("Acme Widgets", { font, size: BODY, at: [MARGIN, HEADER_BASELINE] })); line(s, font, "H1", "Annual sales report 2026", MARGIN, TITLE_BASELINE); line(s, font, "P", "Sales grew in three quarters of four.", MARGIN, TITLE_BASELINE + 2 * ROW); table(s, font); chart(s); const link = { target: { type: "uri", uri: "https://example.com/accounts" }, contents: "The full 2026 accounts", } as const; s.tag("P", (s) => s.text("The full accounts", { font, size: BODY, at: [MARGIN, LINK_BASELINE], fill: [...BLUE], link }), );}
/** A heading and a table of the quarters, whose first row holds the columns' header cells. */function table(s: Surface, font: Font): void { line(s, font, "H2", "Sales by quarter", MARGIN, TABLE_TOP); const header: Tag = { type: "TH", scope: "column" }; s.tag("Table", (s) => { s.tag("TR", (s) => { line(s, font, header, "Quarter", MARGIN, TABLE_TOP + ROW); line(s, font, header, "Sales (k€)", MARGIN + COLUMN, TABLE_TOP + ROW); }); QUARTERS.forEach(([quarter, sales], i) => { const y = TABLE_TOP + ROW * (i + 2); s.tag("TR", (s) => { line(s, font, "TD", quarter, MARGIN, y); line(s, font, "TD", sales.toFixed(0), MARGIN + COLUMN, y); }); }); });}
/** The quarters as bars standing on the chart's base: one figure with alternate text. */function chart(s: Surface): void { s.tag({ type: "Figure", alt: CHART_ALT }, (s) => { s.fillColor([...BLUE]); QUARTERS.forEach(([, sales], i) => { s.path((p) => p.rect([CHART_LEFT + BAR_PITCH * i, CHART_BASE - sales, BAR_WIDTH, sales])).fill(); }); });}//! An accessible report that screen readers can follow, checked against PDF/UA-1 when it is built.
use laminapdf::{ ArtifactKind, BuildError, BuildOptions, Builder, Color, FillRule, FontHandle, LinkTarget, Metadata, PageSize, PointPt, Profile, Pt, RectPt, SaveOptions, Surface, TableScope, Tag, TagKind,};
const MARGIN: f64 = 56.0;const ROW: f64 = 18.0;const COLUMN: f64 = 144.0;const HEADER_AT: PointPt = PointPt::from_points(MARGIN, 40.0);const TITLE_BASELINE: f64 = 90.0;const TABLE_TOP: f64 = 150.0;const LINK_AT: PointPt = PointPt::from_points(MARGIN, 400.0);const CHART_LEFT: f64 = 320.0;const CHART_BASE: f64 = 360.0;const BAR_WIDTH: Pt = Pt::new(36.0);const BAR_PITCH: f64 = 50.0;const BODY: Pt = Pt::new(11.0);/// The font sizes of the title and the headings; other text is `BODY`.const SIZES: [(TagKind, Pt); 2] = [(TagKind::H1, Pt::new(22.0)), (TagKind::H2, Pt::new(15.0))];const BLUE: Color = Color::Rgb(0.12, 0.47, 0.78);const QUARTERS: [(&str, f64); 4] = [("Q1", 120.0), ("Q2", 135.0), ("Q3", 160.0), ("Q4", 150.0)];const CHART_ALT: &str = "Bar chart of sales by quarter: 120, 135, 160 and 150 thousand euros.";
fn main() -> Result<(), Box<dyn std::error::Error>> { let mut args = std::env::args().skip(1); let font = std::fs::read(args.next().ok_or("arguments: <font.ttf> [out-dir]")?)?; let out = std::path::PathBuf::from(args.next().unwrap_or_else(|| "target/examples-out".into())); std::fs::create_dir_all(&out)?; Ok(std::fs::write(out.join("pdf_ua_report.pdf"), build(font)?)?)}
pub(crate) fn build(font: Vec<u8>) -> Result<Vec<u8>, Box<dyn std::error::Error>> { let mut b = Builder::new(BuildOptions::new().with_profile(Profile::PdfUa1)); b.metadata(Metadata::default().with_title("Annual sales report 2026")); b.lang("en-GB"); let font = b.font_bytes(font)?; let mut page = b.page(PageSize::A4); draw(page.surface(), &font)?; page.finish()?; Ok(b.finish()?.save(&SaveOptions::new())?.bytes)}
/// One line of text with its baseline at `y`, as the structure element `tag`, sized by it.fn line(s: &mut Surface, font: &FontHandle, tag: impl Into<Tag>, text: &str, x: f64, y: f64) -> Result<(), BuildError> { let tag = tag.into(); let size = SIZES.iter().find(|e| e.0 == tag.kind()).map_or(BODY, |e| e.1); s.tag(tag, |s| s.text(text, font, size, PointPt::from_points(x, y)).map(drop))}
fn draw(s: &mut Surface, font: &FontHandle) -> Result<(), BuildError> { // The running header is decoration: an artifact, which screen readers skip. let header = |s: &mut Surface| s.text("Acme Widgets", font, BODY, HEADER_AT).map(drop); s.artifact(ArtifactKind::Pagination, header)?; line(s, font, TagKind::H1, "Annual sales report 2026", MARGIN, TITLE_BASELINE)?; let summary = "Sales grew in three quarters of four."; line(s, font, TagKind::P, summary, MARGIN, TITLE_BASELINE + 2.0 * ROW)?; table(s, font)?; chart(s)?; let link = LinkTarget::Uri("https://example.com/accounts".into()); s.tag(TagKind::P, |s| { let text = s.text("The full accounts", font, BODY, LINK_AT)?; text.fill(BLUE).link(link, Some("The full 2026 accounts".into())); Ok(()) })}
/// A heading and a table of the quarters, whose first row holds the columns' header cells.fn table(s: &mut Surface, font: &FontHandle) -> Result<(), BuildError> { line(s, font, TagKind::H2, "Sales by quarter", MARGIN, TABLE_TOP)?; let header = Tag::new(TagKind::TH).with_scope(TableScope::Column); s.tag(TagKind::Table, |s| { s.tag(TagKind::TR, |s| { line(s, font, header.clone(), "Quarter", MARGIN, TABLE_TOP + ROW)?; line(s, font, header.clone(), "Sales (k€)", MARGIN + COLUMN, TABLE_TOP + ROW) })?; for (row, (quarter, sales)) in (2_u8..).zip(QUARTERS) { let y = TABLE_TOP + ROW * f64::from(row); s.tag(TagKind::TR, |s| { line(s, font, TagKind::TD, quarter, MARGIN, y)?; line(s, font, TagKind::TD, &format!("{sales:.0}"), MARGIN + COLUMN, y) })?; } Ok(()) })}
/// The quarters as bars standing on the chart's base: one figure with alternate text.fn chart(s: &mut Surface) -> Result<(), BuildError> { s.tag(Tag::new(TagKind::Figure).with_alt(CHART_ALT), |s| { s.fill_color(BLUE); for (i, (_, sales)) in (0_u8..).zip(QUARTERS) { let x = CHART_LEFT + BAR_PITCH * f64::from(i); let bar = RectPt::from_xywh(Pt::new(x), Pt::new(CHART_BASE - sales), BAR_WIDTH, Pt::new(sales)); s.path(|p| _ = p.rect(bar)).fill(FillRule::NonZero); } Ok(()) })}
What a program can’t check
Section titled “What a program can’t check”About half of PDF/UA’s requirements need a person. Lamina PDF can check that a figure has alternate text, but not that the text describes the figure. It can check that headings go down one level at a time. It can’t check that the right text is a heading, that the reading order makes sense or that colour isn’t the only way the document conveys meaning. Read the document with a screen reader before you publish it.
How Lamina PDF checks its own output
Section titled “How Lamina PDF checks its own output”Every example on this site that claims PDF/UA-1 is validated each night with veraPDF, the open-source validator the PDF Association backs.
Next: to make a document both accessible and archival, add a PDF/A profile next to PDF/UA-1, as Archival PDFs shows.
Archival PDFs
This guide builds PDF/A documents, which you need when a file must stay readable and look the same for decades: contracts, records kept by law, e-invoices. Lamina PDF writes PDF/A as it generates a document; it doesn’t convert existing files to PDF/A.
What PDF/A asks for
Section titled “What PDF/A asks for”PDF/A is the archival subset of PDF. A PDF/A file carries everything it needs to be displayed: its fonts are embedded, its colours are defined, and nothing depends on the viewer, the network or a password. Lamina PDF writes three PDF/A profiles:
- PDF/A-2b (“basic”): the document looks the same everywhere.
- PDF/A-2u (“Unicode”): PDF/A-2b, and every glyph maps to Unicode, so the text can be searched and copied.
- PDF/A-3b: PDF/A-2b that may carry attached files of any kind.
Choose one with the profiles option (BuildOptions::with_profile in Rust). The builder then writes two things the standard asks for. It writes the PDF/A identification in the document’s XMP metadata, the XML packet in the file that describes it. That packet always agrees with the Info dictionary, the older list of the same facts (title, author, dates) that PDF readers also show.
It also writes an output intent: a declaration of what device colours mean. The intent embeds an ICC profile, the standard file format that describes a colour space. Lamina PDF’s output intent is sRGB, so RGB and gray colour are defined. DeviceCMYK is CMYK colour given as plain numbers, with no profile to say which inks they mean (Color::cmyk in Rust, four numbers in TypeScript), so the sRGB intent leaves it undefined.
finish() fails with a coded error for each rule the document breaks:
| Rule | Error |
|---|---|
| Every font is embedded (no standard 14 font) | font-not-embedded |
No DeviceCMYK colour or CMYK image (the output intent is sRGB) |
device-color-without-output-intent |
| PDF/A-2u: every glyph maps to Unicode | glyph-without-unicode |
| PDF/A-2b, PDF/A-2u: no attached files | embedded-file-forbidden |
| Every attached file has a MIME type | embedded-file-without-mime-type |
| The PDF version is 1.7 or lower | profile-version-conflict |
For CMYK colour under PDF/A, give the colour an ICC profile instead (Color::icc in Rust): an ICC-based colour defines itself. Transparency is allowed in PDF/A-2 and PDF/A-3.
An archived letter
Section titled “An archived letter”The letter below is written twice, as PDF/A-2b and as PDF/A-2u. It embeds its font, places a photo and draws a translucent band across the top. The PDF/A-2u copy is also PDF/UA-1, the accessibility standard (see Accessible PDFs): a document can be both archival and accessible.
// An archival letter, written as PDF/A-2b and as PDF/A-2u that is also PDF/UA-1.import { Builder, Font, Image, PAGE_SIZES, type Profile, type Surface } from "@laminapdf/sdk";
const MARGIN = 56;const BAND_HEIGHT = 70;const TITLE_BASELINE = 110;/** The top of the letter's text and of the photo beside it, and the height of both. */const BLOCK_TOP = 130;const BLOCK_HEIGHT = 120;const LETTER_WIDTH = 300;const PHOTO_LEFT = 380;const PHOTO_WIDTH = 160;const FOOTER_BASELINE = 300;const TITLE = 22;const BODY = 11;const BAND_OPACITY = 0.35;const PHOTO_ALT = "A photograph of the sprockets, packed in a box";const LETTER = "Thank you for your order of 12 sprockets. This letter confirms the delivery date and the price we agreed. " + "Keep it: PDF/A files look the same in any viewer, now and in the future.";
/** PDF/A-2b, or PDF/A-2u (whose text maps to Unicode) with PDF/UA-1. */const PROFILES: Record<"2b" | "2u", Profile[]> = { "2b": ["PDF/A-2b"], "2u": ["PDF/A-2u", "PDF/UA-1"],};
/** * The letter's bytes. Needs `init({ text: true })`. * * @param level - `2b` or `2u`. * @param notoSans - the bytes of the Noto Sans font file. * @param photo - the bytes of a JPEG photo. */export function pdfAArchive(level: "2b" | "2u", notoSans: Uint8Array, photo: Uint8Array): Uint8Array<ArrayBuffer> { using b = new Builder({ profiles: PROFILES[level], tagged: true }); b.metadata({ title: "Order confirmation 42", author: "Acme Widgets Ltd" }); b.lang("en-GB"); const font = Font.fromBytes(notoSans); b.font(font); const page = b.page("A4"); draw(page.surface(), font, Image.jpeg(photo)); page.finish(); using doc = b.finish(); return doc.save();}
function draw(s: Surface, font: Font, photo: Image): void { // A translucent band across the top: decoration, and transparency, which PDF/A-2 allows. const [width] = PAGE_SIZES.A4; s.artifact("layout", (s) => { s.save().opacity(BAND_OPACITY, 1).fillColor([0.12, 0.47, 0.78]); s.path((p) => p.rect([0, 0, width, BAND_HEIGHT])).fill(); s.restore(); }); s.tag("H1", (s) => s.text("Order confirmation 42", { font, size: TITLE, at: [MARGIN, TITLE_BASELINE] })); s.tag("P", (s) => s.textBox(LETTER, { font, size: BODY, box: [MARGIN, BLOCK_TOP, LETTER_WIDTH, BLOCK_HEIGHT] })); s.image(photo, [PHOTO_LEFT, BLOCK_TOP, PHOTO_WIDTH, BLOCK_HEIGHT], PHOTO_ALT); s.tag("P", (s) => s.text("Acme Widgets Ltd, 1 Example Street, London", { font, size: BODY, at: [MARGIN, FOOTER_BASELINE] }), );}//! An archival letter, written as PDF/A-2b and as PDF/A-2u that is also PDF/UA-1.//!//! Run it with `cargo run -p laminapdf --example pdf_a_archive -- <font.ttf> <photo.jpg> [out-dir]`: it writes//! `pdf_a_archive-2b.pdf` and `pdf_a_archive-2u.pdf`.
use std::error::Error;use std::path::PathBuf;
use laminapdf::{ ArtifactKind, BuildError, BuildOptions, Builder, Color, FillRule, FontHandle, Image, Metadata, PageSize, PointPt, Profile, Pt, RectPt, SaveOptions, Surface, TagKind, TextBoxOptions,};
const MARGIN: f64 = 56.0;const BAND_HEIGHT: f64 = 70.0;const TITLE_AT: PointPt = PointPt::from_points(MARGIN, 110.0);/// The top of the letter's text and of the photo beside it, and the height of both.const BLOCK_TOP: f64 = 130.0;const BLOCK_HEIGHT: f64 = 120.0;const LETTER_WIDTH: f64 = 300.0;const PHOTO_LEFT: f64 = 380.0;const PHOTO_WIDTH: f64 = 160.0;const FOOTER_AT: PointPt = PointPt::from_points(MARGIN, 300.0);const TITLE: Pt = Pt::new(22.0);const BODY: Pt = Pt::new(11.0);const BAND_OPACITY: f64 = 0.35;const PHOTO_ALT: &str = "A photograph of the sprockets, packed in a box";const LETTER: &str = "Thank you for your order of 12 sprockets. This letter confirms the delivery date and the \ price we agreed. Keep it: PDF/A files look the same in any viewer, now and in the future.";
fn main() -> Result<(), Box<dyn Error>> { let mut args = std::env::args().skip(1); let usage = "arguments: <font.ttf> <photo.jpg> [out-dir]"; let font = std::fs::read(args.next().ok_or(usage)?)?; let photo = std::fs::read(args.next().ok_or(usage)?)?; let out = PathBuf::from(args.next().unwrap_or_else(|| "target/examples-out".into())); std::fs::create_dir_all(&out)?; let a2b = build(Level::A2b, font.clone(), photo.clone())?; std::fs::write(out.join("pdf_a_archive-2b.pdf"), a2b)?; let a2u = build(Level::A2u, font, photo)?; Ok(std::fs::write(out.join("pdf_a_archive-2u.pdf"), a2u)?)}
/// Which archive to write.#[derive(Debug, Clone, Copy)]pub(crate) enum Level { /// PDF/A-2b: the letter looks the same everywhere. A2b, /// PDF/A-2u, whose text maps to Unicode, and PDF/UA-1. A2u,}
/// The letter's bytes, in `font` (a TrueType or OpenType file) with `photo` (a JPEG).pub(crate) fn build(level: Level, font: Vec<u8>, photo: Vec<u8>) -> Result<Vec<u8>, Box<dyn Error>> { let options = match level { Level::A2b => BuildOptions::new().with_profile(Profile::PdfA2b), Level::A2u => BuildOptions::new() .with_profile(Profile::PdfA2u) .with_profile(Profile::PdfUa1), }; let mut b = Builder::new(options.with_tagged(true)); b.metadata( Metadata::default() .with_title("Order confirmation 42") .with_author("Acme Widgets Ltd"), ); b.lang("en-GB"); let font = b.font_bytes(font)?; let photo = Image::jpeg(photo)?; let mut page = b.page(PageSize::A4); draw(page.surface(), &font, &photo)?; page.finish()?; let mut doc = b.finish()?; Ok(doc.save(&SaveOptions::new())?.bytes)}
fn draw(s: &mut Surface, font: &FontHandle, photo: &Image) -> Result<(), BuildError> { // A translucent band across the top: decoration, and transparency, which PDF/A-2 allows. let width = PageSize::A4.width.get(); s.artifact(ArtifactKind::Layout, |s| { s.save() .opacity(BAND_OPACITY, 1.0) .fill_color(Color::rgb(0.12, 0.47, 0.78)); s.path(|p| _ = p.rect(RectPt::from_points(0.0, 0.0, width, BAND_HEIGHT))) .fill(FillRule::NonZero); s.restore(); Ok(()) })?; s.tag(TagKind::H1, |s| { s.text("Order confirmation 42", font, TITLE, TITLE_AT).map(drop) })?; let body = RectPt::from_points(MARGIN, BLOCK_TOP, LETTER_WIDTH, BLOCK_HEIGHT); s.tag(TagKind::P, |s| { s.text_box(LETTER, font, BODY, body, &TextBoxOptions::new()).map(drop) })?; let beside = RectPt::from_points(PHOTO_LEFT, BLOCK_TOP, PHOTO_WIDTH, BLOCK_HEIGHT); s.figure(photo, beside, Some(PHOTO_ALT)); let footer = "Acme Widgets Ltd, 1 Example Street, London"; s.tag(TagKind::P, |s| s.text(footer, font, BODY, FOOTER_AT).map(drop))}


Attaching files: a hybrid invoice
Section titled “Attaching files: a hybrid invoice”PDF/A-3 lets a document carry other files, provided each one is associated with the document and says how it relates to it: its source, the data it was made from, or another representation of the same content. E-invoicing formats such as Factur-X and ZUGFeRD use this to put the machine-readable invoice (XML) inside the human-readable one (PDF).
attach(name, bytes, mime, { relationship }) adds a file, its MIME type and its relationship, and lists it in the document’s attachments. The example uses a made-up XML schema; a real e-invoice follows the EN 16931 standard and adds its own XMP metadata.
// A PDF/A-3b invoice that carries the same invoice as XML, attached for software to read.import { Builder, Font, PAGE_SIZES, type Surface } from "@laminapdf/sdk";
const MARGIN = 56;/** The page's right edge, less the margin: where the rule under the items ends. */const RIGHT = PAGE_SIZES.A4[0] - MARGIN;const AMOUNTS = 460;const ROW = 22;const TITLE_BASELINE = 80;const FIRST_ROW = 130;/** * How far above the next row's baseline the rule sits, and how far below it the total and * the note are. */const RULE_RISE = 7;const TOTAL_DROP = 18;const NOTE_DROP = 68;/** How far left of the amounts column the total starts, to fit its "Total" label. */const TOTAL_INDENT = 40;const TITLE = 24;const TOTAL = 14;const BODY = 11;const ITEMS = [ ["Sprockets", 12, 1.25], ["Gadget", 1, 79.9], ["Delivery", 1, 4.5],] as const;
/** The invoice's total. */function total(): number { return ITEMS.reduce((sum, [, qty, price]) => sum + qty * price, 0);}
/** The invoice as XML, in a made-up schema (a real e-invoice follows EN 16931, as Factur-X does). */function invoiceXml(): string { const lines = ITEMS.map( ([item, qty, price]) => ` <line item="${item}" quantity="${qty}" price="${price.toFixed(2)}"/>\n`, ); return `<?xml version="1.0" encoding="UTF-8"?>\n<invoice number="42" currency="EUR">\n${lines.join("")} <total>${total().toFixed(2)}</total>\n</invoice>\n`;}
/** * The invoice's bytes. Needs `init({ text: true })`. * * @param notoSans - the bytes of the Noto Sans font file. */export function pdfA3InvoiceWithXml(notoSans: Uint8Array): Uint8Array<ArrayBuffer> { using b = new Builder({ profiles: ["PDF/A-3b"] }); b.metadata({ title: "Invoice 42", author: "Acme Widgets Ltd" }); const font = Font.fromBytes(notoSans); b.font(font); const page = b.page("A4"); draw(page.surface(), font); page.finish(); b.attach("invoice-42.xml", new TextEncoder().encode(invoiceXml()), "text/xml", { relationship: "alternative", description: "Invoice 42 as XML", }); using doc = b.finish(); return doc.save();}
function draw(s: Surface, font: Font): void { s.text("Invoice 42", { font, size: TITLE, at: [MARGIN, TITLE_BASELINE] }); let y = FIRST_ROW; for (const [item, qty, price] of ITEMS) { s.text(`${qty} × ${item}`, { font, size: BODY, at: [MARGIN, y] }); s.text(`€ ${(qty * price).toFixed(2)}`, { font, size: BODY, at: [AMOUNTS, y] }); y += ROW; } const rule = y - RULE_RISE; s.strokeColor([0.5]) .path((p) => p.moveTo(MARGIN, rule).lineTo(RIGHT, rule)) .stroke(); s.text(`Total € ${total().toFixed(2)}`, { font, size: TOTAL, at: [AMOUNTS - TOTAL_INDENT, y + TOTAL_DROP] }); s.text("The invoice is attached as invoice-42.xml.", { font, size: BODY, at: [MARGIN, y + NOTE_DROP], link: { target: { type: "uri", uri: "https://example.com/invoices/42" }, contents: "Invoice 42 online" }, });}//! A PDF/A-3b invoice that carries the same invoice as XML, attached for software to read.//!//! Run it with `cargo run -p laminapdf --example pdf_a3_invoice_with_xml -- <font.ttf> [out-dir]`.
use std::error::Error;use std::fmt::Write as _;use std::path::PathBuf;
use laminapdf::{ AfRelationship, Attachment, BuildError, BuildOptions, Builder, Color, FontHandle, LinkTarget, Metadata, PageSize, PointPt, Profile, Pt, SaveOptions, StrokeStyle, Surface,};
const MARGIN: f64 = 56.0;/// The page's right edge, less the margin: where the rule under the items ends.const RIGHT: f64 = PageSize::A4.width.get() - MARGIN;const AMOUNTS: f64 = 460.0;const ROW: f64 = 22.0;const TITLE_BASELINE: f64 = 80.0;const FIRST_ROW: f64 = 130.0;/// How far above the next row's baseline the rule sits, and how far below it the total and/// the note are.const RULE_RISE: f64 = 7.0;const TOTAL_DROP: f64 = 18.0;const NOTE_DROP: f64 = 68.0;/// How far left of the amounts column the total starts, to fit its "Total" label.const TOTAL_INDENT: f64 = 40.0;const TITLE: Pt = Pt::new(24.0);const TOTAL: Pt = Pt::new(14.0);const BODY: Pt = Pt::new(11.0);const ITEMS: [(&str, u32, f64); 3] = [("Sprockets", 12, 1.25), ("Gadget", 1, 79.90), ("Delivery", 1, 4.50)];
fn main() -> Result<(), Box<dyn Error>> { let mut args = std::env::args().skip(1); let font = std::fs::read(args.next().ok_or("arguments: <font.ttf> [out-dir]")?)?; let out = PathBuf::from(args.next().unwrap_or_else(|| "target/examples-out".into())); std::fs::create_dir_all(&out)?; Ok(std::fs::write(out.join("pdf_a3_invoice_with_xml.pdf"), build(font)?)?)}
/// The invoice's total.fn total() -> f64 { ITEMS.iter().map(|(_, qty, price)| f64::from(*qty) * price).sum()}
/// The invoice as XML, in a made-up schema (a real e-invoice follows EN 16931, as Factur-X does).fn invoice_xml() -> Result<String, std::fmt::Error> { let mut xml = String::from("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<invoice number=\"42\" currency=\"EUR\">\n"); for (item, qty, price) in ITEMS { writeln!(xml, " <line item=\"{item}\" quantity=\"{qty}\" price=\"{price:.2}\"/>")?; } writeln!(xml, " <total>{:.2}</total>\n</invoice>", total())?; Ok(xml)}
/// The invoice's bytes, in `font` (a TrueType or OpenType file).pub(crate) fn build(font: Vec<u8>) -> Result<Vec<u8>, Box<dyn Error>> { let mut b = Builder::new(BuildOptions::new().with_profile(Profile::PdfA3b)); b.metadata( Metadata::default() .with_title("Invoice 42") .with_author("Acme Widgets Ltd"), ); let font = b.font_bytes(font)?; let mut page = b.page(PageSize::A4); draw(page.surface(), &font)?; page.finish()?; let xml = Attachment::new("invoice-42.xml", invoice_xml()?.into_bytes(), "text/xml") .with_relationship(AfRelationship::Alternative) .with_description("Invoice 42 as XML"); b.attach(xml); let mut doc = b.finish()?; Ok(doc.save(&SaveOptions::new())?.bytes)}
fn draw(s: &mut Surface, font: &FontHandle) -> Result<(), BuildError> { let at = PointPt::from_points; s.text("Invoice 42", font, TITLE, at(MARGIN, TITLE_BASELINE))?; let mut y = FIRST_ROW; for (item, qty, price) in ITEMS { s.text(&format!("{qty} × {item}"), font, BODY, at(MARGIN, y))?; let amount = f64::from(qty) * price; s.text(&format!("€ {amount:.2}"), font, BODY, at(AMOUNTS, y))?; y += ROW; } let rule = y - RULE_RISE; s.stroke_color(Color::gray(0.5)) .path(|p| _ = p.move_to(at(MARGIN, rule)).line_to(at(RIGHT, rule))) .stroke(&StrokeStyle::default()); let total_at = at(AMOUNTS - TOTAL_INDENT, y + TOTAL_DROP); s.text(&format!("Total € {:.2}", total()), font, TOTAL, total_at)?; let note = "The invoice is attached as invoice-42.xml."; let note = s.text(note, font, BODY, at(MARGIN, y + NOTE_DROP))?; let online = LinkTarget::Uri("https://example.com/invoices/42".into()); note.link(online, Some("Invoice 42 online".into())); Ok(())}
How Lamina PDF checks its own output
Section titled “How Lamina PDF checks its own output”Every example on this site that claims a PDF/A profile is validated each night with veraPDF, the open-source PDF/A and PDF/UA validator the PDF Association backs.
Next: open a PDF and change it, in Edit a PDF.