Swift

The RustPdf package wraps the rust-pdf core with idiomatic, handle-owning classes. It covers the whole product surface: vector graphics, embedded/subset fonts & Unicode text, paragraphs, images, PDF/A (1b–3a + A-4/4e/4f), tagged/accessible output, attachments, AcroForm fields, manipulation, text extraction, encryption and digital signatures. It ships as a SwiftPM package with a static xcframework, so it links into macOS and iOS apps with nothing to bundle alongside.

Two classes do almost everything. Document authors a new PDF; EditableDoc loads and manipulates an existing one. Both are reference types that own a native handle, released automatically in deinit. Stateless calls (version, licensing, extraction, signing) live on the Pdf enum. Every fallible call throws a PdfError.

Download

The binding ships as a SwiftPM package with a prebuilt, static RustPdfFFI.xcframework (macOS universal + iOS device + iOS simulator slices). Two artifacts are published per release: the self-contained package (sources + xcframework, consumed via a local path) and the standalone xcframework (consumed by URL). Basic PDF generation works immediately as a free trial; the corporate features unlock with a license token.

rustpdf-swift v0.4.2 macOS 11+ · iOS 13+ · static xcframework included · Swift 5.9+
Download package .zip SHA-256 checksum

Prefer the URL route? The standalone RustPdfFFI-0.4.2.xcframework.zip (.sha256) is referenced directly from a .binaryTarget(url:checksum:) (see Installation). Building from source? make swift-dist assembles the same artifacts.

Installation

The native library is linked statically inside the xcframework, so it works inside an iOS app bundle with no sidecar library and nothing to dlopen. Add the binding to your Package.swift one of two ways.

A. Local package. Unzip rustpdf-swift-0.4.2.zip and depend on it by path:

swift
// Package.swift
dependencies: [
    .package(path: "path/to/RustPdf")
],
targets: [
    .executableTarget(name: "MyApp", dependencies: [
        .product(name: "RustPdf", package: "RustPdf")
    ])
]

B. URL-hosted xcframework. Reference the published xcframework directly; SwiftPM downloads and verifies it:

swift
// In your Package.swift targets:
.binaryTarget(
    name: "CRustPdf",
    url: "https://rustpdf.dev/downloads/RustPdfFFI-0.4.2.xcframework.zip",
    checksum: "c9521f119a14e0ee3c60241b8cdfe691fddb7a68556c6aa9e78cbd3cc4a31108"
),
.target(
    name: "RustPdf",
    dependencies: ["CRustPdf"],
    // the static Rust library links libiconv (its only non-system dependency)
    linkerSettings: [.linkedLibrary("iconv")]
)
In Xcode you can also add the package by its repository URL (File ▸ Add Package Dependencies…) and pin the swift-v0.4.2 tag.

Import it and verify the version:

swift
import RustPdf

print(Pdf.version)   // native library version, e.g. "0.4.0"

Quick start

A one-page document with a filled rectangle, saved to disk:

swift
import RustPdf

let doc = try Document()            // A4 by default
try doc.addPage()
try doc.setFillRGB(0.86, 0.20, 0.18)
try doc.rect(x: 72, y: 640, width: 200, height: 120)   // points
try doc.fill()
try doc.save(to: "out.pdf")

Most mutators return self, so calls chain:

swift
let doc = try Document()
let font = try doc.addFont(path: "Roboto-Regular.ttf")
try doc.addPage()
    .setFillRGB(0.1, 0.1, 0.12).rect(x: 0, y: 800, width: 595, height: 42).fill()
    .showText(font: font, size: 24, x: 72, y: 740, "Olá, açúcar — café")
let data: [UInt8] = try doc.toBytes()   // in-memory bytes instead of a file
Binary payloads cross as Swift [UInt8]; the binding copies native out-buffers and frees them for you. Strings cross as UTF-8 automatically.

Licensing & activation

Basic generation (everything above) is always free. The corporate features (PDF/A, digital signatures/PAdES, encryption, accessibility) require an active license token. Without one, those calls throw PdfError with status .license and produce no output.

