Recursive AI

onepdf-go

All onepdf Go docs

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 pathWhat it is for
recursiveai.org/go/onepdfOpen, repair and decrypt; objects, pages, metadata, outlines, forms, annotations; save, merge, split and page edits; content creation.
.../onepdf/deviceThe drawing device the interpreter drives, with the geometry, path, colour and glyph types it passes.
.../onepdf/device/displaylistRecords, replays and serialises the calls a device receives.
.../onepdf/textText extraction: glyphs, words, lines and blocks in reading order, plain text, the shared JSON form.
.../onepdf/tagTagging an untagged file, and reading and editing structure trees.
.../onepdf/pdfaPDF/A checks, preparation, conformance saves and conversion of existing files.
.../onepdf/pdfuaPDF/UA checks, preparation and conformance saves.
.../onepdf/redactRemoving content for good.
.../onepdf/signVerifying and writing digital signatures, timestamps and two-phase signing.
.../onepdf/layoutLaying out documents in code: text, boxes, tables, lists, pages, headers and footers, tagged PDF output.
.../onepdf/layout/hyphenHyphenation patterns for the layout engine.
.../onepdf/fontsA 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.

Rowonepdffastest pure-Go competitoronepdf / GoC# 1.26.0onepdf / C#allocs (onepdf / competitor)
Open, 1 page2.8 µsledongthuc/pdf 6.0 µs0.474.7 µs0.6037 / 123
Open, 1,000 pages268.5 µsledongthuc/pdf 466.2 µs0.581.41 ms0.1953 / 11,881
Open, needs repair13.4 µspdfcpu 102.2 µs0.13201 / 853
Read Info, XMP and page count, 300 pages90.4 µspdfcpu 8.57 ms0.01397.3 µs0.23324 / 78,356
Read every object, 300 pages5.27 mspdfcpu 11.30 ms0.4715,416 / 52,892
Read every object, 1,000 pages8.12 mspdfcpu 20.80 ms0.3950,686 / 167,419
Interpret, 5,000-path page3.03 msnone3.68 ms0.82129
Interpret, dense text page596.8 µsnone1.11 ms0.54750
Save, 300 pages1.31 mspdfcpu 13.77 ms0.1016,715 / 71,724
Incremental save22.0 µsnone107
Encrypt (AES-256 save)4.07 mspdfcpu 7.30 ms0.5619,443 / 69,713
Merge 100 documents5.74 mspdfcpu 12.09 ms0.4775,442 / 105,901
Split, 300 pages16.38 mspdfcpu 65.15 ms0.2576,729 / 345,948
Rotate every page1.59 mspdfcpu 10.50 ms0.1517,685 / 193,652
Import 100 pages1.18 mspdfcpu 9.07 ms0.1314,769 / 99,195
Fill 100 form fields1.24 mspdfcpu 5.18 ms0.2412,508 / 40,404
Flatten 100 form fields1.34 msnone13,078
Sign1.10 msdigitorus/pdfsign 1.49 ms0.74782 / 515
Verify a signature260.8 µsdigitorus/pdfsign 382.9 µs0.681.08 ms0.24374 / 716
Convert to PDF/A622.5 µsnone1.01 ms0.622,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

Rowonepdffastest pure-Go competitoronepdf / GoC# 1.26.0onepdf / C#allocs (onepdf / competitor)
Plain text, content order, 300 pages72.81 msdslipak/pdf 132.16 ms0.5552,905 / 3,077,915
Plain text, reading order, 300 pages164.41 msnone178.87 ms0.92156,208
Words with positions, 300 pages155.52 msnone233.42 ms0.67153,772
Plain text, reading order, 300 pages, 4 workers45.38 msnone53.18 ms0.85156,599
Plain text, 100 CJK pages (Type 0 font, predefined CMap)64.49 msnone606,709
Plain text, AES-256, 300 pages153.52 msnone158,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.

Rowonepdf (tagged)fastest competitoronepdf / competitorallocs (onepdf / competitor)onepdf, untagged
Invoice, 1 page0.84 msgopdf 2.00 ms0.422,908 / 7,7830.72 ms
Report, 50 pages14.15 msfpdf 20.48 ms0.6974,239 / 193,76612.11 ms
Table, 10,000 rows55.41 msfpdf 63.76 ms0.87360,965 / 654,85039.37 ms
Book, 500 pages68.76 msmaroto 158.80 ms0.43164,807 / 2,585,70867.56 ms
32 invoices at once7.42 msgopdf 15.37 ms0.4893,492 / 249,3517.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.

Licensed under MIT OR Apache-2.0, (c) Recursive AI, LLC.