# onepdf Go docs, all pages (onepdf-go 1.0.1) Every page of https://recursiveai.org/onepdf/go/docs/ as markdown, getting started first. Index: https://recursiveai.org/onepdf/go/llms.txt # Getting started with onepdf for Go Install onepdf for Go, lay out a PDF, extract its text and words, split and merge it, redact a word, sign and verify it, and convert it to PDF/A. onepdf for Go reads, repairs and decrypts PDFs, extracts their text, edits, signs and redacts them, converts them to PDF/A and PDF/UA, and lays out new ones, in pure Go with no cgo. It never runs document scripts and never touches the network. Every sample on this page was compiled and run with Go 1.26.8 against `recursiveai.org/go/onepdf` v1.0.1 and `recursiveai.org/go/onepdf/fonts` v1.0.1 from the Go module proxy; the output under each one is what it printed, and each PDF it wrote was checked with Poppler (`pdfinfo`, `pdftotext`, `pdfsig`). ## Install onepdf needs Go 1.24 or newer. ```sh mkdir pdf-start && cd pdf-start go mod init example.com/pdf-start go get recursiveai.org/go/onepdf@v1.0.1 recursiveai.org/go/onepdf/fonts@v1.0.1 ``` `recursiveai.org/go/onepdf` is the library. It has no third-party dependencies: it needs only our `recursiveai.org/go/onefont` module, which uses only the Go standard library, and `go get` adds it. `recursiveai.org/go/onepdf/fonts` is a separate module with substitute fonts (Liberation, Noto Sans Math and Symbols, under the SIL Open Font License 1.1), for laying out text without a font file of your own and for drawing fonts a PDF does not embed. onepdf is MIT or Apache-2.0, at your choice. Each sample is a complete `main.go` in its own folder (`go run ./write`, `go run ./extract`, …), and every sample after the first reads the `letter.pdf` the first one writes. ## Lay out a PDF The `layout` package builds a document in code and writes a tagged PDF. `fonts.LayoutFonts()` gives it the Liberation faces, so no font file is needed. ```go package main import ( "log" "os" "recursiveai.org/go/onepdf/fonts" "recursiveai.org/go/onepdf/layout" ) // heading is a tagged heading in bold. func heading(level int, s string, size float64) layout.Element { p := layout.NewParagraph(s) p.Style = layout.TextStyle{Size: size, Weight: 700} return layout.Heading{Level: level, Child: &layout.TextBlock{Paragraph: p}} } func main() { doc := &layout.Document{ Fonts: fonts.LayoutFonts(), // Liberation Sans, Serif and Mono DefaultStyle: layout.TextStyle{Size: 12}, Sections: []*layout.Section{{ Size: layout.A4, Margin: layout.All(layout.Mm(20)), Content: &layout.Column{Items: []layout.Element{ heading(1, "Letter", 20), layout.Spacer{H: 12}, layout.Text("Account 1234 is secret."), layout.PageBreak{}, heading(2, "Terms", 16), layout.Spacer{H: 12}, layout.Text("Payment is due in 30 days."), }}, }}, } f, err := os.Create("letter.pdf") if err != nil { log.Fatal(err) } defer f.Close() if _, err := doc.WritePDF(f, layout.WithTitle("Letter"), layout.WithLanguage("en")); err != nil { log.Fatal(err) } } ``` It prints nothing and writes `letter.pdf`. `pdfinfo letter.pdf` reports `Title: Letter`, `Tagged: yes`, `Pages: 2`, `Page size: 595.276 x 841.89 pts (A4)` and `PDF version: 1.7`. ## Extract text `text.Plain` returns the text of every page in reading order. `onepdf.OpenBytes` opens a byte slice and `onepdf.Open` an `io.ReaderAt`. ```go package main import ( "fmt" "log" "recursiveai.org/go/onepdf" "recursiveai.org/go/onepdf/text" ) func main() { doc, err := onepdf.OpenFile("letter.pdf") if err != nil { log.Fatal(err) } // Reading order; text.Extract gives words, lines and blocks. s, err := text.Plain(doc) if err != nil { log.Fatal(err) } fmt.Println(s) } ``` ```text Letter Account 1234 is secret. Terms Payment is due in 30 days. ``` ## Words with positions `text.Extract` returns each page as blocks, lines and words, each with its bounds in PDF points from the bottom-left corner of the page. ```go package main import ( "fmt" "log" "recursiveai.org/go/onepdf" "recursiveai.org/go/onepdf/text" ) func main() { doc, err := onepdf.OpenFile("letter.pdf") if err != nil { log.Fatal(err) } pages, err := text.Extract(doc) if err != nil { log.Fatal(err) } for i, p := range pages { for w := range p.Words() { b := w.Bounds fmt.Printf("page %d %-9s x %6.1f y %6.1f\n", i+1, w.Text, b.X0, b.Y0) } } } ``` ```text page 1 Letter x 56.7 y 762.3 page 1 Account x 56.7 y 735.4 page 1 1234 x 103.4 y 735.4 page 1 is x 133.4 y 735.4 page 1 secret. x 145.4 y 735.4 page 2 Terms x 56.7 y 766.8 page 2 Payment x 56.7 y 740.2 page 2 is x 107.4 y 740.2 page 2 due x 119.4 y 740.2 page 2 in x 142.7 y 740.2 page 2 30 x 155.4 y 740.2 page 2 days. x 172.1 y 740.2 ``` ## Split and merge `onepdf.Split` makes one document per page range and `onepdf.Merge` joins documents, keeping outlines, links and form fields. ```go package main import ( "fmt" "log" "recursiveai.org/go/onepdf" ) func main() { doc, err := onepdf.OpenFile("letter.pdf") if err != nil { log.Fatal(err) } // One document per page range: Start is zero-based. parts, err := onepdf.Split(doc, onepdf.PageRange{Start: 0, Count: 1}, onepdf.PageRange{Start: 1, Count: 1}) if err != nil { log.Fatal(err) } for i, p := range parts { name := fmt.Sprintf("part-%d.pdf", i+1) if err := p.SaveFile(name); err != nil { log.Fatal(err) } fmt.Println(name, p.PageCount(), "page") } // Back together, second part first. merged, err := onepdf.Merge([]*onepdf.Document{parts[1], parts[0]}) if err != nil { log.Fatal(err) } if err := merged.SetInfo("Title", "Merged"); err != nil { log.Fatal(err) } if err := merged.SaveFile("merged.pdf"); err != nil { log.Fatal(err) } fmt.Println("merged.pdf", merged.PageCount(), "pages") } ``` ```text part-1.pdf 1 page part-2.pdf 1 page merged.pdf 2 pages ``` `pdftotext merged.pdf` reads “Terms” before “Letter”. ## Redact a word `redact.Apply` removes the text, vector paths and image pixels under each area for good, not just covers them. A document must be opened with `onepdf.WithEditing()` to change it. ```go package main import ( "fmt" "log" "recursiveai.org/go/onepdf" "recursiveai.org/go/onepdf/redact" "recursiveai.org/go/onepdf/text" ) func main() { doc, err := onepdf.OpenFile("letter.pdf", onepdf.WithEditing()) if err != nil { log.Fatal(err) } // Find the account number and redact the area under it. pages, err := text.Extract(doc) if err != nil { log.Fatal(err) } var regions []redact.Region for i, p := range pages { for w := range p.Words() { if w.Text == "1234" { regions = append(regions, redact.Region{Page: i, Rect: w.Bounds}) } } } res, err := redact.Apply(doc, regions) if err != nil { log.Fatal(err) } if err := doc.SaveFile("redacted.pdf"); err != nil { log.Fatal(err) } fmt.Println("glyphs removed:", res.GlyphsRemoved) } ``` ```text glyphs removed: 4 ``` `pdftotext redacted.pdf` gives “Account” and “is secret.” with nothing between them. ## Sign and verify `sign.Sign` writes a PAdES signature with your certificate and its RSA or ECDSA key. `sign.Verify` checks it against the trust anchors you pass and never downloads anything. ```go package main import ( "crypto/ecdsa" "crypto/elliptic" "crypto/rand" "crypto/x509" "crypto/x509/pkix" "fmt" "log" "math/big" "os" "time" "recursiveai.org/go/onepdf" "recursiveai.org/go/onepdf/sign" ) func main() { // A self-signed certificate stands in for your own. key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) if err != nil { log.Fatal(err) } tmpl := &x509.Certificate{ SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "Ada Lovelace"}, NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(24 * time.Hour), KeyUsage: x509.KeyUsageDigitalSignature, } der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key) if err != nil { log.Fatal(err) } cert, _ := x509.ParseCertificate(der) cred, err := sign.NewCredential(cert, key) if err != nil { log.Fatal(err) } doc, err := onepdf.OpenFile("letter.pdf", onepdf.WithEditing()) if err != nil { log.Fatal(err) } out, err := os.Create("signed.pdf") if err != nil { log.Fatal(err) } if _, err := sign.Sign(doc, out, cred, sign.WithReason("I approve")); err != nil { log.Fatal(err) } out.Close() signed, err := onepdf.OpenFile("signed.pdf") if err != nil { log.Fatal(err) } report, err := sign.Verify(signed, sign.WithTrustAnchors(cert)) if err != nil { log.Fatal(err) } fmt.Println(report.Summary()) fmt.Println("valid:", report.Signatures[0].IsValid) } ``` ```text 1 signature: 1 valid, 0 not valid valid: true ``` `pdfsig signed.pdf` reports `Signature Validation: Signature is Valid.` ## Convert to PDF/A `pdfa.ConvertFile` writes a PDF/A-2b copy and lists what it changed. A file that cannot be converted fails with every reason. ```go package main import ( "context" "fmt" "log" "recursiveai.org/go/onepdf/pdfa" ) func main() { res, err := pdfa.ConvertFile(context.Background(), "letter-pdfa.pdf", "letter.pdf") if err != nil { log.Fatal(err) // a file that cannot be converted fails with every reason } fmt.Println(res.Profile) for _, c := range res.Changes { fmt.Println("-", c.Description) } } ``` ```text PDF/A-2b - an output intent with a generated RGB profile was added - the XMP metadata was written from the information dictionary ``` ## Next - [Overview](https://recursiveai.org/onepdf/go/docs/overview/): every package, the README examples, how fonts are found, and performance. - [Substitute fonts](https://recursiveai.org/onepdf/go/docs/fonts/): the fonts module. - [API reference on pkg.go.dev](https://pkg.go.dev/recursiveai.org/go/onepdf). # onepdf-go A pure-Go PDF library: no cgo, no bindings, no WebAssembly. It reads, repairs and decrypts PDFs, reads their structure and text, interprets pages into a drawing device, and writes, edits, signs, redacts, tags, converts to PDF/A and PDF/UA, and lays out documents. Files are treated as untrusted: the library is written not to panic or hang on any input, and what it allocates is bounded by limits you can change. It never runs document code and never touches the network. ``` go get recursiveai.org/go/onepdf ``` Go 1.24 or later. ## Packages | Import path | What it is for | |---|---| | `recursiveai.org/go/onepdf` | Open, repair and decrypt; objects, pages, metadata, outlines, forms, annotations; save, merge, split and page edits; content creation. | | `.../onepdf/device` | The drawing device the interpreter drives, with the geometry, path, colour and glyph types it passes. | | `.../onepdf/device/displaylist` | Records, replays and serialises the calls a device receives. | | `.../onepdf/text` | Text extraction: glyphs, words, lines and blocks in reading order, plain text, the shared JSON form. | | `.../onepdf/tag` | Tagging an untagged file, and reading and editing structure trees. | | `.../onepdf/pdfa` | PDF/A checks, preparation, conformance saves and conversion of existing files. | | `.../onepdf/pdfua` | PDF/UA checks, preparation and conformance saves. | | `.../onepdf/redact` | Removing content for good. | | `.../onepdf/sign` | Verifying and writing digital signatures, timestamps and two-phase signing. | | `.../onepdf/layout` | Laying out documents in code: text, boxes, tables, lists, pages, headers and footers, tagged PDF output. | | `.../onepdf/layout/hyphen` | Hyphenation patterns for the layout engine. | | `.../onepdf/fonts` | A nested module with substitute fonts (Liberation, Noto); see *Fonts*. | Each package has two layers: a short happy path (open, extract, fill, save) built on a low layer you can use directly (objects, the content-stream interpreter and its device, the writer). ## Examples The snippets are the examples in `readme_example_test.go`, which `go test` runs. `doc` is an `*onepdf.Document` from `onepdf.OpenFile(path)` or `onepdf.OpenBytes(data)`; add `onepdf.WithEditing()` to change it. ### Extract text ```go doc, err := onepdf.OpenFile("letter.pdf") if err != nil { log.Fatal(err) } s, err := text.Plain(doc) // reading order; text.Extract gives words, lines and blocks ``` ### Fill a form and save ```go doc, _ := onepdf.OpenFile("form.pdf", onepdf.WithEditing()) err := doc.Form().Fill(map[string]any{"name": "Ada", "agree": true}) err = doc.SaveFile("filled.pdf") ``` ### Sign ```go cred, err := sign.NewCredential(cert, key) // an *x509.Certificate and its RSA or ECDSA key doc, _ := onepdf.OpenFile("in.pdf", onepdf.WithEditing()) res, err := sign.Sign(doc, out, cred, sign.WithReason("I approve")) report, err := sign.Verify(signedDoc, sign.WithTrustAnchors(root)) // report.Signatures[i].IsValid ``` ### Convert to PDF/A ```go res, err := pdfa.Convert(ctx, dst, src, size) // PDF/A-2b; res.Changes lists what was repaired ``` ### Tag an untagged file ```go doc, _ := onepdf.OpenFile("in.pdf", onepdf.WithEditing()) pages, _ := text.Extract(doc, text.WithRetainGlyphs(true)) _, err := tag.Tag(doc, pages, func(b tag.BlockInfo) tag.BlockRole { if b.BlockIndex == 0 { return tag.BlockHeading(1) // you choose every role } return tag.BlockParagraph() }, tag.WithLanguage("en")) ``` ### Redact ```go doc, _ := onepdf.OpenFile("in.pdf", onepdf.WithEditing()) res, err := redact.Apply(doc, []redact.Region{{Page: 0, Rect: area}}) // glyphs, paths and pixels under area are gone err = doc.Save(out) ``` ### Lay out a document ```go fonts := layout.NewFonts() fonts.Add(fontBytes, layout.FontSpec{Family: "Mono"}) doc := &layout.Document{ Fonts: fonts, DefaultStyle: layout.TextStyle{Size: 12}, Sections: []*layout.Section{{ Size: layout.A4, Margin: layout.All(layout.Mm(20)), Content: layout.Text("Hello from layout."), }}, } _, err := doc.WritePDF(out, layout.WithTitle("Hello"), layout.WithLanguage("en")) ``` The PDF is tagged by default. `layout.WithSaveOptions` takes the save options of the core package, so a PDF/A or PDF/UA file is `layout.WithSaveOptions(pdfa.WithPDFA())` or `layout.WithSaveOptions(pdfua.WithPDFUA())`. ## Fonts A font the file does not embed is drawn, and a stand-in is embedded on request, from a *font provider*. There are three sources, asked in this order: 1. the document's own provider (`doc.SetFontProvider`); 2. the providers registered for the process (`onepdf.RegisterFontProvider`, or `fonts.Register()` from the `recursiveai.org/go/onepdf/fonts` module, which carries Liberation, Noto Sans Math and Noto Sans Symbols); 3. the fonts installed on the machine, **only if you ask**: `onepdf.OpenFile(path, onepdf.WithSystemFonts())`. **Installed fonts are off by default**, so the same file gives the same output on every machine. `WithSystemFonts()` turns them on for one document (`doc.SystemFonts()` reports it); the library then reads the platform's font directories and the ones listed in `ONEPDF_FONT_DIRS`, and nothing else. `onepdf.SystemFontProvider(dirs...)` gives the same lookup as a provider you can register or hand to one call. ## Performance Each row times the same workload on the same file, after checking that every library produced the same answer (page counts, extracted text, a reopened output). Where a pure-Go library can do the row, onepdf is compared with the fastest one; where none can, with the C# library of the same family (RecursiveAI.OnePdf 1.26.0). Ratios below 1 mean onepdf is faster. Time is the median of six runs; allocations are per operation. | Row | onepdf | fastest pure-Go competitor | onepdf / Go | C# 1.26.0 | onepdf / C# | allocs (onepdf / competitor) | |---|---:|---|---:|---:|---:|---:| | Open, 1 page | 2.8 µs | ledongthuc/pdf 6.0 µs | 0.47 | 4.7 µs | 0.60 | 37 / 123 | | Open, 1,000 pages | 268.5 µs | ledongthuc/pdf 466.2 µs | 0.58 | 1.41 ms | 0.19 | 53 / 11,881 | | Open, needs repair | 13.4 µs | pdfcpu 102.2 µs | 0.13 | | | 201 / 853 | | Read Info, XMP and page count, 300 pages | 90.4 µs | pdfcpu 8.57 ms | 0.01 | 397.3 µs | 0.23 | 324 / 78,356 | | Read every object, 300 pages | 5.27 ms | pdfcpu 11.30 ms | 0.47 | | | 15,416 / 52,892 | | Read every object, 1,000 pages | 8.12 ms | pdfcpu 20.80 ms | 0.39 | | | 50,686 / 167,419 | | Interpret, 5,000-path page | 3.03 ms | none | | 3.68 ms | 0.82 | 129 | | Interpret, dense text page | 596.8 µs | none | | 1.11 ms | 0.54 | 750 | | Save, 300 pages | 1.31 ms | pdfcpu 13.77 ms | 0.10 | | | 16,715 / 71,724 | | Incremental save | 22.0 µs | none | | | | 107 | | Encrypt (AES-256 save) | 4.07 ms | pdfcpu 7.30 ms | 0.56 | | | 19,443 / 69,713 | | Merge 100 documents | 5.74 ms | pdfcpu 12.09 ms | 0.47 | | | 75,442 / 105,901 | | Split, 300 pages | 16.38 ms | pdfcpu 65.15 ms | 0.25 | | | 76,729 / 345,948 | | Rotate every page | 1.59 ms | pdfcpu 10.50 ms | 0.15 | | | 17,685 / 193,652 | | Import 100 pages | 1.18 ms | pdfcpu 9.07 ms | 0.13 | | | 14,769 / 99,195 | | Fill 100 form fields | 1.24 ms | pdfcpu 5.18 ms | 0.24 | | | 12,508 / 40,404 | | Flatten 100 form fields | 1.34 ms | none | | | | 13,078 | | Sign | 1.10 ms | digitorus/pdfsign 1.49 ms | 0.74 | | | 782 / 515 | | Verify a signature | 260.8 µs | digitorus/pdfsign 382.9 µs | 0.68 | 1.08 ms | 0.24 | 374 / 716 | | Convert to PDF/A | 622.5 µs | none | | 1.01 ms | 0.62 | 2,077 | No pure-Go library appends an incremental update to an edited document, flattens forms, converts to PDF/A, decrypts AES-256 for extraction, or returns words with bounds, so those rows are timed alone or against C#. Competitors that fail a row's check are listed as not applicable in the benchmark module's `results/table.md` rather than timed. ### Text extraction | Row | onepdf | fastest pure-Go competitor | onepdf / Go | C# 1.26.0 | onepdf / C# | allocs (onepdf / competitor) | |---|---:|---|---:|---:|---:|---:| | Plain text, content order, 300 pages | 72.81 ms | dslipak/pdf 132.16 ms | 0.55 | | | 52,905 / 3,077,915 | | Plain text, reading order, 300 pages | 164.41 ms | none | | 178.87 ms | 0.92 | 156,208 | | Words with positions, 300 pages | 155.52 ms | none | | 233.42 ms | 0.67 | 153,772 | | Plain text, reading order, 300 pages, 4 workers | 45.38 ms | none | | 53.18 ms | 0.85 | 156,599 | | Plain text, 100 CJK pages (Type 0 font, predefined CMap) | 64.49 ms | none | | | | 606,709 | | Plain text, AES-256, 300 pages | 153.52 ms | none | | | | 158,312 | The pure-Go competitors (ledongthuc/pdf, dslipak/pdf) return text in content order with no reading-order analysis, so the content-order row is the like-for-like comparison with them; on the reading-order rows onepdf does more work than they do and is compared with C#. Neither competitor extracts the CJK file (ledongthuc fails, dslipak returns the wrong characters) or opens the AES-256 file. C# is the floor for words and the parallel row; its words time varied between 186 and 237 ms across runs on the same machine, so that ratio is the least stable one here. ### Layout The same documents laid out by onepdf's layout engine and by go-pdf/fpdf, signintech/gopdf and johnfercher/maroto: an invoice, a 50-page report (tables, headers, footers), a 10,000-row table, a 500-page justified book, and 32 invoices at once. Every engine embeds the same font, Liberation Sans Regular, in regular weight only, and each render parses and embeds it. Only onepdf shapes text (ligatures, kerning, bidirectional and complex scripts) and writes a tagged structure tree; the others place glyphs by advance width and write an untagged file. The onepdf column is the default, tagged output; the last column is the same layout with tagging switched off, shown for information. | Row | onepdf (tagged) | fastest competitor | onepdf / competitor | allocs (onepdf / competitor) | onepdf, untagged | |---|---:|---|---:|---:|---:| | Invoice, 1 page | 0.84 ms | gopdf 2.00 ms | 0.42 | 2,908 / 7,783 | 0.72 ms | | Report, 50 pages | 14.15 ms | fpdf 20.48 ms | 0.69 | 74,239 / 193,766 | 12.11 ms | | Table, 10,000 rows | 55.41 ms | fpdf 63.76 ms | 0.87 | 360,965 / 654,850 | 39.37 ms | | Book, 500 pages | 68.76 ms | maroto 158.80 ms | 0.43 | 164,807 / 2,585,708 | 67.56 ms | | 32 invoices at once | 7.42 ms | gopdf 15.37 ms | 0.48 | 93,492 / 249,351 | 7.16 ms | Every layout row is ahead of the fastest competitor with tagging on. The table is the closest, at 0.87 of fpdf's time; untagged onepdf takes 0.59 of fpdf's time on the report and 0.62 on the table. Tagging writes the structure tree, marked-content sequences and a parent tree, which is where the difference between the two onepdf columns goes. **Method.** AMD Ryzen 9 7950X3D (16 cores, 32 threads), Linux, Go 1.26.8, .NET 10, an otherwise idle machine (each group started at a load average below 2.0), `GOMAXPROCS=8`, `-benchtime=1s -count=6`, reporting medians. The C# library runs on the same files with 8 processors. The inputs are generated from fixed seeds; the harness, the competitors' versions and how to rerun it are in [`bench/README.md`](https://github.com/recursive-ai-oss/onepdf-go/blob/3d3418a2841e1b3884bba991436fb426c24a560e/bench/README.md). Licensed under MIT OR Apache-2.0, (c) Recursive AI, LLC. # onepdf/fonts Substitute fonts for [onepdf](https://github.com/recursive-ai-oss/onepdf-go/tree/3d3418a2841e1b3884bba991436fb426c24a560e/): Liberation Sans, Serif and Mono (the metric-compatible faces for Helvetica/Arial, Times and Courier), and Noto Sans Math, Noto Sans Symbols and Noto Sans Symbols 2 for Symbol and ZapfDingbats. They are the upstream releases, byte for byte, under the SIL Open Font License 1.1 (`licenses/`, `SOURCE.md`). The root module is `MIT OR Apache-2.0` and does not include them, so a program that never imports this module carries none of them. ```go import "recursiveai.org/go/onepdf/fonts" fonts.Register() // once, at startup: documents without an embedded font now draw with these faces doc, _ := onepdf.OpenFile("in.pdf", onepdf.WithEditing()) rep, _ := doc.EmbedSubstituteFonts() // subset the faces into the document, keeping its widths ``` `fonts.Provider()` is the provider itself, for one document (`doc.SetFontProvider`) or one call. An unknown font name is drawn with the face its descriptor flags ask for (serif, fixed pitch, else sans serif); a symbolic font or a CJK collection gets none. `EmbedSubstituteFonts` embeds only fonts the package has a metric-compatible face for. The module has its own `go.mod` and is versioned separately from the root module (tags `fonts/vX.Y.Z`): `go get recursiveai.org/go/onepdf/fonts` adds it, together with the onepdf version it requires. Installed system fonts are a separate, opt-in source (`onepdf.WithSystemFonts()`); registering this package does not turn them on. # Changelog All notable changes to this project are documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [1.0.1] ### Fixed - A damaged file whose objects name their type through a reference no longer causes a panic while the document is repaired; the file opens repaired or returns an error. ## [1.0.0] First release. `recursiveai.org/go/onepdf` is a pure-Go PDF library: no cgo, no bindings, no WebAssembly, and no dependency beyond the Go standard library and onefont-go (used by `layout`). Go 1.24 or later. ### Reading - Opens a file, a byte slice or an `io.ReaderAt`; reads classic and cross-reference-stream tables, hybrid-reference files, object streams, linearized files and every incremental revision, loading objects lazily. - Repairs damaged files: rebuilds the cross-reference table by scanning, fixes wrong stream lengths, tolerates missing `endobj` and broken trailers, and records each repair as a diagnostic. Strict mode turns repairs into errors. - Decrypts the standard security handler (RC4 40 and 128 bit, AES-128, AES-256; revisions 2 to 6) with the user or owner password. - Decodes Flate, LZW, ASCIIHex, ASCII85, RunLength, CCITT Group 3 and 4, Crypt and the PNG and TIFF predictors with our own code. DCT, JPX and JBIG2 go through a decoder registry that returns raw samples; the library applies every PDF image rule (`/Decode`, Adobe CMYK, colour-key masks, `/SMask`, stencil masks) itself. - Exposes the document model: pages and boxes, metadata (Info and XMP), outlines, page labels, destinations, named destinations, annotations, optional content, embedded files, AcroForm fields and the structure tree. - Limits on object counts, nesting, decoded sizes, image samples and per-page work are checked before memory is allocated and can be changed by the caller. Errors are values that match sentinel categories with `errors.Is`. ### Interpreting pages - Interprets content streams into a `device.Device`: paths, glyph runs with outlines and Unicode, images, shadings, clips, transparency groups, soft masks, tiling patterns, Type 3 glyphs, marked content and annotation appearances. - Colour spaces including ICC, Lab, Indexed, Separation and DeviceN; functions of types 0, 2, 3 and 4; shading types 1 to 7. - Reads Type 1, CFF, TrueType, OpenType and Type 3 fonts, predefined CJK CMaps and the standard 14 font metrics. Fonts that are not embedded come from a provider you register, such as the `fonts` module. - `device/displaylist` records a page, replays it with culling, and reads and writes the shared text form. ### Text extraction - Glyphs, words, lines and blocks in reading order, from the structure tree when the file is tagged and from page geometry otherwise; plain text in reading, content and layout order; bidirectional and vertical text; the shared JSON form. - Unicode comes from `/ToUnicode`, encodings and glyph names, the font's own tables and predefined CMaps. ### Writing and editing - Saves a new file or appends an incremental update, as a classic table or with cross-reference and object streams, with AES or RC4 encryption. The same input and document ID give the same bytes. - Merges, splits, reorders, rotates, deletes and imports pages, keeping outlines, links, names, labels and form fields. - Fills, resets and flattens forms and generates missing field and annotation appearances. - Creates content: text in the standard fonts or embedded TrueType and OpenType subsets, paths, images (JPEG, PNG and raw samples), gradients, stamps and watermarks; writes whole documents as a stream. - Adds and reads markup annotations, links and file attachments. - `redact` removes text, vector paths and image regions under areas, with the annotations, form values and metadata that go with them, and fails closed when a page cannot be read completely. ### Signatures - `sign` verifies signatures against trust anchors you supply, checking the byte range, digest, CMS signature, certificate chain and key usage, timestamps, revocation data you supply, and what changed after signing. - Signs with PAdES baseline or `adbe.pkcs7.detached`, with timestamps, certification and field locks, visible appearances, document timestamps and two-phase signing for keys that live elsewhere. The signing time is the current time unless you set it. - Never downloads anything. ### PDF/A, PDF/UA and tagging - `pdfa` checks, prepares and saves PDF/A-2 and -3 (levels b and u), and converts existing files, refusing with every reason when a file cannot be converted. - `pdfua` checks, prepares and saves PDF/UA-1 and PDF/UA-2. - `tag` adds a structure tree to an untagged file from roles you supply, reads and edits existing trees, and removes tags. ### Layout - `layout` builds documents in code: styled and rich text shaped through onefont-go, boxes, rows and columns, tables with repeated headers, lists, images, headers, footers and page numbers, barcodes, SVG, links and bookmarks. Output is tagged PDF, ready for PDF/UA. - `layout/hyphen` carries hyphenation patterns for 26 languages. ### Safety - No panic and no hang on hostile input; recursion never follows input depth. Document scripts and actions are never run and the library imports no `net` or `os/exec`. A nil `context.Context` passed to any `...Context` function means `context.Background()`.