Activation needs no rebuild. Easiest is an environment variable, auto-activated the first time a corporate feature is used:

shell
export RUSTPDF_LICENSE="010f0000…"           # the token we email you
# or point at a file:
export RUSTPDF_LICENSE_FILE=/etc/rustpdf/license.txt

Or activate explicitly in code:

swift
try Pdf.activateLicense(token)   // throws PdfError(.license) if forged / expired / malformed
Verification is fully offline: signature + expiry checked against a public key embedded in the library. No network callback, no telemetry.

Coordinate system

Threading & concurrency

The core is Send but not Sync: you can build many documents in parallel, but a single handle must never be touched by two threads at once.

swift
DispatchQueue.concurrentPerform(iterations: 8) { i in
    do {
        let doc = try Document()            // one document per task
        try doc.addPage()
            .setFillRGB(0.1, 0.1, 0.12).rect(x: 72, y: 700, width: 200, height: 80).fill()
        try doc.save(to: "out-\(i).pdf")
    } catch { print("render \(i) failed:", error) }
}

Authoring: create & save

try Document() free

Creates an empty document (A4 default page size). The native handle is released automatically when the Document is deallocated.

MethodDescription
addPage()Append a page using the default size.
addPage(width:height:)Append a page with an explicit size in points.
setDefaultSize(width:height:)Default size for subsequently added pages.
setVersion(_:)PDF header version (.v14 / .v15 / .v17 / .v20).
pageCountNumber of pages so far.
toBytes()Render the document to [UInt8].
save(to:)Render and write to a file.
Validity. A document must have at least one page — serializing an empty document throws an error. Color components (RGB/Gray/CMYK) are clamped to the valid 0–1 range.

Pages & vector graphics

Graphics state and path operators mirror PDF's content-stream model. Colors are RGB in 0.0–1.0.

MethodDescription
setFillRGB(_:_:_:)Fill color.
setStrokeRGB(_:_:_:)Stroke color.
setLineWidth(_:)Stroke width in points.
rect(x:y:width:height:)Add a rectangle subpath.
fill()Fill the current path with the fill color.
stroke()Stroke the current path with the stroke color.
swift
try doc.addPage()
try doc.setStrokeRGB(0.10, 0.45, 0.90).setLineWidth(3)
try doc.rect(x: 72, y: 600, width: 300, height: 160).stroke()
try doc.setFillRGB(0.95, 0.77, 0.06)
try doc.rect(x: 120, y: 640, width: 120, height: 80).fill()
try doc.save(to: "shapes.pdf")

Fonts & text

Fonts are embedded and subsetted, with HarfBuzz-quality shaping, kerning and full Unicode (Type0/CIDFontType2 with ToUnicode, so text extracts and copies correctly, provided the embedded font covers those characters). Register a font once, then reference it by its integer id.

addFont(path:) -> Int32   addFont(data:) -> Int32
showText(font:size:x:y:_:headingLevel:)

headingLevel (1–6) tags the run as H1H6 in an accessible document (see Accessibility); leave 0 for ordinary text.

swift
let regular = try doc.addFont(path: "Roboto-Regular.ttf")
try doc.addPage()
try doc.showText(font: regular, size: 28, x: 72, y: 760, "Invoice #1024")
try doc.showText(font: regular, size: 12, x: 72, y: 720, "日本語 · Ελληνικά · العربية")
try doc.save(to: "text.pdf")
Font coverage. Characters outside the embedded font's coverage are silently dropped — they render as the missing-glyph box and won't extract or copy. The bundled Roboto fallback covers Latin, Greek and Cyrillic but not CJK, Arabic, Hebrew or emoji. Embed a font that covers every script you write.
No NUL bytes in strings. Text passed across the API must not contain a NUL (\0) character — it truncates the string at the FFI boundary, silently dropping everything after the NUL. This applies to shown text, metadata and field names.

Paragraphs

