pdf is a module, import pdf, with two halves. A component is printed as
PDF with ui.pdf(c), which answers a pdf.Pdf: the file, which a server
function answers as application/pdf. And any PDF, printed here or brought
by a user, opens as a pdf.Document: its pages arranged, documents merged and
split, its metadata read and written, and the file encrypted and saved again.
The work is the host’s, in Rust, so std/pdf is available on the server and
native hosts and not in the browser. A program built for the browser that
reaches pdf.open is refused (ATOLL1132): call it from a server function.
No call holds the reactor. An operation whose cost grows with the document, a file or what it answers (opening, saving, copying, merging, splitting, editing pages, reading text and images, rendering, filling, signing, verifying, writing and printing) suspends the calling task: the host does the work on its blocking pool while the program’s other tasks run, and the answer arrives when it is done. A document small enough that the hand-off would cost more is answered at once, decided by its size alone. Reading one page’s annotations, a document’s metadata, or a page’s boxes answers at once whatever the file.
Opening and saving
pdf.open(data) reads the bytes in place. A damaged file is repaired as it
opens, by scanning it for its objects, and recovered() says so. An encrypted
file opens with its password, pdf.open(data, "secret"), or with none where
the empty user password opens it, as every viewer tries first. Without the
password it is PasswordRequired, and with another one WrongPassword.
save() writes the whole file. Objects nothing reaches are left out, so a
deleted page’s content is not in it, and without encryption the bytes are a
function of the document: no date, nothing random, and an /ID that is the
file’s own hash. save_with packs objects into object streams and deflates
streams that have no filter. save_incremental(original) appends an update to
the bytes the document was opened from, keeping every one of them, which is
what keeps an existing signature valid.
import pdf
fn stamped(data &[]byte) Result[[]byte, pdf.Error] {
mut doc := pdf.open(data)?
mut info := doc.info()
info.title = Some("Approved")
doc.set_info(&info)?
return doc.save_incremental(data)
}Pages
Pages are indexes from 0, and rectangles are PDF user space: points, the
origin at the bottom left, y up. pages() answers every page at once: its
media and crop boxes, with what it inherits from the page tree resolved, its
rotation, and its size as shown. The document keeps its page count, so
page_count() is no call, and an index out of range traps as a list index
does.
delete_pages, arrange (reorder, repeat or drop), rotate, set_crop and
set_media change pages in place. insert and append copy pages from
another document, each page’s objects copied once, so links between the
copied pages stay links. extract and split make new documents, and
pdf.merge joins several in order.
import pdf
fn joined(cover &[]byte, body &[]byte) Result[[]byte, pdf.Error] {
mut doc := pdf.open(cover)?
rest := pdf.open(body)?
doc.append(&rest)
doc.rotate(&[0], 90)
return doc.save()
}Reading
text(page) answers a page’s text as it now is: its lines top to bottom, the
words of a line with one space between, spaces inferred where the file draws
none. text_runs(page) answers each word with where it sits: its baseline’s
start, its width, its size and its font’s name. The page’s own content is
read, so a filled form field’s value is text of the page once the form is
flattened. Columns are read line by line across the page; reading order is
not inferred.
render(page, dpi) draws a page as a PNG, white behind and its annotations
drawn, and render_with takes a pdf.Render for a transparent background or
the page alone. The same page renders to the same bytes on one machine; the
rasterizer picks its SIMD level when it runs, so machines can differ in a
pixel’s last bits. images(page) answers every image a page draws, a JPEG as
the bytes in the file and any other image as a PNG.
The host reads the document once, at its first read, and keeps what it read
for every page until the document next changes, so reading every page of a
file reads the file once. A file the first reader refuses, a damaged object
stream behind a broken xref stream, is read again by a second reader that
opens the object streams it finds, and recovered() says so.
import pdf
fn summary(data &[]byte) Result[string, pdf.Error] {
doc := pdf.open(data)?
mut out := ""
for p in 0..doc.page_count() {
out.append("--- page ${p + 1}\n")
out.append(doc.text(p)?)
out.append("\n")
}
return Ok(out)
}
fn thumbnail(data &[]byte) Result[[]byte, pdf.Error] {
doc := pdf.open(data)?
return doc.render(0, 36.0)
}Forms
fields() answers a form’s fields with what each inherits resolved: its
fully qualified name (address.city), its kind, its value, its options or
states, and where its first widget is. fill takes every value in one call
and checks them all before it writes any: a name the form does not have is
UnknownField, and a value its field cannot take (not one of its options, too
long, a line break in a single-line field, a character its font cannot draw)
is FieldRefused, and nothing changes. Each filled widget gets an appearance
drawn from the field’s own font and size, so the value shows the same in every
viewer. flatten draws what every field shows into its page and removes the
form, so the values become page text.
Pages copied from another document bring their fields, joined to this
document’s form; a field whose name the form has already is renamed
name_2, so two filled invoices merged keep their values apart.
import pdf
fn filled(form &[]byte, name string, total string) Result[[]byte, pdf.Error] {
mut doc := pdf.open(form)?
doc.fill(&[
pdf.FieldValue { name: "name", value: name },
pdf.FieldValue { name: "total", value: total }
])?
doc.flatten()?
return doc.save()
}Annotations, outlines and attachments
annotations(page) answers a page’s notes, highlights, links and the rest,
and add_annotations adds them with appearances of their own: Annotation.note,
Annotation.link, or Annotation.new with a kind and a rectangle.
remove_annotations removes the kinds it is given. outline() and
set_outline read and write the bookmarks as a list in reading order, each
with its depth; destinations and add_destination are the named places a
link can go. attach embeds a file with its type and description,
attachment(name) answers its bytes and detach removes it; set_language
says what language the document is in.
import pdf
fn reviewed(data &[]byte, xml &[]byte) Result[[]byte, pdf.Error] {
mut doc := pdf.open(data)?
note := pdf.Annotation.note(
pdf.Rect { x: 500.0, y: 760.0, width: 20.0, height: 20.0 },
"Checked"
)
doc.add_annotations(0, &[note])?
doc.set_outline(&[pdf.OutlineItem.to("Invoice", 0, 0), pdf.OutlineItem.to("Terms", 0, 1)])
doc.attach(&pdf.Attachment.new("invoice.xml", "application/xml"), xml)?
doc.set_language("en")
return doc.save()
}Signatures
sign signs a document as PAdES baseline B: an update appended to the bytes
it was opened from, whose signature covers the whole file but itself, made with
a certificate and its RSA or ECDSA P-256 key (pdf.Signer). The signature goes
in a field of its own, visible in a rectangle or invisible, or in an unsigned
signature field the form already has. Every byte of the original is kept, so
the signatures it carries stay valid, and the document becomes the signed file,
so a second signature goes after the first. No clock is read: the signing time
is the signer’s time, and the random parts of a signature come from seed
where one is given, so a test signs the same bytes every run.
pdf.verify(data) checks every signature a file carries: whether the bytes
it covers are the ones it signed (intact), whether the signature verifies
with the certificate it carries (valid), and whether nothing was appended
after it (whole). Whether to trust the signer is the caller’s call: the
certificate’s subject is answered, and no trust store is bundled.
import pdf
fn signed(data &[]byte, certificate []byte, key []byte) Result[[]byte, pdf.Error] {
mut doc := pdf.open(data)?
mut signer := pdf.Signer.new(certificate, key)
signer.reason = Some("Approved")
signer.time = Some("2026-11-17T09:30:00Z")
return doc.sign(data, &signer, "Approval", 0, None)
}
fn checked(data &[]byte) Result[bool, pdf.Error] {
for c in pdf.verify(data)? {
if !(c.intact && c.valid) {
return Ok(false)
}
}
return Ok(true)
}Encryption
encrypt makes every later save AES-256 (ISO 32000-2, revision 6) with a user
password, an owner password and the permissions viewers honour. The file key,
salts and IVs come from the operating system, or from a seed for output that is
the same every run. A file opened with its password is saved encrypted again,
with its own key, until decrypt says otherwise. The permissions are flags
viewers respect, not a security boundary.
import pdf
fn locked(data &[]byte) Result[[]byte, pdf.Error] {
mut doc := pdf.open(data)?
mut p := pdf.Permissions.all()
p.copy = false
doc.encrypt(&pdf.Encryption.new("reader", "owner").permit(p))
return doc.save()
}Writing
A pdf.Writer draws a new file a page at a time: rectangles, lines, paths,
text in a font at a size, text broken into lines in a box, images, links,
bookmarks and attachments. Nothing reaches the host until finish: every
drawing is appended to one buffer in the program, and finish hands it over
once to be written, its fonts subset. pdf.Font.regular() and bold() are the
embedded Inter; pdf.Font.load takes any TrueType or OpenType file, once per
thread. Coordinates are those of Document: points, y up.
import pdf
fn receipt(total string) Result[pdf.Pdf, pdf.Error] {
mut w := pdf.Writer.new()
mut info := pdf.Info.new()
info.title = Some("Receipt")
w.info(&info)
w.page(pdf.Size.a4())
w.fill_rect(
pdf.Rect { x: 0.0, y: 800.0, width: 595.28, height: 41.89 },
pdf.Color.hex(0x1f2937)
)
w.text(72.0, 760.0, "Receipt", &pdf.TextStyle.new(pdf.Font.bold(), 24.0))
w.text(72.0, 730.0, "Total: ${total}", &pdf.TextStyle.new(pdf.Font.regular(), 12.0))
w.link(pdf.Rect { x: 72.0, y: 700.0, width: 200.0, height: 14.0 }, "https://example.com/terms")
return w.finish()
}A tagged file carries its structure for screen readers: begin and end
around a heading, a paragraph or a figure, and pdf.Tag.Artifact around
decoration. conform validates the file as PDF/A, PDF/UA-1 or both as it is
written, and a rule it breaks is NotConforming, naming each one: PDF/UA-1
asks for a title and a language, and PDF/A for a creation date, which is
info.created since no clock is read. place draws a page of an open
document under or over a page being written, and Document.stamp draws one on
pages of an existing file: a letterhead, a watermark.
Printing
A component whose view the PDF host can draw is printed with ui.pdf(c):
pdf.Page sets the page size and margin, pdf.Header and pdf.Footer repeat
on every page, pdf.PageNumber fills {page} and {pages}, pdf.PageBreak
starts a page and pdf.KeepTogether keeps a block on one. A text longer than
what is left of a page goes on at the top of the next, cut between its lines,
with at least two lines on each side of the cut. pdf.Background { doc, page }
draws a page of an open document under every page its pdf.Page prints: a
letterhead opened once and used by every print. The file it answers opens as a
document with p.open(), and doc.to_pdf() saves a document back into a
pdf.Pdf.
import pdf
import ui
import ui.{Text}
component Invoice(letterhead &pdf.Document, number int) {
pdf.Page { size: pdf.A4, margin: 72
pdf.Background { doc: letterhead, page: 0 }
Text { "Invoice ${number}" }
}
}
fn invoice(letterhead &pdf.Document, number int) pdf.Pdf {
return ui.pdf(Invoice { letterhead, number })
}ui.pdf_with(c, &options) prints the same view with a pdf.Print: tagged, so
each text is a paragraph and running headers, footers and page numbers are
decoration a screen reader skips; archived as a PDF/A level, dated; or
validated as PDF/UA-1.
import pdf
import ui
import ui.{Text}
component Notice(title string) {
pdf.Page { size: pdf.A4, margin: 40, title: title
Text { font_size: 18, "${title}" }
Text { "Printed for screen readers and the archive." }
}
}
fn printed() Result[pdf.Pdf, pdf.Error] {
options := pdf.Print.new().tagged("en").archival(pdf.Archival.A2a).dated("2026-11-16T09:30:00Z")
return ui.pdf_with(Notice { title: "Notice" }, &options)
}