Skip to content
Lamina PDF
0.9.0
GitHub
Open the web app

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.

Lamina PDF draws with two kinds of font:

  • The standard 14 fonts (Font.standard("Helvetica"), Standard14::Helvetica in 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.

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:

packages/sdk/examples/multilingual.ts
// 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();
}
Page 1 of multilingual.pdf
Open multilingual.pdf (1 page, 27 KB)

See the output. Text extracted from it, with pdf.js, pypdf or pdftotext, equals the input strings, ligatures included.

  • 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::Override embeds 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()).

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.

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.

  • 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.

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:

packages/sdk/examples/images-and-vectors.ts
// 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();
}
Page 1 of images_and_vectors.pdf
Open images_and_vectors.pdf (1 page, 5 KB)

See the output.

Next: 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.

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.

  • Outline: builder.outline([...]) builds the bookmarks a viewer shows beside the pages, with nested entries, colour, bold, italic and open (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.

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:

Page 1 of links_and_outlines.pdf
Open links_and_outlines.pdf (4 pages, 3 KB)

See the output.

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 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:

packages/sdk/examples/flowing-report.ts
// 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 },
];
}
Page 1 of flowing_report.pdf
Open flowing_report.pdf (13 pages, 57 KB)

The result is thirteen A5 pages: open the reference PDF.

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 Keep group 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.

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’s widows and orphans.
  • 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, or keepWithNext in 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.

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:

packages/sdk/examples/flowing-invoice.ts
// 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")}`;
}
Page 1 of flowing_invoice.pdf
Open flowing_invoice.pdf (3 pages, 27 KB)

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.

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.

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:

packages/sdk/examples/markdown-to-pdf.ts
// 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();
}
Page 1 of markdown_to_pdf.pdf
Open markdown_to_pdf.pdf (4 pages, 52 KB)

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:

Terminal window
laminapdf build report.md -o report.pdf --font regular=NotoSans-Regular.ttf --profile pdf-ua-1

If 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.

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 }).

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 with with_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.

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.

  • 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 TextStyle with that font. List fallback fonts with with_fallback for 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.

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 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.

packages/sdk/examples/pdf-ua-report.ts
// 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();
});
});
}
Page 1 of pdf_ua_report.pdf
Open pdf_ua_report.pdf (1 page, 10 KB)

See the output.

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.

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.

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.

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.

packages/sdk/examples/pdf-a-archive.ts
// 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] }),
);
}

See the output.

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.

packages/sdk/examples/pdf-a3-invoice-with-xml.ts
// 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" },
});
}

See the 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.