The paragraph layer wraps, aligns and justifies text inside a fixed width (greedy line breaking using shaped glyph widths).

paragraph(font:size:x:y:width:text:align:)
swift
let intro = "A long paragraph that wraps to the given width and is justified " +
            "automatically; extra space is distributed between words."
let f = try doc.addFont(path: "Roboto-Regular.ttf")
try doc.addPage()
try doc.paragraph(font: f, size: 12, x: 72, y: 700, width: 451, text: intro, align: .justify)
try doc.save(to: "paragraph.pdf")

See the Align enum for the alignment options.

Images

JPEGs are embedded verbatim (DCTDecode, no re-encode). PNGs are decoded and re-encoded (FlateDecode); alpha becomes an /SMask, palette becomes an Indexed color space. Register an image once, draw it many times.

MethodDescription
addImage(path:) -> Int32Load JPEG/PNG from a file; returns the image id.
addImagePNG(data:) -> Int32Register a PNG from memory.
addImageJPEG(data:) -> Int32Register a JPEG from memory.
drawImage(_:x:y:width:height:)Draw at (x, y) scaled to w × h points.
figure(_:x:y:width:height:alt:)Draw as a tagged /Figure with alt text (accessibility).
swift
let logo = try doc.addImage(path: "logo.png")
try doc.addPage()
try doc.drawImage(logo, x: 72, y: 680, width: 160, height: 90)
try doc.save(to: "with_image.pdf")

PDF/A licensed

Produce archival-grade output. pdfa() defaults to A-2b; pass a PdfaLevel for a specific level. An embedded sRGB ICC profile, output intent, XMP metadata and document /ID are added automatically; A-1b also forces PDF 1.4 and emits a /CIDSet, and A-4 (ISO 19005-4) is based on PDF 2.0.

pdfa()   pdfa(_ level: PdfaLevel)
swift
try doc.pdfa(.a2b).setInfo(DocumentInfo(title: "Q3 Report", author: "Acme Inc."))
let f = try doc.addFont(path: "Roboto-Regular.ttf")
try doc.addPage()
try doc.showText(font: f, size: 20, x: 72, y: 760, "Archival report")
try doc.save(to: "report_pdfa.pdf")   // throws without a license granting PDF/A
A document title is recommended for valid PDF/A metadata, and required for the accessible “a” levels: pass a non-empty title in DocumentInfo.

Accessibility (Tagged PDF / PDF/UA) licensed

tagged() builds a logical structure tree (PDF/UA-1). Combine with pdfa(.a2a) for archival and accessible output. Use headingLevel on showText for H1H6, and figure(…, alt:) for described images.

tagged()
swift
try doc.pdfa(.a2a).tagged().setInfo(DocumentInfo(title: "Accessible report"))
let f = try doc.addFont(path: "Roboto-Regular.ttf")
try doc.addPage()
try doc.showText(font: f, size: 26, x: 72, y: 760, "Annual report", headingLevel: 1)   // H1
try doc.showText(font: f, size: 14, x: 72, y: 720, "Overview", headingLevel: 2)         // H2
try doc.showText(font: f, size: 11, x: 72, y: 690, "Body paragraph of the section…")
let chart = try doc.addImage(path: "chart.png")
try doc.figure(chart, x: 72, y: 520, width: 300, height: 150, alt: "Revenue grew 18% year over year")
try doc.save(to: "accessible.pdf")
Figures need a tagged document. figure() only produces an accessible, alt-texted figure inside a tagged/accessible document; on a plain document the alt text has no effect.
tagged() alone is not PDF/UA-1 conformant. By itself it builds the structure tree but does not emit the XMP /Metadata stream that PDF/UA-1 requires, so veraPDF fails clause 7.1-8 ("Catalog … shall contain the Metadata key"). For output that validates as PDF/UA-1, pair it with pdfa(.a2a): pdfa(.a2a).tagged() emits the XMP and passes both verapdf -f 2a and verapdf -f ua1.

Attachments (PDF/A-3) licensed

PDF/A-3 allows embedding arbitrary source files (e.g. the XML behind an e-invoice). Each attachment carries a MIME type and an AFRelationship.

attachFile(name:mime:data:relationship:description:)
swift
let xml: [UInt8] = Array(invoiceXmlData)
try doc.pdfa(.a3b).setInfo(DocumentInfo(title: "E-invoice 1024"))
let f = try doc.addFont(path: "Roboto-Regular.ttf")
try doc.addPage()
try doc.showText(font: f, size: 18, x: 72, y: 760, "Invoice 1024")
try doc.attachFile(name: "invoice.xml", mime: "text/xml", data: xml,
                   relationship: .source, description: "Structured invoice data")
try doc.save(to: "einvoice.pdf")
PDF/A-4f needs an attachment. The A4f profile requires at least one embedded file (ISO 19005-4); the library now rejects A4f output that has no attachment, so call attachFile before serializing.
The licence gate is on PDF/A, not on attachFile itself. The licensed badge above reflects the PDF/A-3 workflow shown here. Calling attachFile on a plain (non-PDF/A) document does not require a licence: it succeeds and produces a valid PDF with an /EmbeddedFile. The licence is enforced only when you also request a PDF/A level, which is what makes the attachment archival.

ZUGFeRD / Factur-X e-invoices licensed

Turn the document into a ZUGFeRD / Factur-X electronic invoice: the embedded XML (the Cross-Industry Invoice) is attached as factur-x.xml, the file is marked PDF/A-3, and the Factur-X identification is written into the XMP metadata. The visible PDF is the human-readable invoice; the embedded XML is its machine-readable twin. Validates as PDF/A-3 + Factur-X under veraPDF.

facturx(_ xml: [UInt8], profile: FacturxProfile = .en16931)
swift
let xml: [UInt8] = Array(crossIndustryInvoiceData)   // your Factur-X XML
try doc.setInfo(DocumentInfo(title: "Invoice INV-2026-001"))
let f = try doc.addFont(path: "Roboto-Regular.ttf")
try doc.addPage()
try doc.showText(font: f, size: 18, x: 72, y: 760, "Invoice INV-2026-001")
try doc.facturx(xml, profile: .en16931)
try doc.save(to: "einvoice.pdf")     // PDF/A-3 + Factur-X; needs a PDF/A license

See the FacturxProfile enum for the conformance levels (.minimum through .extended).

AcroForm fields

Build interactive forms with generated appearance streams (no NeedAppearances). Rectangles are tuples (x0, y0, x1, y1); page is a 0-based page index. Dotted names ("a.b.c") create hierarchical fields.

MethodDescription
textField(name:page:rect:value:size:)Text input (size: 0 → auto font size).
checkbox(name:page:rect:checked:)Checkbox.
dropdown(name:page:rect:options:selected:size:)Combo box from an array of strings.
radioGroup(name:page:buttons:selected:)buttons: [RadioButton], each with a rect and an export value.
swift
try doc.addPage()
try doc.textField(name: "applicant.name", page: 0, rect: (72, 700, 320, 720))
try doc.checkbox(name: "agree", page: 0, rect: (72, 660, 88, 676), checked: false)
try doc.dropdown(name: "plan", page: 0, rect: (72, 620, 240, 640),
                 options: ["Starter", "Pro", "Enterprise"], selected: 1)
try doc.radioGroup(name: "billing", page: 0, buttons: [
    RadioButton(rect: (72, 580, 88, 596),  export: "monthly"),
    RadioButton(rect: (140, 580, 156, 596), export: "annual"),
], selected: 1)
try doc.save(to: "form.pdf")

Fill and flatten fields later with EditableDoc.

Page index and rectangle are validated. A field (or internal link) whose page does not exist, or whose rectangle is degenerate (x1 < x0 or zero area), is rejected when the document is serialized: toBytes()/save() throw PdfError ("targets page index N…" / "degenerate rectangle…") instead of producing an invisible, never-appearing widget. Pass a 0-based page index that exists and a rectangle with x1 > x0 and y1 > y0.

Add clickable link rectangles to the current page: a web link opens a URL; an internal link jumps to another page (optionally scrolling so a given top y-coordinate sits at the top of the view).

linkURI(rect:uri:)   linkToPage(rect:pageIndex:top:)
swift
let f = try doc.addFont(path: "Roboto-Regular.ttf")
try doc.addPage()
try doc.showText(font: f, size: 14, x: 72, y: 760, "Visit rustpdf.dev (see page 2)")
try doc.linkURI(rect: (72, 756, 320, 776), uri: "https://rustpdf.dev/")   // web link
try doc.linkToPage(rect: (330, 756, 430, 776), pageIndex: 1, top: 800)    // jump to page 2
try doc.addPage()
try doc.save(to: "links.pdf")

Rectangles are tuples (x0, y0, x1, y1) in points; pageIndex is 0-based.

Bookmarks / outline free

Build a navigable document outline. A Bookmark has a title, a target page and an optional top; nest children with .child(_:). A document with bookmarks opens with the outline pane shown.

Bookmark(title:page:top:)   .child(_ bookmark: Bookmark)   addBookmark(_:)
swift
let f = try doc.addFont(path: "Roboto-Regular.ttf")
for _ in 0..<3 { try doc.addPage() }
try doc.addBookmark(
    Bookmark(title: "Chapter 1", page: 0, top: 820)
        .child(Bookmark(title: "Section 1.1", page: 1))
        .child(Bookmark(title: "Section 1.2", page: 2)))
try doc.addBookmark(Bookmark(title: "Chapter 2", page: 2))
try doc.save(to: "outline.pdf")

Metadata

setInfo(_ info: DocumentInfo)

Sets the document information dictionary (and, for PDF/A, the matching XMP). Every field of DocumentInfo is optional.

swift
try doc.setInfo(DocumentInfo(
    title: "Q3 Report", author: "Acme Inc.",
    subject: "Quarterly results", keywords: "finance, q3"))

Manipulation: load an existing PDF

EditableDoc parses an existing document (classic & xref streams, object streams, all standard filters, RC4/AES decryption) into an editable model. Pages are a flat list; the page tree is rebuilt on output.

EditableDoc(loading: [UInt8])   EditableDoc(loading: [UInt8], password: String)
swift
let bytes = [UInt8](try Data(contentsOf: URL(fileURLWithPath: "in.pdf")))
let ed = try EditableDoc(loading: bytes)
print(ed.pageCount)

// encrypted input:
let secured = try EditableDoc(loading: encryptedBytes, password: "user-or-owner-pw")
try secured.save(to: "plain.pdf")
Corrupt or truncated input. A badly damaged file (truncated mid-stream, for example) may still load via the recovery scan but recover zero pages, and load does not throw in that case. Serializing a zero-page document throws PdfError ("document has no pages") instead of writing an invalid file, but check pageCount > 0 after loading untrusted input before relying on it.

Pages: merge, split, reorder, rotate

MethodDescription
merge(_:)Append all pages of another EditableDoc (objects renumbered & remapped).
rotatePage(_:degrees:)Rotate one page (90 / 180 / 270).
deletePage(_:)Remove a page.
reorderPages(_:)Reorder with a full permutation array of indices.
extractPages(_:) -> EditableDocNew document containing just those pages.
pageCountCurrent page count.
swift
let a = try EditableDoc(loading: try read("a.pdf"))
let b = try EditableDoc(loading: try read("b.pdf"))
try a.merge(b)                  // a now has a's pages followed by b's
try a.rotatePage(0, degrees: 90)
try a.reorderPages([2, 1, 0])
try a.save(to: "merged.pdf")
Page indices are 0-based. An out-of-range index to rotate/delete is silently ignored, and extract skips out-of-range indices. reorderPages requires a true permutation of every page index (each used exactly once); an invalid argument — wrong length, a repeated index, or out-of-range — is rejected and leaves the page order unchanged — the call is a silent no-op that raises no error, so an invalid reorder cannot be detected from a return value.

Metadata, overlay & form fill

MethodDescription
setInfo(key:value:)Set one info entry (e.g. "Title").
getInfo(key:) -> StringRead an info entry.
setXMP(_:)Replace the XMP metadata stream.
overlayPage(_:content:)Overlay a content-stream fragment onto a page (stamps/watermarks).
fillTextField(name:value:) -> BoolFill an AcroForm text field; returns whether it was found.
swift
let ed = try EditableDoc(loading: try read("form.pdf"))
try ed.setInfo(key: "Title", value: "Filled form")
let found = try ed.fillTextField(name: "applicant.name", value: "Jane Doe")
print("filled:", found, "| title:", try ed.getInfo(key: "Title"))
try ed.save(to: "filled.pdf")

Form fill & flatten free

Fill the fields of an existing AcroForm and (optionally) flatten them: filling generates a fresh appearance stream (no NeedAppearances), and flattening bakes every widget's appearance into the page content and removes the interactive form entirely.

MethodDescription
fieldNames() -> [String]Fully-qualified names of every terminal field.
fillTextField(name:value:) -> BoolSet a text (or text-style choice) field; returns whether it matched.
setCheckbox(name:checked:) -> BoolCheck/uncheck a checkbox.
setRadio(name:exportValue:) -> BoolSelect a radio button by its export value.
setChoice(name:value:) -> BoolSet a dropdown / list-box value.
flattenForms()Bake all fields into static content and drop the /AcroForm.
swift
let ed = try EditableDoc(loading: try read("form.pdf"))
print(try ed.fieldNames())              // ["applicant.name", "agree", "plan", ...]
_ = try ed.fillTextField(name: "applicant.name", value: "Jane Doe")
_ = try ed.setCheckbox(name: "agree", checked: true)
_ = try ed.setRadio(name: "billing", exportValue: "annual")
_ = try ed.setChoice(name: "plan", value: "Pro")
try ed.flattenForms()                   // optional: make it non-editable
try ed.save(to: "filled.pdf")

Watermarks free

Stamp a diagonal text watermark or a centered image watermark across every page, drawn semi-transparently over the existing content. Text uses the standard Helvetica font, so keep it to WinAnsi (Latin-1) for stamps like "CONFIDENTIAL".

watermarkText(_:size:color:opacity:rotationDeg:)
watermarkImageFile(path:width:height:opacity:)
swift
let ed = try EditableDoc(loading: try read("report.pdf"))
try ed.watermarkText("CONFIDENTIAL", opacity: 0.25, rotationDeg: 45)
try ed.save(to: "stamped.pdf")

Redaction licensed

True redaction: the text and graphics whose origin falls inside a rectangle are removed from the content stream (not just covered), so the data is gone from the file and is no longer extractable. Opaque black boxes are then painted over the regions.

redact(_ index: Int, rects: [(Double, Double, Double, Double)]) -> Bool
swift
let ed = try EditableDoc(loading: try read("statement.pdf"))
// rects = array of (x0, y0, x1, y1) tuples on that page
let ok = try ed.redact(0, rects: [(60, 590, 400, 620), (60, 540, 400, 570)])
try ed.save(to: "redacted.pdf")     // throws without a license granting redaction
Content under a rect is deleted before the file is written, so Pdf.extractText on the output no longer returns it.

Convert to PDF/A licensed

Convert an existing PDF to archival PDF/A (a basic profile: A-1b, A-2b or A-3b). An sRGB output intent, PDF/A XMP metadata (synced with /Info) and a document /ID are added. Fails if any font is not embedded (PDF/A requires every font embedded) or a level-A profile is requested.

convertToPdfa(_ level: PdfaLevel = .a2b)
swift
let ed = try EditableDoc(loading: try read("in.pdf"))
try ed.convertToPdfa(.a2b)          // throws if fonts aren't embedded
try ed.save(to: "archival.pdf")     // veraPDF: PDF/A-2b compliant

Optimize & compact

MethodDescription
optimize()Drop unreferenced objects, Flate-compress uncompressed streams, dedupe identical objects.
compact(_:)Pack objects into object streams + emit a cross-reference stream.
swift
let ed = try EditableDoc(loading: try read("big.pdf"))
try ed.optimize().compact(true)
try ed.save(to: "small.pdf")

Encryption licensed

Apply standard-handler encryption at output. AES-256 (V5/R6) uses OS-CSPRNG keys/IVs.

encrypt(method:user:owner:readOnly:)
swift
let ed = try EditableDoc(loading: try read("in.pdf"))
try ed.encrypt(method: .aes256, user: "", owner: "owner-secret", readOnly: true)
try ed.save(to: "secured.pdf")     // throws without an Encryption license

See the Encryption enum for RC4 / AES-128 / AES-256.

Passwords protect, permissions only advise. A non-empty user password is real cryptographic protection: opening with the wrong password is rejected (cross-checked against qpdf for all three ciphers). The read-only permission flags, by contrast, are advisory: they are enforced only by the viewer, and a file with an empty user password opens with no prompt, so any tool can strip the restrictions. Treat read-only as a hint to well-behaved viewers, not as an access control.

Output & incremental update

MethodDescription
toBytes() -> [UInt8]Serialize the manipulated document.
save(to:)Serialize to a file.
toBytesIncremental(over:) -> [UInt8]Append only changes to the original bytes (signature-safe, non-destructive).
swift
let original = try read("in.pdf")
let ed = try EditableDoc(loading: original)
try ed.setInfo(key: "Subject", value: "reviewed")
let incremental = try ed.toBytesIncremental(over: original)   // original bytes preserved verbatim

Digital signatures licensed

Sign a PDF with a PKCS#7 detached signature via an incremental update (the original bytes are preserved). Keys and certificates are passed as DER [UInt8]. pades: true switches to PAdES-B-B.

Pdf.sign(pdf:keyDER:certDER:options:) -> [UInt8]
swift
let pdf  = try read("contract.pdf")
let key  = try read("signer.pk8")    // PKCS#8 private key (DER)
let cert = try read("signer.der")    // X.509 certificate (DER)

let signed = try Pdf.sign(pdf: pdf, keyDER: key, certDER: cert,
    options: SignOptions(reason: "Approved", location: "New York",
                         name: "Jane Doe", pades: true))
// Verify in a shell: pdfsig contract.signed.pdf  →  "Signature is Valid."

Timestamp & DSS (PAdES LTV) licensed

Build long-term-validation signatures offline. addDss appends a Document Security Store (/DSS with certs/CRLs, PAdES-B-LT); timestamp appends an RFC 3161 document timestamp (/DocTimeStamp, PAdES-B-LTA).

Pdf.addDss(pdf:certs:crls:) -> [UInt8]
Pdf.timestamp(pdf:tsaKeyDER:tsaCertDER:date:) -> [UInt8]
swift
// B-LT: embed validation material (caller supplies DER certs/CRLs)
let lt = try Pdf.addDss(pdf: signed, certs: [cert], crls: [crl])

// B-LTA: add a document timestamp signed by a TSA key/cert
let lta = try Pdf.timestamp(pdf: lt, tsaKeyDER: tsaKey, tsaCertDER: tsaCert)

Validate signatures licensed

Validate every signature in a PDF: each report recomputes the /ByteRange digest, parses the CMS, and checks that the cryptographic signature is valid, that the messageDigest matches the covered bytes, and whether the signature covers the whole document.

Pdf.verifySignatures(_ data: [UInt8]) -> [SignatureReport]

Each SignatureReport has fieldName, subFilter, signer, coversWholeDocument, digestValid, signatureValid, isValid and byteRange. Note that fieldName and signer are optional (String?) and nil when absent. An empty array means the document is unsigned. Signature validation is a licensed feature: this call requires an active license (signatures) even when the document is unsigned — it is not available on the free tier.

swift
let data = try read("contract.signed.pdf")
for sig in try Pdf.verifySignatures(data) {
    print(sig.signer ?? "?", "valid:", sig.isValid,
          "covers whole doc:", sig.coversWholeDocument)
}

Text & image extraction

Extract a document's text, mapping shown glyph codes back to Unicode through each font's ToUnicode map, with space/line inference. Raster images can be pulled out too: JPEGs are written verbatim as .jpg, everything else as .png. The output directory is created automatically if it does not already exist.

Pdf.extractText(_ pdf: [UInt8]) -> String free
Pdf.extractImagesToDir(_ data: [UInt8], _ dir: String) -> Int free
swift
let data = try read("report.pdf")
print(try Pdf.extractText(data))

let n = try Pdf.extractImagesToDir(data, "out_images/")   // returns how many were written
print("wrote \(n) image(s)")

Render a page to an image licensed

Rasterize a page to a PNG image. A native Rust renderer (built on tiny-skia, with no headless browser) interprets the page content stream, painting real glyph outlines, vector graphics, images, color and transparency. Page rendering is a Pro feature; page_count is free.

Pdf.renderPageToPng(_ pdf: [UInt8], page: Int = 0, dpi: Double = 150.0) throws → [UInt8] licensed
Pdf.pageCount(_ pdf: [UInt8]) throws → Int free
swift
let data = [UInt8](try Data(contentsOf: URL(fileURLWithPath: "report.pdf")))
print("\(try Pdf.pageCount(data)) page(s)")
let png = try Pdf.renderPageToPng(data, page: 0, dpi: 150.0)
try Data(png).write(to: URL(fileURLWithPath: "page1.png"))

Enums

PdfaLevel

ValueLevel
.a1bPDF/A-1b (basic, PDF 1.4)
.a2bPDF/A-2b (basic): default of pdfa()
.a2aPDF/A-2a (accessible: pair with tagged())
.a3bPDF/A-3b (basic, allows attachments)
.a3aPDF/A-3a (accessible + attachments)
.a4PDF/A-4 (ISO 19005-4, based on PDF 2.0)
.a4ePDF/A-4e (engineering)
.a4fPDF/A-4f (requires at least one embedded file)

Align

ValueMeaning
.leftLeft-aligned (default)
.rightRight-aligned
.centerCentered
.justifyJustified (space distributed between words)

AFRelationship

ValueMeaning
.sourceSource data for the document (e.g. the invoice XML)
.dataData used to derive the visual content
.alternativeAlternative representation
.supplementSupplementary material
.unspecifiedUnspecified relationship

Encryption

ValueCipher
.rc4RC4-128 (legacy)
.aes128AES-128
.aes256AES-256 (V5/R6): recommended

FacturxProfile

ValueConformance level
.minimumMinimal header data only
.basicWLBasic, without line items
.basicBasic, with line items
.en16931EN 16931 (Comfort): the interoperable core, default
.extendedEN 16931 plus extensions

Error handling

Every failing native call throws PdfError, carrying the status (a PdfStatus) and the library's last-error message. License failures (missing/expired/forged token, or a feature the token doesn't grant) surface here too. Token activation failures carry the dedicated license status code (12); a gated build, sign or encrypt call instead reports that operation’s own status (for example Serialize = 4 or Sign = 10) with the same “requires a valid license” message.

swift
do {
    try doc.pdfa().setInfo(DocumentInfo(title: "x"))
    try doc.addPage()
    try doc.save(to: "out.pdf")
} catch let e as PdfError {
    print("failed:", e.message, "(status \(e.status))")   // e.g. .license
}

Utilities

MemberDescription
Pdf.versionNative library version string.
Pdf.activateLicense(_:)Activate a license token (throws on invalid/expired).
Looking for another language? The same API exists in Python, C#, Go, PHP, Ruby, Node and Delphi: browse all docs. They share one core, so behavior is identical.