onepdf

package module
v1.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 4, 2026 License: Apache-2.0, MIT Imports: 51 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

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
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
doc, _ := onepdf.OpenFile("form.pdf", onepdf.WithEditing())
err := doc.Form().Fill(map[string]any{"name": "Ada", "agree": true})
err = doc.SaveFile("filled.pdf")
Sign
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
res, err := pdfa.Convert(ctx, dst, src, size) // PDF/A-2b; res.Changes lists what was repaired
Tag an untagged file
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
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
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.

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

Documentation

Overview

Package onepdf reads, edits and writes PDF files.

It is pure Go with no dependencies. Open a document from a file, a byte slice or an io.ReaderAt:

doc, err := onepdf.OpenFile("report.pdf")
if err != nil { ... }
defer doc.Close()
fmt.Println(doc.Version(), doc.PageCount())

Objects

The document is a graph of objects (ISO 32000-2 7.3). Object is a closed interface over Bool, Int, Real, String, Name, Ref, *Array, *Dict and *Stream; the PDF null object is Go's nil. Dict and Array getters follow indirect references for you (Get, Int, Name, ...) and have a Raw form that returns what the file stored. Document.Object gives any object by number.

Structure

Open reads the cross-reference tables and streams, hybrid-reference files and the /Prev chain of incremental updates, and loads objects lazily. Every update is a Revision whose objects, trailer and catalog can be read as they were. Linearized files read like any other file.

Editing and saving

A document opened with WithEditing can be changed: Dict.Set and Dict.Delete, Array.Append, Insert, SetAt, RemoveAt and Clear, Stream.SetData and SetStoredBytes change objects in place, and Document.AddObject, SetObject and RemoveObject add, replace and free indirect objects. SetInfo, SetXMP, AttachFile, InsertBlankPage and RemovePage are the document-level edits built on them. An editable document keeps every object it reads in memory, and each change marks the indirect object it lives in, however deeply nested, so that nothing is lost and an incremental save knows what to write. A value that is already an indirect object is stored as its reference, a stream with no document is added as a new object, and a value of another document is refused with ErrArgument. Changes on a document opened without WithEditing, or on an object of an earlier Revision, return ErrNotEditable. Editing is for one goroutine at a time; reading stays concurrent.

Save writes a new, clean file (classic table, or cross-reference stream with object streams); SaveIncremental appends an update to the original bytes. Both take SaveOption values (WithXRefFormat, WithObjectStreams, WithCompressedStreams, WithMinimumVersion, WithDocumentID, WithEncryption and WithoutEncryption). The same document and options give the same bytes, except that encryption uses random salts and vectors. New makes an empty editable document.

Hostile input

A PDF is untrusted input. Limits bound object counts, nesting and decoded stream sizes, and are checked before memory is allocated. Errors match one of the category values ErrFormat, ErrLimit, ErrPassword, ErrEncryption, ErrSourceChanged and ErrUnsupported with errors.Is; FormatError, LimitError and PasswordError (which tells a missing password from a wrong one) carry detail for errors.As. Nothing in this package runs document code or touches the network.

Contexts

Every call that loops over pages, objects or streams has an XxxContext twin whose first parameter is a context.Context; it stops with an error wrapping the context's error. A nil context is treated as context.Background in every exported function and method of every package that takes one, so passing nil never panics.

Concurrency

Any number of goroutines may read one Document: Page, Pages, Object, Resolve, Interpret, text extraction and Save are safe together. Editing is for one goroutine at a time: the mutators (Dict.Set, Dict.Delete, the Array mutators, Stream.SetData, AddObject, SetObject, RemoveObject, SetInfo, SetXMP, the page operations, form filling, annotation and content creation) must not run while another goroutine reads or saves the same document. Builders (ContentBuilder, DocumentWriter and the pages and forms they make) belong to one goroutine each.

Example (ConvertToPDFA)
package main

import (
	"bytes"
	"context"
	"fmt"
	"log"
	"os"

	"recursiveai.org/go/onepdf/layout"
	"recursiveai.org/go/onepdf/pdfa"
)

// readmeDocument lays out a one-page letter. With untagged set, the PDF
// carries no structure tree, like most files in the wild.
func readmeDocument(untagged bool) []byte {
	data, err := os.ReadFile("layout/testdata/fonts/kit-mono-regular.ttf")
	if err != nil {
		log.Fatal(err)
	}
	fonts := layout.NewFonts()
	if _, err := fonts.Add(data, layout.FontSpec{Family: "Mono"}); err != nil {
		log.Fatal(err)
	}
	doc := &layout.Document{
		Fonts:        fonts,
		DefaultStyle: layout.TextStyle{Size: 12},
		Options:      layout.Options{Untagged: untagged},
		Sections: []*layout.Section{{
			Size:   layout.A6,
			Margin: layout.All(20),
			Content: &layout.Column{Items: []layout.Element{
				layout.Heading{Level: 1, Child: layout.Text("Letter")},
				layout.Spacer{H: 24},
				layout.Text("Account 1234 is secret."),
			}},
		}},
	}
	var buf bytes.Buffer
	if _, err := doc.WritePDF(&buf, layout.WithTitle("Letter"), layout.WithLanguage("en")); err != nil {
		log.Fatal(err)
	}
	return buf.Bytes()
}

func main() {
	src := readmeDocument(false)
	var out bytes.Buffer
	res, err := pdfa.Convert(context.Background(), &out, bytes.NewReader(src), int64(len(src)))
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(res.Profile)
}
Output:
PDF/A-2b
Example (ExtractText)
package main

import (
	"bytes"
	"fmt"
	"log"
	"os"

	"recursiveai.org/go/onepdf"
	"recursiveai.org/go/onepdf/layout"
	"recursiveai.org/go/onepdf/text"
)

// readmeDocument lays out a one-page letter. With untagged set, the PDF
// carries no structure tree, like most files in the wild.
func readmeDocument(untagged bool) []byte {
	data, err := os.ReadFile("layout/testdata/fonts/kit-mono-regular.ttf")
	if err != nil {
		log.Fatal(err)
	}
	fonts := layout.NewFonts()
	if _, err := fonts.Add(data, layout.FontSpec{Family: "Mono"}); err != nil {
		log.Fatal(err)
	}
	doc := &layout.Document{
		Fonts:        fonts,
		DefaultStyle: layout.TextStyle{Size: 12},
		Options:      layout.Options{Untagged: untagged},
		Sections: []*layout.Section{{
			Size:   layout.A6,
			Margin: layout.All(20),
			Content: &layout.Column{Items: []layout.Element{
				layout.Heading{Level: 1, Child: layout.Text("Letter")},
				layout.Spacer{H: 24},
				layout.Text("Account 1234 is secret."),
			}},
		}},
	}
	var buf bytes.Buffer
	if _, err := doc.WritePDF(&buf, layout.WithTitle("Letter"), layout.WithLanguage("en")); err != nil {
		log.Fatal(err)
	}
	return buf.Bytes()
}

func main() {
	doc, err := onepdf.OpenBytes(readmeDocument(false))
	if err != nil {
		log.Fatal(err)
	}
	s, err := text.Plain(doc)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(s)
}
Output:
Letter

Account 1234 is secret.
Example (FillForm)
doc, err := onepdf.OpenBytes([]byte(exampleFormPDF), onepdf.WithEditing())
if err != nil {
	log.Fatal(err)
}
if err := doc.Form().Fill(map[string]any{"name": "Ada", "agree": true}); err != nil {
	log.Fatal(err)
}
var out bytes.Buffer
if err := doc.Save(&out); err != nil {
	log.Fatal(err)
}
saved, _ := onepdf.OpenBytes(out.Bytes())
name, _ := saved.Form().Find("name").Value()
fmt.Println(name)
Output:
Ada
Example (Layout)
package main

import (
	"bytes"
	"fmt"
	"log"
	"os"

	"recursiveai.org/go/onepdf"
	"recursiveai.org/go/onepdf/layout"
)

func main() {
	data, err := os.ReadFile("layout/testdata/fonts/kit-mono-regular.ttf")
	if err != nil {
		log.Fatal(err)
	}
	fonts := layout.NewFonts()
	if _, err := fonts.Add(data, layout.FontSpec{Family: "Mono"}); err != nil {
		log.Fatal(err)
	}
	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."),
		}},
	}
	var out bytes.Buffer
	if _, err := doc.WritePDF(&out, layout.WithTitle("Hello"), layout.WithLanguage("en")); err != nil {
		log.Fatal(err)
	}
	pdf, _ := onepdf.OpenBytes(out.Bytes())
	fmt.Println(pdf.PageCount())
}
Output:
1
Example (Redact)
package main

import (
	"bytes"
	"fmt"
	"log"
	"os"

	"recursiveai.org/go/onepdf"
	"recursiveai.org/go/onepdf/layout"
	"recursiveai.org/go/onepdf/redact"
	"recursiveai.org/go/onepdf/text"
)

// readmeDocument lays out a one-page letter. With untagged set, the PDF
// carries no structure tree, like most files in the wild.
func readmeDocument(untagged bool) []byte {
	data, err := os.ReadFile("layout/testdata/fonts/kit-mono-regular.ttf")
	if err != nil {
		log.Fatal(err)
	}
	fonts := layout.NewFonts()
	if _, err := fonts.Add(data, layout.FontSpec{Family: "Mono"}); err != nil {
		log.Fatal(err)
	}
	doc := &layout.Document{
		Fonts:        fonts,
		DefaultStyle: layout.TextStyle{Size: 12},
		Options:      layout.Options{Untagged: untagged},
		Sections: []*layout.Section{{
			Size:   layout.A6,
			Margin: layout.All(20),
			Content: &layout.Column{Items: []layout.Element{
				layout.Heading{Level: 1, Child: layout.Text("Letter")},
				layout.Spacer{H: 24},
				layout.Text("Account 1234 is secret."),
			}},
		}},
	}
	var buf bytes.Buffer
	if _, err := doc.WritePDF(&buf, layout.WithTitle("Letter"), layout.WithLanguage("en")); err != nil {
		log.Fatal(err)
	}
	return buf.Bytes()
}

func main() {
	doc, err := onepdf.OpenBytes(readmeDocument(false), onepdf.WithEditing())
	if err != nil {
		log.Fatal(err)
	}
	pages, _ := text.Extract(doc)
	var regions []redact.Region
	for w := range pages[0].Words() {
		if w.Text == "1234" {
			regions = append(regions, redact.Region{Page: 0, Rect: w.Bounds})
		}
	}
	if _, err := redact.Apply(doc, regions); err != nil {
		log.Fatal(err)
	}
	var out bytes.Buffer
	if err := doc.Save(&out); err != nil {
		log.Fatal(err)
	}
	saved, _ := onepdf.OpenBytes(out.Bytes())
	s, _ := text.Plain(saved)
	fmt.Printf("%v %q\n", bytes.Contains(out.Bytes(), []byte("1234")), s)
}
Output:
false "Letter\n\nAccount\tis secret."
Example (Sign)
package main

import (
	"bytes"
	"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/layout"
	"recursiveai.org/go/onepdf/sign"
)

// readmeDocument lays out a one-page letter. With untagged set, the PDF
// carries no structure tree, like most files in the wild.
func readmeDocument(untagged bool) []byte {
	data, err := os.ReadFile("layout/testdata/fonts/kit-mono-regular.ttf")
	if err != nil {
		log.Fatal(err)
	}
	fonts := layout.NewFonts()
	if _, err := fonts.Add(data, layout.FontSpec{Family: "Mono"}); err != nil {
		log.Fatal(err)
	}
	doc := &layout.Document{
		Fonts:        fonts,
		DefaultStyle: layout.TextStyle{Size: 12},
		Options:      layout.Options{Untagged: untagged},
		Sections: []*layout.Section{{
			Size:   layout.A6,
			Margin: layout.All(20),
			Content: &layout.Column{Items: []layout.Element{
				layout.Heading{Level: 1, Child: layout.Text("Letter")},
				layout.Spacer{H: 24},
				layout.Text("Account 1234 is secret."),
			}},
		}},
	}
	var buf bytes.Buffer
	if _, err := doc.WritePDF(&buf, layout.WithTitle("Letter"), layout.WithLanguage("en")); err != nil {
		log.Fatal(err)
	}
	return buf.Bytes()
}

func main() {
	// A self-signed certificate stands in for the signer's own.
	key, _ := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
	tmpl := &x509.Certificate{
		SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "Signer"},
		NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(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.OpenBytes(readmeDocument(false), onepdf.WithEditing())
	if err != nil {
		log.Fatal(err)
	}
	var out bytes.Buffer
	res, err := sign.Sign(doc, &out, cred, sign.WithReason("I approve"))
	if err != nil {
		log.Fatal(err)
	}
	signed, _ := onepdf.OpenBytes(out.Bytes())
	report, _ := sign.Verify(signed)
	fmt.Println(res.FieldName != "", len(report.Signatures))
}
Output:
true 1
Example (Tag)
package main

import (
	"bytes"
	"fmt"
	"log"
	"os"

	"recursiveai.org/go/onepdf"
	"recursiveai.org/go/onepdf/layout"
	"recursiveai.org/go/onepdf/tag"
	"recursiveai.org/go/onepdf/text"
)

// readmeDocument lays out a one-page letter. With untagged set, the PDF
// carries no structure tree, like most files in the wild.
func readmeDocument(untagged bool) []byte {
	data, err := os.ReadFile("layout/testdata/fonts/kit-mono-regular.ttf")
	if err != nil {
		log.Fatal(err)
	}
	fonts := layout.NewFonts()
	if _, err := fonts.Add(data, layout.FontSpec{Family: "Mono"}); err != nil {
		log.Fatal(err)
	}
	doc := &layout.Document{
		Fonts:        fonts,
		DefaultStyle: layout.TextStyle{Size: 12},
		Options:      layout.Options{Untagged: untagged},
		Sections: []*layout.Section{{
			Size:   layout.A6,
			Margin: layout.All(20),
			Content: &layout.Column{Items: []layout.Element{
				layout.Heading{Level: 1, Child: layout.Text("Letter")},
				layout.Spacer{H: 24},
				layout.Text("Account 1234 is secret."),
			}},
		}},
	}
	var buf bytes.Buffer
	if _, err := doc.WritePDF(&buf, layout.WithTitle("Letter"), layout.WithLanguage("en")); err != nil {
		log.Fatal(err)
	}
	return buf.Bytes()
}

func main() {
	doc, err := onepdf.OpenBytes(readmeDocument(true), onepdf.WithEditing())
	if err != nil {
		log.Fatal(err)
	}
	pages, err := text.Extract(doc, text.WithRetainGlyphs(true))
	if err != nil {
		log.Fatal(err)
	}
	// You decide each block's role; the package builds the structure tree.
	_, err = tag.Tag(doc, pages, func(b tag.BlockInfo) tag.BlockRole {
		if b.BlockIndex == 0 {
			return tag.BlockHeading(1)
		}
		return tag.BlockParagraph()
	}, tag.WithLanguage("en"))
	if err != nil {
		log.Fatal(err)
	}
	for e := range tag.Structure(doc).Elements() {
		fmt.Println(e.StandardType)
	}
}
Output:
Document
H1
P

Index

Examples

Constants

View Source
const (
	AnnotInvisible     = 1 << 0
	AnnotHidden        = 1 << 1
	AnnotPrint         = 1 << 2
	AnnotNoZoom        = 1 << 3
	AnnotNoRotate      = 1 << 4
	AnnotNoView        = 1 << 5
	AnnotReadOnly      = 1 << 6
	AnnotLocked        = 1 << 7
	AnnotToggleNoView  = 1 << 8
	AnnotLockedContent = 1 << 9
)

Annotation flag bits (ISO 32000-2 12.5.3, Table 167), for Annotation.Flags.

View Source
const (
	CapButt   = device.ButtCap
	CapRound  = device.RoundCap
	CapSquare = device.ProjectingCap
)

The line caps.

View Source
const (
	JoinMiter = device.MiterJoin
	JoinRound = device.RoundJoin
	JoinBevel = device.BevelJoin
)

The line joins.

View Source
const (
	BlendNormal     = device.BlendNormal
	BlendMultiply   = device.BlendMultiply
	BlendScreen     = device.BlendScreen
	BlendOverlay    = device.BlendOverlay
	BlendDarken     = device.BlendDarken
	BlendLighten    = device.BlendLighten
	BlendColorDodge = device.BlendColorDodge
	BlendColorBurn  = device.BlendColorBurn
	BlendHardLight  = device.BlendHardLight
	BlendSoftLight  = device.BlendSoftLight
	BlendDifference = device.BlendDifference
	BlendExclusion  = device.BlendExclusion
	BlendHue        = device.BlendHue
	BlendSaturation = device.BlendSaturation
	BlendColor      = device.BlendColor
	BlendLuminosity = device.BlendLuminosity
)

The blend modes.

View Source
const (
	FieldReadOnly    = 1 << 0
	FieldRequired    = 1 << 1
	FieldNoExport    = 1 << 2
	FieldMultiline   = 1 << 12
	FieldPassword    = 1 << 13
	FieldRadio       = 1 << 15 // a button that is a radio button
	FieldPushButtonF = 1 << 16 // a button that is a push button
	FieldCombo       = 1 << 17 // a choice that is a combo box
	FieldMultiSelect = 1 << 21
)

Field flag bits (/Ff, ISO 32000-2 12.7.4.1 and the type tables).

View Source
const (
	// ImageDecoded: Samples hold 8-bit samples of Space with /Decode
	// applied (an Indexed image holds its indices).
	ImageDecoded = device.ImageDecoded
	// ImageStencil: an image mask; Coverage is 255 where the fill colour
	// paints and 0 where it does not.
	ImageStencil = device.ImageStencil
	// ImageEncoded: the image is left as the codec stored it, because no
	// decoder is registered or the caller asked for encoded data.
	ImageEncoded = device.ImageEncoded
	// ImageNone: the dictionary or data is unusable; nothing is painted.
	ImageNone = device.ImageNone
	// ImageLimit: the image is larger than Limits.MaxImagePixels allows.
	ImageLimit = device.ImageLimit
)

Image kinds.

View Source
const (
	CropBox  = device.CropBox
	MediaBox = device.MediaBox
	BleedBox = device.BleedBox
	TrimBox  = device.TrimBox
	ArtBox   = device.ArtBox
)

The page boxes.

View Source
const (
	// XMPNSDublinCore is the Dublin Core schema (dc:title, dc:creator, dc:description).
	XMPNSDublinCore = "http://purl.org/dc/elements/1.1/"
	// XMPNSBasic is the XMP basic schema (xmp:CreatorTool, xmp:CreateDate, xmp:ModifyDate).
	XMPNSBasic = "http://ns.adobe.com/xap/1.0/"
	// XMPNSPDF is the Adobe PDF schema (pdf:Producer, pdf:Keywords).
	XMPNSPDF = "http://ns.adobe.com/pdf/1.3/"
	// XMPNSPDFA is the PDF/A identification schema (pdfaid:part, pdfaid:conformance).
	XMPNSPDFA = "http://www.aiim.org/pdfa/ns/id/"
	// XMPNSPDFUA is the PDF/UA identification schema (pdfuaid:part, pdfuaid:rev).
	XMPNSPDFUA = "http://www.aiim.org/pdfua/ns/id/"
	// XMPNSMediaManagement is the XMP media management schema (xmpMM:DocumentID, xmpMM:InstanceID).
	XMPNSMediaManagement = "http://ns.adobe.com/xap/1.0/mm/"
	// XMPNSPDFAExtension is the PDF/A extension schema container (pdfaExtension:schemas).
	XMPNSPDFAExtension = "http://www.aiim.org/pdfa/ns/extension/"
	// XMPNSPDFASchema is the PDF/A schema description namespace (pdfaSchema:namespaceURI).
	XMPNSPDFASchema = "http://www.aiim.org/pdfa/ns/schema#"
	// XMPNSPDFAProperty is the PDF/A property description namespace (pdfaProperty:name).
	XMPNSPDFAProperty = "http://www.aiim.org/pdfa/ns/property#"
)

Namespace URIs of the XMP schemas the library reads and writes.

View Source
const PermissionsAll = permAll

PermissionsAll is every usage flag set.

Variables

View Source
var (
	// ErrFormat means the data is not a PDF, or its damage could not be repaired.
	ErrFormat = errors.New("onepdf: not a valid PDF")
	// ErrLimit means a bound (see Limits) was reached before the work was done.
	ErrLimit = errors.New("onepdf: limit exceeded")
	// ErrPassword means the document needs a password, or the one given is wrong.
	ErrPassword = errors.New("onepdf: password required or wrong")
	// ErrEncryption means the document uses a security handler this library cannot use, or its encryption is damaged.
	ErrEncryption = errors.New("onepdf: unsupported or damaged encryption")
	// ErrSourceChanged means the bytes behind a document changed after it was opened.
	ErrSourceChanged = errors.New("onepdf: source changed since the document was opened")
	// ErrArgument means a call was given a value it cannot use: an index out of range, an object number that does
	// not exist, a value that belongs to another document, a size that is not positive.
	ErrArgument = errors.New("onepdf: invalid argument")
	// ErrNotEditable means the call would change a document that was not opened with WithEditing, or an object
	// that belongs to an earlier revision, or the call is one the document's state forbids.
	ErrNotEditable = errors.New("onepdf: the document or object cannot be edited")
	// ErrBuilderState means a content builder, streaming writer, page or structure element was used
	// when its state forbids the call: after it was closed or finished, a restore with nothing saved,
	// text drawn before a font was set, a page begun while another is open. It is a programming error
	// in the caller's sequence of calls, not a property of the document, which is why it is not
	// ErrNotEditable.
	ErrBuilderState = errors.New("onepdf: the builder is not in a state that allows the call")
	// ErrNoFontProvider means a call needed substitute fonts and no font provider is set, on the document or
	// registered. The substitute faces are in the nested fonts module.
	ErrNoFontProvider = errors.New("onepdf: no font provider")
	// ErrUnsupported means the request names something this library does not do, such as a stream filter it cannot decode.
	ErrUnsupported = errors.New("onepdf: unsupported")
)

Error categories. Every error this package returns matches one of them with errors.Is; the typed errors below carry the detail.

View Source
var (
	PDF14 = Version{1, 4}
	PDF15 = Version{1, 5}
	PDF16 = Version{1, 6}
	PDF17 = Version{1, 7}
	PDF20 = Version{2, 0}
)

The versions the standards define.

View Source
var ErrDate = errors.New("onepdf: not a PDF date")

ErrDate is returned by ParseDate for text that is not a PDF date.

View Source
var ErrFontEmbed = errors.New("onepdf: font cannot be embedded")

ErrFontEmbed is matched, through errors.Is, by every FontEmbedError.

View Source
var ErrForm = errors.New("onepdf: form value rejected")

ErrForm is matched by every FormError: a value or name the form cannot take. A FormError also matches ErrArgument.

View Source
var ErrNotImageCodec = errors.New("onepdf: not an image codec filter")

ErrNotImageCodec is returned when a decoder is registered for a filter that is not one of the image codecs DCTDecode, JPXDecode and JBIG2Decode.

View Source
var ErrPageRange = errors.New("onepdf: page index out of range")

ErrPageRange is returned by Document.Page for an index outside 0..PageCount-1.

Functions

func ParseDate

func ParseDate(s string) (time.Time, error)

ParseDate reads a PDF date string, "D:YYYYMMDDHHmmSS+HH'mm'" (ISO 32000-2 7.9.4), and returns the instant in UTC.

Leniency, in the way readers treat real files: leading white space and a missing "D:" prefix are accepted; every field after the year may be missing and then takes its lowest value (month and day 1, the rest 0); text after a valid date is ignored; a missing zone means UTC. The zone is Z, or + or - with hours, optionally followed by an apostrophe and minutes with or without a closing apostrophe, or four digits without apostrophes. A second of 60 (a leap second) reads as 59. Anything out of range (month 13, 30 February, hour 24, minute 60, second 61, an offset beyond 23:59) fails with ErrDate.

Example
package main

import (
	"fmt"

	"recursiveai.org/go/onepdf"
)

func main() {
	t, err := onepdf.ParseDate("D:20200317093045+05'30'")
	fmt.Println(t.Format("2006-01-02 15:04:05 MST"), err)
	_, err = onepdf.ParseDate("D:20201301")
	fmt.Println(err)
}
Output:
2020-03-17 04:00:45 UTC <nil>
onepdf: not a PDF date

func RegisterFontProvider

func RegisterFontProvider(p FontProvider)

RegisterFontProvider adds a provider consulted, in registration order, for every font without an embedded program, and by Document.EmbedSubstituteFonts when the document has no provider of its own. Registering a provider that is already registered changes nothing. Like database/sql.Register, call it from an init function or from main before the first Open; the registry is safe for concurrent use, but fonts a document has already loaded keep the stand-ins they got. With no provider such fonts keep their widths and Unicode but have no outlines. The library reads installed fonts only when the caller turns them on with WithSystemFonts or registers SystemFontProvider.

Example
package main

import (
	"fmt"
	"os"

	"recursiveai.org/go/onepdf"
)

// A provider that lends one TrueType program to every font a document does
// not embed. The library finds glyphs by name or Unicode and scales them to
// the widths the file states.
type lendFont struct{ program []byte }

func (p lendFont) FindFont(req onepdf.FontRequest) (*onepdf.Substitute, bool) {
	if req.Standard14 == "" {
		return nil, false
	}
	return &onepdf.Substitute{Name: "lent", Data: p.program}, true
}

func main() {
	program, err := os.ReadFile("testdata/fonts/kit-tt.ttf")
	if err != nil {
		fmt.Println(err)
		return
	}
	onepdf.RegisterFontProvider(lendFont{program})
	fmt.Println("registered", len(program) > 0)
}
Output:
registered true

func RegisterImageDecoder

func RegisterImageDecoder(filter string, d ImageDecoder) error

RegisterImageDecoder registers d for filter in DefaultImageDecoders(), replacing any decoder already there. filter is DCTDecode, JPXDecode or JBIG2Decode (the abbreviation DCT is accepted); any other name returns ErrNotImageCodec. A nil d removes the registration.

Like database/sql.Register and image.RegisterFormat, call it from an init function or from main before the first Open: the registry is safe for concurrent use, but a document that has already decoded an image keeps what it decoded, so a later registration does not change it.

Types

type AFRelationship

type AFRelationship string

AFRelationship says how an attached file relates to the document that carries it (ISO 32000-2 7.11.3, Table 43), the "associated file" relationship PDF/A-3 asks for.

const (
	// RelUnspecified is the default: the relationship is not stated.
	RelUnspecified AFRelationship = "Unspecified"
	// RelSource is the original source material of the document.
	RelSource AFRelationship = "Source"
	// RelData is data the document presents, such as the values behind a chart.
	RelData AFRelationship = "Data"
	// RelAlternative is an alternative representation, such as a different format of the same content.
	RelAlternative AFRelationship = "Alternative"
	// RelSupplement is a supplement to the document.
	RelSupplement AFRelationship = "Supplement"
	// RelFormData is the data of a form.
	RelFormData AFRelationship = "FormData"
	// RelSchema is a schema that describes the data.
	RelSchema AFRelationship = "Schema"
)

Relationships of an attached file.

type Access

type Access int

Access says which password opened an encrypted document.

const (
	// AccessNone is reported for a document that is not open, which a Document
	// never is: Open refuses a document whose password does not work.
	AccessNone Access = iota
	// AccessUser means the user password (possibly the empty one) opened the document.
	AccessUser
	// AccessOwner means the owner password opened the document, or the
	// document is not encrypted and nothing limits its use.
	AccessOwner
)

func (Access) String

func (a Access) String() string

String returns "none", "user" or "owner".

type AcroForm

type AcroForm struct {
	// contains filtered or unexported fields
}

AcroForm is the interactive form (ISO 32000-2 12.7.3) read as data. Filling is the editor's job; scripts in the form (/AA, /JS) are never run.

func (*AcroForm) All

func (f *AcroForm) All() iter.Seq[*Field]

All iterates over every field, parents before their children, in tree order.

func (*AcroForm) Clear

func (f *AcroForm) Clear(name string, opts ...FillOption) error

Clear removes the value of the field with the fully qualified name. See Field.Clear.

func (*AcroForm) Dict

func (f *AcroForm) Dict() *Dict

Dict returns the /AcroForm dictionary.

func (*AcroForm) Fields

func (f *AcroForm) Fields() []*Field

Fields returns the top-level fields; each holds its Children.

func (*AcroForm) Fill

func (f *AcroForm) Fill(values map[string]any, opts ...FillOption) error

Fill sets many fields at once, the happy path of the form API. Each key is a fully qualified field name; each value is a string (SetValue), a bool (SetChecked), a []string (SetValues) or nil (Clear). Fields are filled in name order, so the result is the same on every run. A field that is refused is skipped and its error joined into the result; the others are still filled. On the nil form that Document.Form returns for a file without one, every name is refused and the result matches ErrForm; an empty map returns nil.

Example
package main

import (
	"bytes"
	"errors"
	"fmt"

	"recursiveai.org/go/onepdf"
)

// exampleFormPDF is a one-page form with a text field and a check box. The file has no
// cross-reference table: the reader rebuilds it.
const exampleFormPDF = `%PDF-1.7
1 0 obj
<</Type /Catalog/Pages 2 0 R/AcroForm <</Fields [5 0 R 6 0 R]/DA (/Helv 0 Tf 0 g)/NeedAppearances true>>>>
endobj
2 0 obj
<</Type /Pages/Kids [3 0 R]/Count 1>>
endobj
3 0 obj
<</Type /Page/Parent 2 0 R/MediaBox [0 0 200 100]/Annots [5 0 R 6 0 R]>>
endobj
5 0 obj
<</Type /Annot/Subtype /Widget/FT /Tx/T (name)/MaxLen 8/Rect [10 60 150 80]/F 4>>
endobj
6 0 obj
<</Type /Annot/Subtype /Widget/FT /Btn/T (agree)/Rect [10 20 30 40]/F 4/AS /Off/V /Off/AP <</N <</Yes 7 0 R/Off 7 0 R>>>>>>
endobj
7 0 obj
<</Type /XObject/Subtype /Form/BBox [0 0 20 20]/Length 14>>
stream
0 0 20 20 re S
endstream
endobj
trailer
<</Root 1 0 R>>
`

func main() {
	doc, err := onepdf.OpenBytes([]byte(exampleFormPDF), onepdf.WithEditing())
	if err != nil {
		fmt.Println(err)
		return
	}
	form := doc.Form()
	// Strings fill text and choice fields, bools check boxes; a refused field is reported and the rest are filled.
	err = form.Fill(map[string]any{"name": "Ada", "agree": true, "nobody": "x"})
	var fe *onepdf.FormError
	if errors.As(err, &fe) {
		fmt.Println("refused:", fe.Field, fe.Reason)
	}
	var out bytes.Buffer
	if err := doc.Save(&out); err != nil {
		fmt.Println(err)
		return
	}
	saved, _ := onepdf.OpenBytes(out.Bytes())
	name, _ := saved.Form().Find("name").Value()
	agree, _ := saved.Form().Find("agree").Value()
	fmt.Println(name, agree, saved.Form().NeedAppearances())
}
Output:
refused: nobody UnknownField
Ada Yes false

func (*AcroForm) FillContext

func (f *AcroForm) FillContext(ctx context.Context, values map[string]any, opts ...FillOption) error

FillContext is Fill that stops with ctx.Err() when ctx is done, between fields; fields filled before then stay filled.

func (*AcroForm) Find

func (f *AcroForm) Find(fullName string) *Field

Find returns the field with the fully qualified name, or nil.

func (*AcroForm) GenerateMissingAppearances

func (f *AcroForm) GenerateMissingAppearances() (int, error)

GenerateMissingAppearances stores a generated normal appearance for every widget that has none and returns how many it stored. A check box or radio widget that is off needs none; signature fields get none. When every widget has an appearance afterwards, /NeedAppearances is cleared by the rule that fills follow. It needs a document opened with WithEditing.

func (*AcroForm) GenerateMissingAppearancesContext

func (f *AcroForm) GenerateMissingAppearancesContext(ctx context.Context) (int, error)

GenerateMissingAppearancesContext is GenerateMissingAppearances that stops with ctx.Err() when ctx is done, between widgets, returning how many it had stored.

func (*AcroForm) HasXFA

func (f *AcroForm) HasXFA() bool

HasXFA reports whether the form has an /XFA entry. The XFA data is never rendered or run.

func (*AcroForm) NeedAppearances

func (f *AcroForm) NeedAppearances() bool

NeedAppearances reports /NeedAppearances: the file asks readers to rebuild field appearances.

func (*AcroForm) RenameField

func (f *AcroForm) RenameField(name, newName string) error

RenameField changes the partial name (/T) of the field with the fully qualified name. See Field.Rename.

func (*AcroForm) Reset

func (f *AcroForm) Reset(name string, opts ...FillOption) error

Reset sets the field with the fully qualified name back to its default. See Field.Reset.

func (*AcroForm) ResetAll

func (f *AcroForm) ResetAll(opts ...FillOption) (int, error)

ResetAll resets every terminal field and returns how many it reset. Read-only fields are skipped unless WithFillOverrideReadOnly is given; push buttons and signature fields are always skipped.

func (*AcroForm) ResetAllContext

func (f *AcroForm) ResetAllContext(ctx context.Context, opts ...FillOption) (int, error)

ResetAllContext is ResetAll that stops with ctx.Err() when ctx is done, between fields, returning how many it had reset.

func (*AcroForm) SetChecked

func (f *AcroForm) SetChecked(name string, on bool, opts ...FillOption) error

SetChecked checks or clears the check box or radio group with the fully qualified name.

func (*AcroForm) SetFieldAppearance

func (f *AcroForm) SetFieldAppearance(name string, style FieldStyle) (int, error)

SetFieldAppearance restyles the field with the fully qualified name. See Field.SetAppearance.

func (*AcroForm) SetValue

func (f *AcroForm) SetValue(name, value string, opts ...FillOption) error

SetValue fills the field with the fully qualified name. See Field.SetValue.

func (*AcroForm) SetValues

func (f *AcroForm) SetValues(name string, values []string, opts ...FillOption) error

SetValues fills the field with the fully qualified name. See Field.SetValues.

func (*AcroForm) SignatureFlags

func (f *AcroForm) SignatureFlags() int

SignatureFlags returns /SigFlags: bit 1 says the file has signatures, bit 2 that it is append-only.

func (*AcroForm) Terminal

func (f *AcroForm) Terminal() iter.Seq[*Field]

Terminal iterates over the fields that have no sub-fields: the ones that hold values.

func (*AcroForm) XFA

func (f *AcroForm) XFA() ([]byte, error)

XFA returns the XFA XML packets, concatenated in order when /XFA is an array of name and stream pairs; nil when the form has none. It is raw XML.

type Action

type Action struct {
	// Type is the action's /S name, such as "GoTo", "URI" or "JavaScript".
	Type string
	// URI is the address of a URI action (decoded as stored, normally ASCII).
	URI string
	// File is the file of a GoToR, Launch, ImportData or SubmitForm action.
	File string
	// Named is the /N name of a Named action such as "NextPage".
	Named string
	// JavaScript is the script of a JavaScript action.
	JavaScript string
	// Destination is where a GoTo or GoToR action leads.
	Destination *Destination
	// Next lists every action that follows this one, flattened in order: the
	// /Next entries and, after each, what it leads to. An action appears once,
	// never in its own list, and an action never lists one that comes before
	// it, so a chain that loops back ends there. Each listed action carries its
	// own list of those after it.
	Next []*Action
	// Dict is the action dictionary.
	Dict *Dict
}

Action is an interactive action (ISO 32000-2 12.6) read as data. Nothing in this library runs an action: a JavaScript action's script is text, a URI action's address is text, and none is ever followed.

type Annotation

type Annotation struct {
	// Dict is the annotation dictionary.
	Dict *Dict
	// Page is the page whose /Annots array lists the annotation.
	Page *Page
	// Subtype is /Subtype: "Link", "Text", "Widget" and so on; "" when missing.
	Subtype string
	// Rect is /Rect, normalised; the zero Rect when missing or malformed.
	Rect Rect
	// Contents, Title and Name are /Contents, /T and /NM as text.
	Contents, Title, Name string
	// Color is /C: nil when absent, empty for transparent, else 1, 3 or 4 numbers.
	Color []float64
	// Flags is /F; test it against the Annot constants.
	Flags int
	// Modified is /M in UTC; the zero time when absent or not a date.
	Modified time.Time
	// QuadPoints is /QuadPoints truncated to whole quadrilaterals of 8 numbers.
	QuadPoints []float64
	// Popup is the /Popup annotation dictionary, or nil.
	Popup *Dict
	// URI is the address of the annotation's URI action, or "".
	URI string
	// Destination is the link's /Dest, resolved; nil when it has none. A link led by an action keeps it in Action.
	Destination *Destination
	// Action is the annotation's /A action chain, or nil.
	Action *Action
	// AttachedFile is the file of a FileAttachment annotation, or nil.
	AttachedFile *EmbeddedFile
}

Annotation is one annotation of a page (ISO 32000-2 12.5) read as data. Absent text fields are "" (the underlying Dict tells absent from empty).

func (*Annotation) AppearanceStream

func (a *Annotation) AppearanceStream(kind AppearanceKind) *Stream

AppearanceStream returns the annotation's appearance stream of the kind, or nil. An entry that is a dictionary of states is read at the state /AS names (ISO 32000-2 12.5.5); without an /AS there is none.

func (*Annotation) GenerateAppearance

func (a *Annotation) GenerateAppearance() (*GeneratedAppearance, error)

GenerateAppearance builds the annotation's normal appearance from its dictionary, the way the interpreter draws one that is missing: widgets, Square, Circle, Line, Polygon, PolyLine, Ink, Caret, the text-markup subtypes, FreeText and Text. It changes nothing; the result is data for the caller to store. The annotation need not lack an appearance: a stored one is ignored.

It returns an error matching ErrUnsupported for a subtype with no generated appearance (Link, Stamp and the rest) and ErrArgument for an annotation with no usable /Rect, or one with nothing to draw.

Example
package main

import (
	"fmt"

	"recursiveai.org/go/onepdf"
)

func main() {
	pdf := []byte("%PDF-1.7\n" +
		"1 0 obj\n<</Type /Catalog/Pages 2 0 R>>\nendobj\n" +
		"2 0 obj\n<</Type /Pages/Kids [3 0 R]/Count 1>>\nendobj\n" +
		"3 0 obj\n<</Type /Page/Parent 2 0 R/MediaBox [0 0 100 100]/Annots [4 0 R]>>\nendobj\n" +
		"4 0 obj\n<</Type /Annot/Subtype /Square/Rect [10 10 60 40]/C [1 0 0]>>\nendobj\n" +
		"trailer\n<</Root 1 0 R>>\n")
	doc, err := onepdf.OpenBytes(pdf)
	if err != nil {
		fmt.Println(err)
		return
	}
	page, _ := doc.Page(0)
	ap, err := page.Annotations()[0].GenerateAppearance()
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(ap.Rect.X0, ap.Rect.Y0, ap.Rect.X1, ap.Rect.Y1)
	fmt.Println(ap.Dict.Name("Subtype"))
	fmt.Println(len(ap.Content) > 0)
}
Output:
9.5 9.5 60.5 40.5
Form true
true

func (*Annotation) HasAppearance

func (a *Annotation) HasAppearance() bool

HasAppearance reports whether the annotation has an /AP dictionary, even an empty one.

type AnnotationMode

type AnnotationMode uint8

AnnotationMode says which annotations Interpret draws.

const (
	// AnnotationsView draws every annotation a viewer shows on screen: not
	// hidden and not marked NoView. It is the default.
	AnnotationsView AnnotationMode = iota
	// AnnotationsPrint draws the annotations a printer prints: those with
	// the Print flag that are not hidden.
	AnnotationsPrint
	// AnnotationsNone draws page content only.
	AnnotationsNone
)

Annotation modes.

func (AnnotationMode) String

func (m AnnotationMode) String() string

String returns "view", "print" or "none".

type AppearanceKind

type AppearanceKind int

AppearanceKind selects one of an annotation's three appearances (ISO 32000-2 12.5.5).

const (
	AppearanceNormal AppearanceKind = iota
	AppearanceRollover
	AppearanceDown
)

The appearance kinds: the normal appearance, shown at rest; the rollover, shown under the pointer; and the down appearance, shown while pressed.

func (AppearanceKind) String

func (k AppearanceKind) String() string

String returns "Normal", "Rollover" or "Down".

type Array

type Array struct {
	// contains filtered or unexported fields
}

Array is a PDF array (7.3.6). Elements are kept as read: a reference stays a Ref until a getter resolves it.

func NewArray

func NewArray(items ...Object) *Array

NewArray returns an array holding items. It belongs to no document, so its getters leave references unresolved.

func (*Array) All

func (a *Array) All() iter.Seq2[int, Object]

All yields every element as stored, in order.

func (*Array) Append

func (a *Array) Append(v ...Object) error

Append adds the elements at the end and records the change; each is treated as Dict.Set treats a value, and a nil element is stored as the null object. If any value is refused nothing is added. On an array that belongs to no document, or to one being built, it never fails with ErrNotEditable.

func (*Array) Clear

func (a *Array) Clear() error

Clear deletes every element.

func (*Array) Get

func (a *Array) Get(i int) Object

Get returns element i with references followed. An index out of range, a null element and a reference to nothing give nil.

func (*Array) Insert

func (a *Array) Insert(i int, v Object) error

Insert stores v before element i, which may be Len to append. An index out of range is ErrArgument.

func (*Array) Int

func (a *Array) Int(i int, def int64) int64

Int returns element i as an integer. A real is truncated toward zero; any other type, and a missing element, give def.

func (*Array) Len

func (a *Array) Len() int

Len returns the number of elements.

func (*Array) Name

func (a *Array) Name(i int) (name Name, ok bool)

Name returns element i when it is a name, and "" otherwise; ok says which.

func (*Array) Raw

func (a *Array) Raw(i int) Object

Raw returns element i as stored, a Ref left unresolved. An index out of range, and a null element, give nil.

func (*Array) Real

func (a *Array) Real(i int, def float64) float64

Real returns element i as a real; an integer converts. Anything else gives def.

func (*Array) Ref

func (a *Array) Ref() Ref

Ref returns the reference this array was read through, if it is an indirect object's value; otherwise the zero Ref.

func (*Array) RemoveAt

func (a *Array) RemoveAt(i int) error

RemoveAt deletes element i. An index out of range is ErrArgument.

func (*Array) Resolved

func (a *Array) Resolved() iter.Seq2[int, Object]

Resolved yields every element with references followed.

func (*Array) SetAt

func (a *Array) SetAt(i int, v Object) error

SetAt replaces element i. An index out of range is ErrArgument.

type ArtifactSubtype

type ArtifactSubtype int

ArtifactSubtype refines a pagination artifact.

const (
	ArtifactSubtypeNone ArtifactSubtype = iota
	ArtifactHeader
	ArtifactFooter
	ArtifactWatermark
)

The artifact subtypes.

func (ArtifactSubtype) String

func (s ArtifactSubtype) String() string

String returns the subtype's PDF name, or "None".

type ArtifactType

type ArtifactType int

ArtifactType is the kind of an artifact: content that is not part of the document's real content (ISO 32000-2 14.8.2.2).

const (
	ArtifactNone ArtifactType = iota
	ArtifactPagination
	ArtifactLayout
	ArtifactPage
	ArtifactBackground
)

The artifact types.

func (ArtifactType) String

func (t ArtifactType) String() string

String returns the type's PDF name, or "None".

type Attachment

type Attachment struct {
	// Name is the file name, shown by readers and used as the name-tree key. It must not be empty.
	Name string
	// Data is the file's content.
	Data []byte
	// Description is optional free text (/Desc).
	Description string
	// MIMEType is the media type, written as the embedded stream's /Subtype. Default "application/octet-stream".
	MIMEType string
	// Relationship is the /AFRelationship. Default RelUnspecified.
	Relationship AFRelationship
	// Created and Modified are written to the embedded file's /Params when they are not the zero time.
	Created, Modified time.Time
}

Attachment describes a file to embed with AttachFile.

type BlendMode

type BlendMode = device.BlendMode

BlendMode is a PDF blend mode (ISO 32000-2 11.3.5). It is the device package's type; the constants keep their names.

type Bool

type Bool bool

Bool is a PDF boolean.

type BoxColor

type BoxColor struct {
	// R, G and B are the line colour, each 0..1; default black.
	R, G, B float64
	// LineWidth is the outline width in points; default 1.
	LineWidth float64
	// Style is BoxSolid, or BoxDashed when /S is /D.
	Style BoxStyle
	// Dash is the dash array in points; default [3].
	Dash []float64
}

BoxColor describes how a viewer should outline a page box (ISO 32000-2 14.11.2.2, Table 395).

type BoxStyle

type BoxStyle int

BoxStyle is the line style of a BoxColor.

const (
	BoxSolid BoxStyle = iota
	BoxDashed
)

Line styles of a page-box outline.

func (BoxStyle) String

func (s BoxStyle) String() string

String returns "Solid" or "Dashed".

type Cipher

type Cipher int

Cipher names the algorithm that protects a document's streams.

const (
	// CipherNone means the streams are stored in the clear (an /Identity filter).
	CipherNone Cipher = iota
	// CipherRC4 is RC4 with a 40 to 128 bit key.
	CipherRC4
	// CipherAES128 is AES-128 in CBC mode (crypt filter AESV2).
	CipherAES128
	// CipherAES256 is AES-256 in CBC mode (crypt filter AESV3).
	CipherAES256
)

func (Cipher) String

func (c Cipher) String() string

String returns "none", "rc4", "aes128" or "aes256".

type ColorSpace

type ColorSpace struct {
	// contains filtered or unexported fields
}

ColorSpace is a PDF colour space (ISO 32000-2 8.6) resolved for use outside the interpreter: a program that reads image samples, annotation colours or shading data itself can turn component values into a colour in a final space, the same conversion the interpreter makes before it calls a device. A ColorSpace is immutable and safe for concurrent use.

func (*ColorSpace) Base

func (c *ColorSpace) Base() *ColorSpace

Base is the base space of an Indexed or Pattern space and the alternate space of a Separation or DeviceN space; nil for any other.

func (*ColorSpace) Color

func (c *ColorSpace) Color(comps ...float64) (col device.Color, ok bool)

Color converts component operands (one per component, in the space's own ranges: 0 to 1 for most, the index for Indexed, L*, a*, b* for Lab) to a colour in the final space, evaluating Indexed lookups and tint transforms. Operands are clamped to the range as ISO 32000-2 8.6.4 says. ok is false when the operand count is wrong or the space is a Pattern.

func (*ColorSpace) Components

func (c *ColorSpace) Components() int

Components is the number of operands one colour of this space takes: 1 for Indexed and Separation, the colorant count for DeviceN, 0 for Pattern.

func (*ColorSpace) DefaultDecode

func (c *ColorSpace) DefaultDecode(bitsPerComponent int) []float64

DefaultDecode is the /Decode array an image of this space gets when it has none (ISO 32000-2 8.9.5.2, Table 87) at bitsPerComponent bits: 0 and 1 per component, 0 and 2^bits-1 for Indexed, 0 to 100 then the a and b range for Lab, the profile's /Range for ICCBased. It is nil for a Pattern space and for a bit depth outside 1 to 16.

func (*ColorSpace) Family

func (c *ColorSpace) Family() Name

Family is the colour space family: DeviceGray, DeviceRGB, DeviceCMYK, CalGray, CalRGB, Lab, ICCBased, Indexed, Separation, DeviceN or Pattern. CalGray and CalRGB given by bare name report as the device space.

func (*ColorSpace) Final

func (c *ColorSpace) Final() device.ColorSpace

Final is the space colours come out in: the space itself for device, CIE and ICC spaces, the base space for Indexed and the alternate space for Separation and DeviceN. It is what a device sees in device.Color.Space.

func (*ColorSpace) ICCProfile

func (c *ColorSpace) ICCProfile() []byte

ICCProfile returns the profile bytes of an ICCBased space, or nil. The bytes are shared and must not be modified.

func (*ColorSpace) IndexedTable

func (c *ColorSpace) IndexedTable() (hival int, lookup []byte, ok bool)

IndexedTable returns, for an Indexed space, the largest index and the lookup table: the base space's components for index 0, then for index 1, and so on, one byte per component (the table may be shorter than (hival+1)*n when the file's is; missing entries read as 0). ok is false for any other space. The table is shared and must not be modified.

func (*ColorSpace) Initial

func (c *ColorSpace) Initial() device.Color

Initial is the colour a content stream starts with after selecting the space (ISO 32000-2 8.6.5 to 8.6.8): black for the device spaces, full tint for Separation and DeviceN, the nearest to zero in range for Lab. A Pattern space gives a colour with no pattern.

func (*ColorSpace) String

func (c *ColorSpace) String() string

String names the space in the canonical object form (for example "[/Indexed /DeviceRGB 1 <...>]").

type ContentBuilder

type ContentBuilder struct {
	// contains filtered or unexported fields
}

ContentBuilder is a drawing surface: paths, colours, graphics state, images, forms, gradients, text and marked content, written as a content stream. PageContent and FormContent embed it; the streaming writer's pages do too.

A builder collects its operators and writes them only when it is committed, so a builder that is closed first leaves its target as it was.

Coordinates are those of the page's default user space: the origin is the lower left corner of the MediaBox as stored, y points up and one unit is 1/72 inch (times /UserUnit). /Rotate and the CropBox are not applied to what is drawn. Numbers are written rounded to four decimals.

The first call that fails records its error and every later call does nothing: check Err, or the error Commit returns. A value that is not a finite number, or that belongs to another document, is ErrArgument; a call the builder's state forbids (a restore with nothing saved, a closed builder) is ErrNotEditable.

func (*ContentBuilder) BeginArtifact

func (b *ContentBuilder) BeginArtifact(t ArtifactType, sub ArtifactSubtype, bbox *Rect)

BeginArtifact begins an artifact sequence, ended by EndMarkedContent. The type and subtype are left out when None; bbox, when not nil, is the artifact's bounding box.

func (*ContentBuilder) BeginMarkedContent

func (b *ContentBuilder) BeginMarkedContent(tag string)

BeginMarkedContent begins a marked-content sequence with the given tag (ISO 32000-2 14.6), such as "P" or "Span". Every sequence needs an EndMarkedContent at the same Save depth; Commit ends the ones left open.

func (*ContentBuilder) BeginMarkedContentID

func (b *ContentBuilder) BeginMarkedContentID(tag string, mcid int)

BeginMarkedContentID begins a sequence with a marked-content identifier (/MCID) that a structure element refers to.

func (*ContentBuilder) BeginSpan

func (b *ContentBuilder) BeginSpan(o SpanOptions)

BeginSpan begins a Span marked-content sequence with the given properties, ended by EndMarkedContent.

func (*ContentBuilder) ClearSoftMask

func (b *ContentBuilder) ClearSoftMask()

ClearSoftMask removes the soft mask.

func (*ContentBuilder) Clip

func (b *ContentBuilder) Clip(rule device.FillRule)

Clip intersects the clipping region with the current path by the given rule. The path ends without painting; the clip lasts until the matching Restore.

func (*ContentBuilder) Close

func (b *ContentBuilder) Close()

Close discards what was drawn and closes the builder; the target is left as it was. It does nothing after Commit. A closed builder takes no more calls.

func (*ContentBuilder) ClosePath

func (b *ContentBuilder) ClosePath()

ClosePath closes the current subpath with a straight line to its start.

func (*ContentBuilder) CurveTo

func (b *ContentBuilder) CurveTo(x1, y1, x2, y2, x3, y3 float64)

CurveTo adds a cubic Bézier curve to (x3, y3) with control points (x1, y1) and (x2, y2).

func (*ContentBuilder) Document

func (b *ContentBuilder) Document() *Document

Document returns the document the builder draws into, or nil for a streaming writer's builder.

func (*ContentBuilder) DrawExistingForm

func (b *ContentBuilder) DrawExistingForm(form *Stream)

DrawExistingForm draws a Form XObject that is already in the builder's document. Another document's stream, or one that is not a form, is ErrArgument.

func (*ContentBuilder) DrawExistingImage

func (b *ContentBuilder) DrawExistingImage(img *Stream, x, y, width, height float64)

DrawExistingImage draws again an image XObject that is already in the builder's document, for instance one found on a page: the stream must be an indirect object of that document with /Subtype /Image. Another document's stream, an inline image, or anything else is ErrArgument.

func (*ContentBuilder) DrawForm

func (b *ContentBuilder) DrawForm(f *FormXObject)

DrawForm draws a form made by this document or writer. It is positioned by the current transformation matrix: Translate, Scale and Rotate first.

func (*ContentBuilder) DrawGlyphRun

func (b *ContentBuilder) DrawGlyphRun(x, y float64, glyphs []ShapedGlyph, text string) float64

DrawGlyphRun draws glyphs a shaping engine has already chosen and placed, starting at the pen position (x, y), with the current font, which must be an embedded font. text is the string the glyphs were shaped from. The result is the total advance of the run in text units.

Glyphs go in drawing order, left to right on the page, so right-to-left text is given in visual order. Text extraction returns the characters in logical order: a glyph that alone stands for its cluster is mapped to that text, and a cluster of several glyphs is wrapped in an ActualText span. A cluster index outside the text, or a glyph the font does not have, is ErrArgument.

func (*ContentBuilder) DrawImage

func (b *ContentBuilder) DrawImage(img *CreatedImage, x, y, width, height float64)

DrawImage places an image in the box with lower left corner (x, y) and the given size, in the current coordinates.

func (*ContentBuilder) DrawText

func (b *ContentBuilder) DrawText(text string, x, y float64)

DrawText shows text with the start of its baseline at (x, y). Nothing is shaped: no kerning, ligatures, contextual forms or reordering; characters go one after another in the order of the string. Control characters are skipped. A character the font cannot show is replaced and noted in the document's diagnostics.

func (*ContentBuilder) DrawTextAligned

func (b *ContentBuilder) DrawTextAligned(text string, x, y, width float64, align TextAlignment)

DrawTextAligned shows one line of text in the span from x to x+width, on the baseline at y. Justify, for a single line, is the same as left.

func (*ContentBuilder) DrawTextBox

func (b *ContentBuilder) DrawTextBox(text string, x, y, width, height float64, align TextAlignment, lineSpacing float64) string

DrawTextBox wraps text into the box with lower left corner (x, y) and the given size, and draws what fits. The first baseline is one ascent of the font below the top of the box and lines are the font size times lineSpacing apart; a line that would reach below the bottom is left out. It returns the text that did not fit, from the start of the first line left out, or "" when everything fit.

Example
package main

import (
	"fmt"

	"recursiveai.org/go/onepdf"
)

func main() {
	doc, _ := onepdf.New()
	doc.InsertBlankPage(0, 200, 200)
	font, _ := doc.AddStandardFont(onepdf.FontCourier)
	pc, _ := doc.BeginContent(0, onepdf.PlaceOver)
	pc.SetFont(font, 10)
	// The box is 60 points wide and 40 high: three lines of 1.2 times the font size fit.
	rest := pc.DrawTextBox("aaaa bbbb cccc dddd eeee ffff gggg hhhh", 10, 110, 60, 40, onepdf.AlignLeft, 1.2)
	pc.Commit()
	fmt.Printf("did not fit: %q\n", rest)
}
Output:
did not fit: "gggg hhhh"

func (*ContentBuilder) DrawTextMatrix

func (b *ContentBuilder) DrawTextMatrix(text string, m device.Matrix)

DrawTextMatrix is DrawText with a full text matrix m, which scales, rotates and skews the text as well as placing it.

func (*ContentBuilder) Ellipse

func (b *ContentBuilder) Ellipse(x, y, width, height float64)

Ellipse adds a closed ellipse inscribed in the rectangle at (x, y) of the given size, as four Bézier curves starting at its rightmost point and going counter-clockwise.

func (*ContentBuilder) EndMarkedContent

func (b *ContentBuilder) EndMarkedContent()

EndMarkedContent ends the innermost sequence. With none open, or when a Save was made inside it, it is ErrNotEditable.

func (*ContentBuilder) EndPath

func (b *ContentBuilder) EndPath()

EndPath ends the current path without painting it.

func (*ContentBuilder) Err

func (b *ContentBuilder) Err() error

Err returns the first error a call recorded, or nil.

func (*ContentBuilder) Fill

func (b *ContentBuilder) Fill(rule device.FillRule)

Fill fills the current path with the fill colour by the given rule (device.NonZero, the nonzero winding rule, or device.EvenOdd; ISO 32000-2 8.5.3.3.2) and ends it. The zero rule is the nonzero one.

func (*ContentBuilder) FillRectangle

func (b *ContentBuilder) FillRectangle(x, y, width, height float64, g *Gradient)

FillRectangle fills the rectangle at (x, y) with the gradient: it clips to the rectangle and paints the gradient, inside a Save and Restore.

func (*ContentBuilder) FillStroke

func (b *ContentBuilder) FillStroke(rule device.FillRule)

FillStroke fills the current path by the given rule, strokes it and ends it. The two paint as one knockout group (ISO 32000-2 11.7.4.4).

func (*ContentBuilder) Font

func (b *ContentBuilder) Font() CreatedFont

Font returns the font set by SetFont, or nil.

func (*ContentBuilder) FontSize

func (b *ContentBuilder) FontSize() float64

FontSize returns the size set by SetFont, or 0.

func (*ContentBuilder) IsClosed

func (b *ContentBuilder) IsClosed() bool

IsClosed reports whether the builder was committed or closed; a closed builder takes no more calls.

func (*ContentBuilder) LineTo

func (b *ContentBuilder) LineTo(x, y float64)

LineTo adds a straight line to (x, y).

func (*ContentBuilder) MarkedContentDepth

func (b *ContentBuilder) MarkedContentDepth() int

MarkedContentDepth is the number of marked-content sequences begun and not yet ended.

func (*ContentBuilder) MeasureText

func (b *ContentBuilder) MeasureText(text string) float64

MeasureText returns the width of text in the current font, size and spacing: character spacing after every character and word spacing after every space. Without a font it is ErrNotEditable and returns 0.

func (*ContentBuilder) MoveTo

func (b *ContentBuilder) MoveTo(x, y float64)

MoveTo begins a new subpath at (x, y).

func (*ContentBuilder) PaintGradient

func (b *ContentBuilder) PaintGradient(g *Gradient)

PaintGradient paints the gradient over the whole current clipping region (the sh operator). The current fill opacity applies. To fill a shape, clip to it first.

func (*ContentBuilder) Rectangle

func (b *ContentBuilder) Rectangle(x, y, width, height float64)

Rectangle adds a closed rectangle with its lower left corner at (x, y). A negative width or height extends it to the left or down.

func (*ContentBuilder) Restore

func (b *ContentBuilder) Restore()

Restore pops the graphics state (Q). With nothing saved, or inside a marked-content sequence begun after the matching Save, it is ErrNotEditable.

func (*ContentBuilder) Rotate

func (b *ContentBuilder) Rotate(degrees float64)

Rotate turns later coordinates counter-clockwise by degrees about the origin. Multiples of 90 are exact.

func (*ContentBuilder) Save

func (b *ContentBuilder) Save()

Save pushes the graphics state (q). Every Save needs a Restore; Commit closes the ones left open.

func (*ContentBuilder) Scale

func (b *ContentBuilder) Scale(sx, sy float64)

Scale scales by (sx, sy) about the origin.

func (*ContentBuilder) SetBlendMode

func (b *ContentBuilder) SetBlendMode(m BlendMode)

SetBlendMode sets the blend mode.

func (*ContentBuilder) SetCharacterSpacing

func (b *ContentBuilder) SetCharacterSpacing(v float64)

SetCharacterSpacing adds space after every character (Tc), in text units.

func (*ContentBuilder) SetDash

func (b *ContentBuilder) SetDash(lengths []float64, phase float64)

SetDash sets the dash pattern: alternating dash and gap lengths, starting phase units in. No lengths gives a solid line. Lengths cannot be negative and cannot all be zero.

func (*ContentBuilder) SetFillCMYK

func (b *ContentBuilder) SetFillCMYK(c, m, y, k float64)

SetFillCMYK sets the fill colour in DeviceCMYK; components are clamped to 0..1.

func (*ContentBuilder) SetFillGray

func (b *ContentBuilder) SetFillGray(g float64)

SetFillGray sets the fill colour in DeviceGray; components are clamped to 0..1.

func (*ContentBuilder) SetFillOpacity

func (b *ContentBuilder) SetFillOpacity(a float64)

SetFillOpacity sets the fill and image opacity (/ca), 0 to 1; values outside are clamped.

func (*ContentBuilder) SetFillRGB

func (b *ContentBuilder) SetFillRGB(r, g, bl float64)

SetFillRGB sets the fill colour in DeviceRGB; components are clamped to 0..1.

func (*ContentBuilder) SetFillRegistration

func (b *ContentBuilder) SetFillRegistration()

SetFillRegistration sets the fill colour to the registration colour, which prints on every plate of a separated job: the Separation colour space /All at full tint with DeviceGray as alternate (ISO 32000-2 8.6.6.4).

func (*ContentBuilder) SetFont

func (b *ContentBuilder) SetFont(f CreatedFont, size float64)

SetFont selects the font and size for the text methods. The font must come from the document or writer the builder draws into, and the size must be a positive finite number; otherwise it is ErrArgument.

func (*ContentBuilder) SetLineCap

func (b *ContentBuilder) SetLineCap(c LineCap)

SetLineCap sets the line cap.

func (*ContentBuilder) SetLineJoin

func (b *ContentBuilder) SetLineJoin(j LineJoin)

SetLineJoin sets the line join.

func (*ContentBuilder) SetLineWidth

func (b *ContentBuilder) SetLineWidth(w float64)

SetLineWidth sets the stroke width. A negative width is ErrArgument.

func (*ContentBuilder) SetMiterLimit

func (b *ContentBuilder) SetMiterLimit(limit float64)

SetMiterLimit sets the miter limit, which must be at least 1.

func (*ContentBuilder) SetOpacity

func (b *ContentBuilder) SetOpacity(a float64)

SetOpacity sets both the fill and the stroke opacity.

func (*ContentBuilder) SetSoftMask

func (b *ContentBuilder) SetSoftMask(form *FormXObject, kind SoftMaskKind)

SetSoftMask sets a soft mask taken from form until ClearSoftMask or the matching Restore. The form is drawn in the coordinates current now.

func (*ContentBuilder) SetStrokeCMYK

func (b *ContentBuilder) SetStrokeCMYK(c, m, y, k float64)

SetStrokeCMYK sets the stroke colour in DeviceCMYK.

func (*ContentBuilder) SetStrokeGray

func (b *ContentBuilder) SetStrokeGray(g float64)

SetStrokeGray sets the stroke colour in DeviceGray.

func (*ContentBuilder) SetStrokeOpacity

func (b *ContentBuilder) SetStrokeOpacity(a float64)

SetStrokeOpacity sets the stroke opacity (/CA), 0 to 1.

func (*ContentBuilder) SetStrokeRGB

func (b *ContentBuilder) SetStrokeRGB(r, g, bl float64)

SetStrokeRGB sets the stroke colour in DeviceRGB.

func (*ContentBuilder) SetStrokeRegistration

func (b *ContentBuilder) SetStrokeRegistration()

SetStrokeRegistration sets the stroke colour to the registration colour.

func (*ContentBuilder) SetTextRenderMode

func (b *ContentBuilder) SetTextRenderMode(m TextRenderMode)

SetTextRenderMode sets how text is painted: with the fill colour, and with the stroke colour and line width in the stroking modes.

func (*ContentBuilder) SetWordSpacing

func (b *ContentBuilder) SetWordSpacing(v float64)

SetWordSpacing adds space after every space character (Tw).

func (*ContentBuilder) ShowGlyphRun

func (b *ContentBuilder) ShowGlyphRun(x, y float64, glyphs []ShapedGlyph, text string) float64

ShowGlyphRun draws shaped glyphs like DrawGlyphRun, but writes the run as one text object with one TJ operator, where kerning, mark offsets and justification become TJ adjustments. A run is then one text-showing operation to a reader, as a line of text is to a person. The font must be embedded (AddFont); glyph advances, offsets and clusters mean what they mean for DrawGlyphRun, with the pen starting at x.

A run that raises or lowers glyphs (a DY other than 0), or that is drawn with character or word spacing set, falls back to DrawGlyphRun's one text object per glyph. It returns the total advance in text units.

func (*ContentBuilder) Stroke

func (b *ContentBuilder) Stroke()

Stroke strokes the current path with the stroke colour and line settings and ends it.

func (*ContentBuilder) Transform

func (b *ContentBuilder) Transform(m device.Matrix)

Transform multiplies the current transformation matrix by m (ISO 32000-2 8.3.4): later coordinates are mapped through it first. The matrix must be finite.

func (*ContentBuilder) Translate

func (b *ContentBuilder) Translate(tx, ty float64)

Translate moves the origin by (tx, ty).

func (*ContentBuilder) WrapText

func (b *ContentBuilder) WrapText(text string, width float64) []string

WrapText splits text into lines that fit in width with the current font, size and spacing. It breaks at spaces and at line feeds, and a word wider than the line is broken between characters. Without a font it is ErrNotEditable and returns nil.

Example
package main

import (
	"fmt"

	"recursiveai.org/go/onepdf"
)

func main() {
	doc, _ := onepdf.New()
	doc.InsertBlankPage(0, 200, 200)
	font, _ := doc.AddStandardFont(onepdf.FontCourier)
	pc, _ := doc.BeginContent(0, onepdf.PlaceOver)
	pc.SetFont(font, 10) // Courier is 6 points a character at size 10
	fmt.Printf("%q\n", pc.WrapText("aaaa bbbb cccc dd", 60))
	fmt.Printf("%q\n", pc.WrapText("abcdefghijklmnop", 60))
	pc.Close()
}
Output:
["aaaa bbbb" "cccc dd"]
["abcdefghij" "klmnop"]

type ContentPlacement

type ContentPlacement int

ContentPlacement says where new content goes relative to a page's own.

const (
	// PlaceOver puts new content after the page's own, so it draws on top.
	PlaceOver ContentPlacement = iota
	// PlaceUnder puts new content before the page's own, so it draws below.
	PlaceUnder
)

The placements. Over is the default.

func (ContentPlacement) String

func (p ContentPlacement) String() string

String returns "Over" or "Under".

type ContextImageDecoder

type ContextImageDecoder interface {
	ImageDecoder
	DecodeImageContext(ctx context.Context, req *ImageRequest) (*DecodedImage, error)
}

ContextImageDecoder is an optional extension of ImageDecoder: a decoder that implements it is called through DecodeImageContext, so it can stop early when ctx is done and return ctx.Err(). A decoder written without it is still called through DecodeImage, after a check of the context.

type CreatedFont

type CreatedFont interface {
	// BaseFontName is the name the font dictionary carries as /BaseFont.
	BaseFontName() string
	// Ascent is the distance from the baseline to the top of the tallest
	// letters, in em (1 = the font size).
	Ascent() float64
	// Descent is the distance from the baseline to the bottom of the lowest
	// letters, in em; it is zero or negative.
	Descent() float64
	// MeasureText is the width of text in a font of the given size, without
	// character or word spacing. Characters the font cannot show count as the
	// character it shows in their place. An empty string measures 0.
	MeasureText(text string, size float64) float64
	// contains filtered or unexported methods
}

CreatedFont is a font a content builder draws with. A document or a streaming writer makes one with AddStandardFont or AddFont; it can only be used with the document or writer that made it.

Text is not shaped: characters are placed one after another in the order of the string, using the font's character map and advance widths.

type CreatedImage

type CreatedImage struct {
	// contains filtered or unexported fields
}

CreatedImage is an image XObject a document or writer holds, ready to be drawn with ContentBuilder.DrawImage any number of times. It can only be used with the document or writer that made it.

func (*CreatedImage) HasAlpha

func (i *CreatedImage) HasAlpha() bool

HasAlpha reports whether the image carries transparency: a soft mask or a colour-key mask.

func (*CreatedImage) Height

func (i *CreatedImage) Height() int

Height is the image's height in pixels.

func (*CreatedImage) Ref

func (i *CreatedImage) Ref() Ref

Ref is the reference of the image XObject.

func (*CreatedImage) Width

func (i *CreatedImage) Width() int

Width is the image's width in pixels.

type DecodedImage

type DecodedImage struct {
	// Width and Height are the pixel size.
	Width, Height int
	// Components counts the colour channels, not an alpha channel.
	Components int
	// BitsPerComponent is 1, 2, 4, 8 or 16.
	BitsPerComponent int
	// Samples are the channels interleaved per pixel, rows padded to a whole
	// number of bytes, most significant bit first, 16-bit samples big-endian.
	// DCT: the components as stored in the file after the YCbCr or YCCK
	// transform the file asks for (CMYK is not inverted). JPX: the channels
	// of the codestream. JBIG2: one bit per pixel with 1 for black, as JBIG2
	// itself has it; onepdf inverts it to the PDF convention.
	Samples []byte
	// HasAlpha says each pixel carries one more channel after the colour
	// channels: opacity, as a JPX codestream with an alpha channel has.
	HasAlpha bool
	// AdobeTransform is the transform flag of a DCT stream's Adobe APP14
	// marker (0, 1 or 2) when HasAdobe is set. It is reported, not applied.
	AdobeTransform int
	HasAdobe       bool
	// Space is the colour space the codestream itself declares, for a decoder
	// that knows one: a JPEG 2000 colour specification box (ISO/IEC 15444-1
	// I.5.3.3), built with [JPXImageSpace], or any ImageSpace whose
	// Components equals Components above. It is used only when the image
	// dictionary has no /ColorSpace, as ISO 32000-2 8.9.5.3 says; with one,
	// the dictionary wins. Nil means the device space with Components channels.
	Space *ImageSpace
}

DecodedImage is what a decoder returns: raw samples, with no PDF semantics applied. onepdf applies /Decode, colour keys, masks and the Adobe CMYK handling itself, so a decoder must not.

type Destination

type Destination struct {
	// Fit is the view type: "XYZ", "Fit", "FitH", "FitV", "FitR", "FitB", "FitBH"
	// or "FitBV"; "" when the destination names none.
	Fit string
	// Name is the named destination this was looked up by, or "".
	Name string
	// Page is the zero-based index of the target page. It is -1 when the
	// destination names no page of this document, for instance a reference to
	// an object that is not a page. For a Remote destination it is the page
	// number in the other file, as stored.
	Page int
	// Remote reports that the destination is in another file (a GoToR action);
	// Page is then that file's page number, or Name says which named
	// destination to use there.
	Remote bool
	// Structure reports a structure destination (ISO 32000-2 12.3.2.3): it
	// names a structure element instead of a page.
	Structure bool
	// StructElem is the structure element of a structure destination.
	StructElem *Dict
	// Left, Bottom, Right and Top are the view's edges, and Zoom the
	// magnification, for the fits that use them; the rest stay invalid.
	// A null parameter is invalid too.
	Left, Bottom, Right, Top, Zoom Opt[float64]
}

Destination is where a link, outline item or action leads (ISO 32000-2 12.3.2): a page and a view of it.

type DiagSeverity

type DiagSeverity int

DiagSeverity ranks a Diagnostic.

const (
	// DiagInfo notes something unusual that is not damage, such as bytes before the header.
	DiagInfo DiagSeverity = iota
	// DiagWarning marks damage that was repaired. With WithStrict it becomes an error.
	DiagWarning
	// DiagError marks data that could not be used and reads as null.
	DiagError
)

Diagnostic severities.

func (DiagSeverity) String

func (s DiagSeverity) String() string

String returns "info", "warning" or "error".

type Diagnostic

type Diagnostic struct {
	// Severity is DiagInfo for a note that needs no action, DiagWarning for a
	// repair of damage, or DiagError for data that could not be used.
	Severity DiagSeverity
	// Object is the object number concerned, or -1.
	Object int
	// Offset is a byte offset in the source, or -1.
	Offset int64
	// Message describes the problem in plain words.
	Message string
}

Diagnostic records something unusual the reader worked around.

type Dict

type Dict struct {
	// contains filtered or unexported fields
}

Dict is a PDF dictionary (7.3.7). Entries keep the order of the file. A key given twice keeps its first position and its last value. An entry whose value is null is treated as absent (ISO 32000-2 7.3.7).

func ListAttributes

func ListAttributes(numbering string) *Dict

ListAttributes is the attribute object of a list: its numbering, such as "Decimal", "Disc" or "None" (ISO 32000-2 14.8.5.4).

func NewDict

func NewDict() *Dict

NewDict returns an empty dictionary that belongs to no document.

func TableAttributes

func TableAttributes(colSpan, rowSpan int) *Dict

TableAttributes is the attribute object of a TD cell: its spans.

func TableHeaderAttributes

func TableHeaderAttributes(scope string, colSpan, rowSpan int) *Dict

TableHeaderAttributes is the attribute object of a TH cell: its scope ("Row", "Column" or "Both") and spans (ISO 32000-2 14.8.5.7).

func (*Dict) All

func (d *Dict) All() iter.Seq2[string, Object]

All yields every entry as stored, in file order.

func (*Dict) Array

func (d *Dict) Array(key string) *Array

Array returns the value of key when it is an array, and nil otherwise.

func (*Dict) Bool

func (d *Dict) Bool(key string) (b bool, ok bool)

Bool returns the value of key when it is a boolean; ok is false for any other type.

func (*Dict) BoolOr

func (d *Dict) BoolOr(key string, def bool) bool

BoolOr returns the value of key when it is a boolean, and def otherwise.

func (*Dict) Delete

func (d *Dict) Delete(key string) error

Delete removes key and records the change. Removing a key that is absent is not an error. It fails like Set on a document that cannot be edited.

func (*Dict) Dict

func (d *Dict) Dict(key string) *Dict

Dict returns the value of key when it is a dictionary, or the dictionary of a stream; otherwise nil.

func (*Dict) Get

func (d *Dict) Get(key string) Object

Get returns the value of key with references followed. A missing key, a null value and a reference to nothing give nil.

Example
package main

import (
	"bytes"
	"fmt"

	"recursiveai.org/go/onepdf"
)

// examplePDF writes a two-page file with an incremental update that adds the second page.
func examplePDF() []byte {
	var b bytes.Buffer
	b.WriteString("%PDF-1.7\n")
	offs := map[int]int{}
	obj := func(n int, body string) {
		offs[n] = b.Len()
		fmt.Fprintf(&b, "%d 0 obj\n%s\nendobj\n", n, body)
	}
	obj(1, "<</Type /Catalog/Pages 2 0 R/Lang (en)>>")
	obj(2, "<</Type /Pages/Kids [3 0 R]/Count 1>>")
	obj(3, "<</Type /Page/Parent 2 0 R/MediaBox [0 0 612 792.5]>>")
	first := b.Len()
	fmt.Fprintf(&b, "xref\n0 4\n0000000000 65535 f \n%010d 00000 n \n%010d 00000 n \n%010d 00000 n \ntrailer\n<</Size 4/Root 1 0 R>>\nstartxref\n%d\n%%%%EOF\n", offs[1], offs[2], offs[3], first)
	obj(2, "<</Type /Pages/Kids [3 0 R 4 0 R]/Count 2>>")
	obj(4, "<</Type /Page/Parent 2 0 R/MediaBox [0 0 100 100]>>")
	second := b.Len()
	fmt.Fprintf(&b, "xref\n2 1\n%010d 00000 n \n4 1\n%010d 00000 n \ntrailer\n<</Size 5/Root 1 0 R/Prev %d>>\nstartxref\n%d\n%%%%EOF\n", offs[2], offs[4], first, second)
	return b.Bytes()
}

func main() {
	doc, _ := onepdf.OpenBytes(examplePDF())
	page, _ := doc.Object(3)
	box := page.(*onepdf.Dict).Array("MediaBox")
	fmt.Println(box.Len(), box.Int(2, 0), box.Real(3, 0))
	// A reference is followed by Get and kept by Raw.
	fmt.Printf("%T %T\n", page.(*onepdf.Dict).Get("Parent"), page.(*onepdf.Dict).Raw("Parent"))
}
Output:
4 612 792.5
*onepdf.Dict onepdf.Ref

func (*Dict) Has

func (d *Dict) Has(key string) bool

Has reports whether key is present, even with a null value.

func (*Dict) Int

func (d *Dict) Int(key string) (n int64, ok bool)

Int returns the value of key as an integer. A real is truncated toward zero (saturating at the int64 range); ok is false for any other type, a null, a NaN and a missing key.

func (*Dict) IntOr

func (d *Dict) IntOr(key string, def int64) int64

IntOr returns the value of key as an integer. A real is truncated toward zero; any other type, a null and a missing key give def.

func (*Dict) Keys

func (d *Dict) Keys() []string

Keys returns the keys in file order.

func (*Dict) Len

func (d *Dict) Len() int

Len returns the number of entries.

func (*Dict) Name

func (d *Dict) Name(key string) (name Name, ok bool)

Name returns the value of key when it is a name; ok is false for any other type.

func (*Dict) Raw

func (d *Dict) Raw(key string) Object

Raw returns the value of key as stored, a Ref left unresolved. A missing key and a null value give nil.

func (*Dict) Real

func (d *Dict) Real(key string) (f float64, ok bool)

Real returns the value of key as a real; an integer converts. ok is false for any other type, a null and a missing key.

func (*Dict) RealOr

func (d *Dict) RealOr(key string, def float64) float64

RealOr returns the value of key as a real; an integer converts. Anything else gives def.

func (*Dict) Ref

func (d *Dict) Ref() Ref

Ref returns the reference this dictionary was read through, if it is an indirect object's value; otherwise the zero Ref.

func (*Dict) Set

func (d *Dict) Set(key string, v Object) error

Set stores v under key and records the change. A nil v removes the key (a null value is never stored, ISO 32000-2 7.3.7). A dictionary, array or stream that is already an indirect object of the same document is stored as its reference; a stream that belongs to no document is added to this one as a new object and stored as its reference; a direct dictionary or array joins the document (the caller keeps editing it through the same value, and a value already stored elsewhere is copied instead). A value of another document is refused with ErrArgument, copy it first.

On a dictionary that belongs to a document, Set needs a document opened with WithEditing and an object of its newest revision, and returns ErrNotEditable otherwise. On a dictionary that belongs to no document (NewDict), or to a document being built (New), it never fails with ErrNotEditable, as bytes.Buffer.Write never fails: callers building such a value may ignore the error when they pass values of their own.

Example
doc, _ := onepdf.OpenBytes(examplePDF(), onepdf.WithEditing())
page := doc.Catalog().Dict("Pages").Array("Kids").Get(0).(*onepdf.Dict)
fmt.Println(page.Set("Rotate", onepdf.Int(90)))
fmt.Println(page.IntOr("Rotate", 0))

readOnly, _ := onepdf.OpenBytes(examplePDF())
fmt.Println(readOnly.Catalog().Set("Lang", onepdf.TextString("de")))
Output:
<nil>
90
onepdf: the document or object cannot be edited: the document was not opened with WithEditing

func (*Dict) Stream

func (d *Dict) Stream(key string) *Stream

Stream returns the value of key when it is a stream, and nil otherwise.

func (*Dict) Text

func (d *Dict) Text(key string) (s String, ok bool)

Text returns the value of key when it is a PDF string; ok is false for any other type.

type Document

type Document struct {
	// contains filtered or unexported fields
}

Document is an open PDF. It is safe for concurrent reading: any number of goroutines may read objects, pages and streams, interpret, extract text and save at the same time. Objects load lazily from the cross-reference data and are cached. The mutators (Dict.Set and Dict.Delete, the Array and Stream mutators, AddObject, SetObject, RemoveObject, SetInfo, SetXMP, the page operations, form filling and the content-creation calls) are not safe while another goroutine reads or saves the same document, Save included.

A Document built from OpenFile holds the file open until Close.

func Merge

func Merge(docs []*Document, opts ...ImportOption) (*Document, error)

Merge returns a new document holding all pages of docs in order. Each source is imported as ImportPages does, with the same options; the result is a PDF 1.7 document in memory with no document information (set it with SetInfo), and its limits are those of the first source. The sources are not changed and may be closed once Merge returns. At least one source is needed, else ErrArgument.

Example
package main

import (
	"fmt"

	"recursiveai.org/go/onepdf"
)

// pagesOfWidths returns an editable document whose pages are as wide as the arguments say, which makes
// the page order visible.
func pagesOfWidths(widths ...float64) *onepdf.Document {
	doc, err := onepdf.New()
	if err != nil {
		panic(err)
	}
	for i, w := range widths {
		if err := doc.InsertBlankPage(i, w, 100); err != nil {
			panic(err)
		}
	}
	return doc
}

func widths(doc *onepdf.Document) []float64 {
	var out []float64
	for p := range doc.Pages() {
		out = append(out, p.MediaBox().Width())
	}
	return out
}

func main() {
	a, b := pagesOfWidths(100, 200), pagesOfWidths(300)
	merged, err := onepdf.Merge([]*onepdf.Document{a, b, a})
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(widths(merged))
}
Output:
[100 200 300 100 200]

func MergeContext

func MergeContext(ctx context.Context, docs []*Document, opts ...ImportOption) (*Document, error)

MergeContext is Merge that stops with ctx.Err() when ctx is done.

func New

func New(opts ...Option) (*Document, error)

New returns a new document with no pages, opened for editing: a catalog and an empty page tree, PDF 1.7. Add pages with InsertBlankPage, then save it with Save. The options are those of Open; WithEditing is implied.

Example
package main

import (
	"bytes"
	"fmt"

	"recursiveai.org/go/onepdf"
)

func main() {
	doc, _ := onepdf.New()
	_ = doc.InsertBlankPage(0, 595, 842)
	_ = doc.InsertBlankPage(1, 842, 595)
	_ = doc.SetInfo("Title", "Blank pages")
	var out bytes.Buffer
	_ = doc.Save(&out, onepdf.WithDocumentID([]byte("0123456789ABCDEF")))
	back, _ := onepdf.OpenBytes(out.Bytes())
	fmt.Println(back.Version(), back.PageCount())
}
Output:
1.7 2

func Open

func Open(r io.ReaderAt, size int64, opts ...Option) (*Document, error)

Open reads the document in r, which holds size bytes. The Document reads from r on demand and keeps it until it is garbage; r must stay readable and unchanged. A read that finds r shorter than size fails with ErrSourceChanged.

Open reads the cross-reference data, not the objects: a large file opens fast. The returned error matches ErrFormat, ErrLimit, ErrPassword or ErrEncryption (errors.Is), or comes from r.

func OpenBytes

func OpenBytes(data []byte, opts ...Option) (*Document, error)

OpenBytes reads the document in data. The Document refers to data without copying it, so the caller must not modify it while the Document is in use.

Example
package main

import (
	"bytes"
	"fmt"

	"recursiveai.org/go/onepdf"
)

// examplePDF writes a two-page file with an incremental update that adds the second page.
func examplePDF() []byte {
	var b bytes.Buffer
	b.WriteString("%PDF-1.7\n")
	offs := map[int]int{}
	obj := func(n int, body string) {
		offs[n] = b.Len()
		fmt.Fprintf(&b, "%d 0 obj\n%s\nendobj\n", n, body)
	}
	obj(1, "<</Type /Catalog/Pages 2 0 R/Lang (en)>>")
	obj(2, "<</Type /Pages/Kids [3 0 R]/Count 1>>")
	obj(3, "<</Type /Page/Parent 2 0 R/MediaBox [0 0 612 792.5]>>")
	first := b.Len()
	fmt.Fprintf(&b, "xref\n0 4\n0000000000 65535 f \n%010d 00000 n \n%010d 00000 n \n%010d 00000 n \ntrailer\n<</Size 4/Root 1 0 R>>\nstartxref\n%d\n%%%%EOF\n", offs[1], offs[2], offs[3], first)
	obj(2, "<</Type /Pages/Kids [3 0 R 4 0 R]/Count 2>>")
	obj(4, "<</Type /Page/Parent 2 0 R/MediaBox [0 0 100 100]>>")
	second := b.Len()
	fmt.Fprintf(&b, "xref\n2 1\n%010d 00000 n \n4 1\n%010d 00000 n \ntrailer\n<</Size 5/Root 1 0 R/Prev %d>>\nstartxref\n%d\n%%%%EOF\n", offs[2], offs[4], first, second)
	return b.Bytes()
}

func main() {
	doc, err := onepdf.OpenBytes(examplePDF())
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println("version", doc.Version())
	fmt.Println("pages", doc.PageCount())
	fmt.Println("objects", doc.ObjectCount())
	fmt.Println("revisions", len(doc.Revisions()))
}
Output:
version 1.7
pages 2
objects 5
revisions 2

func OpenBytesContext

func OpenBytesContext(ctx context.Context, data []byte, opts ...Option) (*Document, error)

OpenBytesContext is OpenBytes that stops when ctx is done, as OpenContext does.

func OpenContext

func OpenContext(ctx context.Context, r io.ReaderAt, size int64, opts ...Option) (*Document, error)

OpenContext is Open that stops when ctx is done: reading the structure, and above all rebuilding a large damaged file, checks ctx between reads and then returns ctx's error. Once Open returns, ctx no longer matters.

Example
ctx, cancel := context.WithCancel(context.Background())
cancel() // the caller gave up before the file was read
data := examplePDF()
_, err := onepdf.OpenContext(ctx, bytes.NewReader(data), int64(len(data)))
fmt.Println(errors.Is(err, context.Canceled))
Output:
true

func OpenFile

func OpenFile(path string, opts ...Option) (*Document, error)

OpenFile opens the file at path. The file stays open until Close. If the file's length changes while the Document is open, reads fail with ErrSourceChanged.

Example
package main

import (
	"bytes"
	"fmt"
	"os"
	"path/filepath"

	"recursiveai.org/go/onepdf"
)

// examplePDF writes a two-page file with an incremental update that adds the second page.
func examplePDF() []byte {
	var b bytes.Buffer
	b.WriteString("%PDF-1.7\n")
	offs := map[int]int{}
	obj := func(n int, body string) {
		offs[n] = b.Len()
		fmt.Fprintf(&b, "%d 0 obj\n%s\nendobj\n", n, body)
	}
	obj(1, "<</Type /Catalog/Pages 2 0 R/Lang (en)>>")
	obj(2, "<</Type /Pages/Kids [3 0 R]/Count 1>>")
	obj(3, "<</Type /Page/Parent 2 0 R/MediaBox [0 0 612 792.5]>>")
	first := b.Len()
	fmt.Fprintf(&b, "xref\n0 4\n0000000000 65535 f \n%010d 00000 n \n%010d 00000 n \n%010d 00000 n \ntrailer\n<</Size 4/Root 1 0 R>>\nstartxref\n%d\n%%%%EOF\n", offs[1], offs[2], offs[3], first)
	obj(2, "<</Type /Pages/Kids [3 0 R 4 0 R]/Count 2>>")
	obj(4, "<</Type /Page/Parent 2 0 R/MediaBox [0 0 100 100]>>")
	second := b.Len()
	fmt.Fprintf(&b, "xref\n2 1\n%010d 00000 n \n4 1\n%010d 00000 n \ntrailer\n<</Size 5/Root 1 0 R/Prev %d>>\nstartxref\n%d\n%%%%EOF\n", offs[2], offs[4], first, second)
	return b.Bytes()
}

func main() {
	path := filepath.Join(os.TempDir(), "onepdf-example.pdf")
	if err := os.WriteFile(path, examplePDF(), 0o600); err != nil {
		fmt.Println(err)
		return
	}
	defer os.Remove(path)
	doc, err := onepdf.OpenFile(path)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer doc.Close()
	fmt.Println(doc.PageCount())
}
Output:
2

func OpenFileContext

func OpenFileContext(ctx context.Context, path string, opts ...Option) (*Document, error)

OpenFileContext is OpenFile that stops when ctx is done, as OpenContext does. The file's modification time is compared with the one seen at open at most every 100 ms, besides its length on every read; a change gives ErrSourceChanged.

func OpenReader

func OpenReader(r io.Reader, opts ...Option) (*Document, error)

OpenReader reads all of r into memory and opens it. Use it for a stream that cannot seek. Reading stops with ErrLimit at 2 GiB.

func OpenReaderContext

func OpenReaderContext(ctx context.Context, r io.Reader, opts ...Option) (*Document, error)

OpenReaderContext is OpenReader that stops when ctx is done, both while reading r and while opening the data. It returns ctx's error then.

func Split

func Split(src *Document, ranges ...PageRange) ([]*Document, error)

Split returns one new document per range, each holding those pages as ImportPages copies them. Ranges may overlap and come in any order. A range that is empty or leaves the document is ErrArgument; no document is returned then. The parts do not refer to src.

Example
package main

import (
	"fmt"

	"recursiveai.org/go/onepdf"
)

// pagesOfWidths returns an editable document whose pages are as wide as the arguments say, which makes
// the page order visible.
func pagesOfWidths(widths ...float64) *onepdf.Document {
	doc, err := onepdf.New()
	if err != nil {
		panic(err)
	}
	for i, w := range widths {
		if err := doc.InsertBlankPage(i, w, 100); err != nil {
			panic(err)
		}
	}
	return doc
}

func widths(doc *onepdf.Document) []float64 {
	var out []float64
	for p := range doc.Pages() {
		out = append(out, p.MediaBox().Width())
	}
	return out
}

func main() {
	doc := pagesOfWidths(100, 200, 300, 400)
	// Ranges may come in any order and overlap.
	parts, err := onepdf.Split(doc, onepdf.PageRange{Start: 2, Count: 2}, onepdf.PageRange{Start: 1, Count: 2})
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(widths(parts[0]), widths(parts[1]))
}
Output:
[300 400] [200 300]

func SplitContext

func SplitContext(ctx context.Context, src *Document, ranges ...PageRange) ([]*Document, error)

SplitContext is Split that stops with ctx.Err() when ctx is done.

func SplitEvery

func SplitEvery(src *Document, perPart int) ([]*Document, error)

SplitEvery splits src into parts of perPart pages, the last one possibly shorter. perPart below 1 is ErrArgument. A document with no pages gives no parts.

Example
package main

import (
	"fmt"

	"recursiveai.org/go/onepdf"
)

// pagesOfWidths returns an editable document whose pages are as wide as the arguments say, which makes
// the page order visible.
func pagesOfWidths(widths ...float64) *onepdf.Document {
	doc, err := onepdf.New()
	if err != nil {
		panic(err)
	}
	for i, w := range widths {
		if err := doc.InsertBlankPage(i, w, 100); err != nil {
			panic(err)
		}
	}
	return doc
}

func widths(doc *onepdf.Document) []float64 {
	var out []float64
	for p := range doc.Pages() {
		out = append(out, p.MediaBox().Width())
	}
	return out
}

func main() {
	doc := pagesOfWidths(100, 200, 300, 400, 500)
	parts, err := onepdf.SplitEvery(doc, 2)
	if err != nil {
		fmt.Println(err)
		return
	}
	for _, part := range parts {
		fmt.Println(widths(part))
	}
}
Output:
[100 200]
[300 400]
[500]

func SplitEveryContext

func SplitEveryContext(ctx context.Context, src *Document, perPart int) ([]*Document, error)

SplitEveryContext is SplitEvery that stops with ctx.Err() when ctx is done.

Example
doc, _ := onepdf.OpenBytes(examplePDF())
parts, err := onepdf.SplitEveryContext(context.Background(), doc, 1)
fmt.Println(len(parts), err)
Output:
2 <nil>

func (*Document) Access

func (d *Document) Access() Access

Access reports which password opened the document. A document that is not encrypted reports AccessOwner.

func (*Document) AddFont

func (d *Document) AddFont(file *FontFile, opts ...EmbedOption) (CreatedFont, error)

AddFont embeds a font program for drawing: the document keeps the program whole or, by default, only the glyphs the builders draw, cut down when the document is saved. Text is not shaped; characters map to glyphs through the program's Unicode cmap, and a glyph run (ContentBuilder.DrawGlyphRun) names glyphs directly. The font is written as a Type 0 font with Identity-H, /W and /ToUnicode.

The options are those of NewFontEmbedder: WithSubsetting, WithBaseFontName and WithIgnoreEmbeddingRestrictions. A program whose fsType forbids embedding is refused with a FontEmbedError (reason EmbedProgramForbidsEmbedding) unless the last option is given. The document needs WithEditing. A bare CFF program has no character map and is ErrFormat.

Example
package main

import (
	"bytes"
	"fmt"
	"os"

	"recursiveai.org/go/onepdf"
	"recursiveai.org/go/onepdf/text"
)

func exampleFont(name string) *onepdf.FontFile {
	data, err := os.ReadFile("testdata/embed/" + name)
	if err != nil {
		panic(err)
	}
	f, err := onepdf.OpenFontFile(data, 0)
	if err != nil {
		panic(err)
	}
	return f
}

func main() {
	doc, _ := onepdf.New()
	doc.InsertBlankPage(0, 200, 100)
	font, err := doc.AddFont(exampleFont("kit-text.ttf"))
	if err != nil {
		fmt.Println(err)
		return
	}
	pc, _ := doc.BeginContent(0, onepdf.PlaceOver)
	pc.SetFont(font, 12)
	pc.DrawText("ABC", 10, 50)
	pc.Commit()

	var out bytes.Buffer
	doc.Save(&out) // the font is cut down to A, B, C and .notdef here
	back, _ := onepdf.OpenBytes(out.Bytes())
	page, _ := back.Page(0)
	pt, _ := text.Page(page)
	fmt.Println(pt.Text())
}
Output:
ABC

func (*Document) AddImageStamp

func (d *Document) AddImageStamp(img *CreatedImage, width, height float64, opts ...StampOption) error

AddImageStamp is AddTextStamp for an image drawn width by height points.

func (*Document) AddImageStampContext

func (d *Document) AddImageStampContext(ctx context.Context, img *CreatedImage, width, height float64, opts ...StampOption) error

AddImageStampContext is AddImageStamp that stops with ctx.Err() when ctx is done, between pages. Pages stamped before then keep the stamp.

func (*Document) AddJPEGImage

func (d *Document) AddJPEGImage(data []byte) (*CreatedImage, error)

AddJPEGImage adds a JPEG file as an image, embedded as it is (DCTDecode): the size and the 1, 3 or 4 components are read from the header, Adobe CMYK gets the inverting /Decode array, and progressive files are fine. Arithmetic-coded, lossless and hierarchical files are ErrUnsupported; a damaged file is ErrFormat.

func (*Document) AddMissingToUnicode

func (d *Document) AddMissingToUnicode(opts ...ToUnicodeOption) (*ToUnicodeReport, error)

AddMissingToUnicode writes /ToUnicode entries for the codes the pages show with each font whose encoding does not say what its codes mean (a /Differences array, a symbolic font, an Identity-encoded Type 0 font), taking each text from the chain text extraction uses: the encoding's glyph names through the Adobe Glyph List, then the embedded program's character map. A code the chain cannot read gets no entry (nothing is guessed) and is listed in CodesWithoutUnicode, unless WithToUnicodeChooser gives it text. Fonts whose encoding already determines Unicode, and Type 3 fonts, are skipped and not listed. Existing entries stay. The document must be editable.

func (*Document) AddMissingToUnicodeContext

func (d *Document) AddMissingToUnicodeContext(ctx context.Context, opts ...ToUnicodeOption) (*ToUnicodeReport, error)

AddMissingToUnicodeContext is AddMissingToUnicode that stops with ctx.Err() when ctx is done: while it scans the objects, while it reads the pages for the codes they show, and between fonts. Fonts already given their map keep it; nothing is half written.

func (*Document) AddObject

func (d *Document) AddObject(v Object) (Ref, error)

AddObject stores v as a new indirect object, with the next free number and generation 0, and returns its reference. v is a dictionary, array, stream or a simple value; a stream that belongs to no document becomes this document's. A reference cannot be an object's value and nil cannot be stored; both are ErrArgument. An object that is already an indirect object of this document returns its own reference.

func (*Document) AddPNGImage

func (d *Document) AddPNGImage(data []byte) (*CreatedImage, error)

AddPNGImage adds a PNG file as an image. It is a minimal reader, not a codec: it reads what a PDF image needs and writes nothing.

Gray (1 to 16 bits), RGB (8, 16) and palette (1 to 8) images without interlacing are passed through: the IDAT data goes into a Flate stream with PNG predictors (ISO 32000-2 7.4.4.4), byte for byte. Palettes become /Indexed over DeviceRGB, padded to 2^bits entries. Adam7 images are decoded and stored as plain rows. Gray+alpha and RGB+alpha images are decoded; the colour samples are stored as above and alpha becomes a soft mask of the same bit depth. A tRNS chunk on gray or RGB becomes a colour-key mask; on a palette it becomes one when the transparent entries are fully transparent and form one run, and an 8-bit soft mask built from the indices otherwise. An iCCP profile of the matching colour space becomes an ICCBased space.

Gamma, chromaticity and the other ancillary chunks are ignored and samples are used as stored; animation frames are ignored. A CRC mismatch in IHDR, PLTE or IDAT is ErrFormat; in tRNS or iCCP the chunk is dropped with a warning in Diagnostics. The pixel count and decoded size are checked against the limits from the header, before any pixel memory is allocated.

Example
package main

import (
	"bytes"
	"fmt"
	"image"
	"image/png"

	"recursiveai.org/go/onepdf"
)

func main() {
	var pngData bytes.Buffer
	png.Encode(&pngData, image.NewNRGBA(image.Rect(0, 0, 5, 4)))

	doc, _ := onepdf.New()
	doc.InsertBlankPage(0, 200, 100)
	img, err := doc.AddPNGImage(pngData.Bytes())
	if err != nil {
		fmt.Println(err)
		return
	}
	pc, _ := doc.BeginContent(0, onepdf.PlaceOver)
	pc.DrawImage(img, 10, 10, 50, 40)
	pc.Commit()
	fmt.Println(img.Width(), img.Height(), img.HasAlpha())
}
Output:
5 4 true

func (*Document) AddRawImage

func (d *Document) AddRawImage(width, height int, color ImageColor, samples, alpha []byte) (*CreatedImage, error)

AddRawImage adds an image from 8-bit samples: Gray, RGB or CMYK, interleaved, rows top to bottom, with an optional 8-bit alpha plane of width*height bytes (stored as a soft mask). The data is Flate-compressed. A size that does not match the samples is ErrArgument; more pixels than the limits allow is ErrLimit.

func (*Document) AddStandardFont

func (d *Document) AddStandardFont(font StandardFont) (CreatedFont, error)

AddStandardFont adds one of the 14 standard fonts, which are not embedded: Courier, Helvetica and Times-Roman in four styles each, Symbol and ZapfDingbats. ParseStandardFont maps names and the usual aliases (Arial, ArialMT, "Arial,Bold", TimesNewRoman, CourierNew, ...) to them. Text is WinAnsi; Symbol and ZapfDingbats use their built-in encodings. Widths come from the Adobe Core 14 metrics; a viewer draws with its own copy of the font. A character outside the encoding is drawn as "?" and noted in Diagnostics.

A value that is not one of the 14 is ErrArgument. The document needs WithEditing.

func (*Document) AddTextStamp

func (d *Document) AddTextStamp(text string, font CreatedFont, size float64, opts ...StampOption) error

AddTextStamp draws text in the font and size on pages, one shared form placed on each of them (every page when none are given), centred on the crop box (or at the options' centre), rotated, at an opacity and blend mode, over or under the content. The text is not shaped. Page indexes out of range are ErrArgument.

Example
package main

import (
	"fmt"

	"recursiveai.org/go/onepdf"
)

func main() {
	doc, _ := onepdf.New()
	doc.InsertBlankPage(0, 200, 100)
	doc.InsertBlankPage(1, 200, 100)
	font, _ := doc.AddStandardFont(onepdf.FontHelveticaBold)
	// One shared form, placed on every page, centred, tilted and see-through.
	err := doc.AddTextStamp("DRAFT", font, 48, onepdf.WithStampOpacity(0.25), onepdf.WithStampRotation(45), onepdf.WithStampColor(1, 0, 0))
	fmt.Println("stamped:", err == nil)
}
Output:
stamped: true

func (*Document) AddTextStampContext

func (d *Document) AddTextStampContext(ctx context.Context, text string, font CreatedFont, size float64, opts ...StampOption) error

AddTextStampContext is AddTextStamp that stops with ctx.Err() when ctx is done, between pages. Pages stamped before then keep the stamp.

func (*Document) AttachFile

func (d *Document) AttachFile(a Attachment) (Ref, error)

AttachFile embeds a file: a Flate-compressed embedded-file stream with its size, MD5 check sum and dates, a file specification with /F, /UF, /EF, /Desc and /AFRelationship, an entry in the catalog's /Names /EmbeddedFiles name tree (kept sorted by name; an existing entry of the same name is replaced) and an entry in the catalog's /AF array. It returns the reference of the file specification.

An empty name, or a relationship that is not one of the constants, is ErrArgument; it needs a document opened with WithEditing.

Example
doc, _ := onepdf.OpenBytes(examplePDF(), onepdf.WithEditing())
_, err := doc.AttachFile(onepdf.Attachment{Name: "data.xml", Data: []byte("<a/>"), MIMEType: "text/xml", Relationship: onepdf.RelData})
if err != nil {
	fmt.Println(err)
	return
}
names := doc.Catalog().Dict("Names").Dict("EmbeddedFiles").Array("Names")
fmt.Println(names.Get(0).(onepdf.String))
Output:
data.xml

func (*Document) Attachments

func (d *Document) Attachments() iter.Seq[*EmbeddedFile]

Attachments iterates over every attached file: the files of the name tree that EmbeddedFiles lists, then the files of file-attachment annotations page by page (their Page field says which). Use EmbeddedFiles for the name tree alone.

func (*Document) BeginContent

func (d *Document) BeginContent(pageIndex int, placement ContentPlacement) (*PageContent, error)

BeginContent starts drawing on page pageIndex. With PlaceOver (the default) the page's own content stays byte for byte as it was, but is wrapped in q and Q, with one extra Q per q it leaves open (found by a lexical scan), so a stray cm, colour, clip or unbalanced q cannot reach what is drawn. PlaceUnder puts the new content first, in its own saved state. Either way the new content is a new stream added to the page's /Contents array, and the shared q and Q streams are made once per document.

Fonts, XObjects, graphics states and shadings the content names go into a page-owned copy of the resource dictionary when the page's was inherited or shared, so other pages are not touched. Names are OpF1, OpFm1, OpGs1, ..., skipping any name already in use.

An index out of range is ErrArgument; a document not opened with WithEditing is ErrNotEditable.

Example
package main

import (
	"fmt"

	"recursiveai.org/go/onepdf"
	"recursiveai.org/go/onepdf/device"
)

func main() {
	doc, _ := onepdf.New()
	doc.InsertBlankPage(0, 200, 100)
	font, _ := doc.AddStandardFont(onepdf.FontCourier)

	pc, _ := doc.BeginContent(0, onepdf.PlaceOver)
	pc.SetFillRGB(0.1, 0.1, 0.5)
	pc.Rectangle(10, 10, 180, 2)
	pc.Fill(device.NonZero)
	pc.SetFillGray(0)
	pc.SetFont(font, 12)
	pc.DrawText("Hello", 10, 50)
	if err := pc.Commit(); err != nil { // nothing reaches the page before this
		fmt.Println(err)
		return
	}

	page, _ := doc.Page(0)
	content, _ := page.Contents()[0].Decode()
	fmt.Printf("%s", content)
}
Output:
0.1 0.1 0.5 rg
10 10 180 2 re
f
0 g
/OpF1 12 Tf
BT
1 0 0 1 10 50 Tm
(Hello) Tj
ET

func (*Document) BeginForm

func (d *Document) BeginForm(bbox Rect) (*FormContent, error)

BeginForm starts a new form with the given bounding box in form space. The box must be finite and not empty (ErrArgument otherwise).

func (*Document) Catalog

func (d *Document) Catalog() *Dict

Catalog returns the document catalog the trailer's /Root names, or nil if it is not a dictionary.

func (*Document) Close

func (d *Document) Close() error

Close releases the file a Document from OpenFile holds. It is safe to call more than once and on any Document; the Document must not be used after.

func (*Document) Destination

func (d *Document) Destination(o Object) *Destination

Destination reads a destination object: an explicit array, a dictionary with /D, or a name or string looked up among the named destinations. It returns nil when o is none of these or names nothing known.

func (*Document) Diagnostics

func (d *Document) Diagnostics() []Diagnostic

Diagnostics returns what the reader noticed and worked around, in the order found.

func (*Document) DuplicatePage

func (d *Document) DuplicatePage(index int) error

DuplicatePage inserts a copy of the page right after it. The copy has its own annotation objects and shares content and resources with the original; a widget joins its field as one more widget. An index out of range is ErrArgument. Views taken earlier are out of date afterwards.

Example
package main

import (
	"fmt"

	"recursiveai.org/go/onepdf"
)

// pagesOfWidths returns an editable document whose pages are as wide as the arguments say, which makes
// the page order visible.
func pagesOfWidths(widths ...float64) *onepdf.Document {
	doc, err := onepdf.New()
	if err != nil {
		panic(err)
	}
	for i, w := range widths {
		if err := doc.InsertBlankPage(i, w, 100); err != nil {
			panic(err)
		}
	}
	return doc
}

func widths(doc *onepdf.Document) []float64 {
	var out []float64
	for p := range doc.Pages() {
		out = append(out, p.MediaBox().Width())
	}
	return out
}

func main() {
	doc := pagesOfWidths(100, 200)
	if err := doc.DuplicatePage(0); err != nil {
		fmt.Println(err)
	}
	fmt.Println(widths(doc))
}
Output:
[100 100 200]

func (*Document) Editable

func (d *Document) Editable() bool

Editable reports whether the document was opened with WithEditing.

func (*Document) EmbedFontProgram

func (d *Document) EmbedFontProgram(font *Dict, file *FontFile, opts ...EmbedOption) (*FontEmbedResult, error)

EmbedFontProgram puts a TrueType program into a font dictionary that has none, so the file satisfies ISO 14289-1 7.21.4.1 and ISO 19005-2 6.2.11.4.1 without any text moving. The document must be editable.

A simple font (Type1, MMType1 or TrueType) becomes /TrueType, each code is mapped to a glyph through the font's encoding (a glyph name, then its Unicode through the Adobe Glyph List, then the program's cmap) or, for a symbolic font, through the program's (3,0) cmap, and the subset gets cmaps that make a reader choose the same glyphs (ISO 32000-2 9.6.5.4). A Type 0 font with an Identity encoding and a CIDFontType2 descendant gets a /CIDToGIDMap; its character ids are glyph indexes with WithCIDsAreGlyphIDs, else they are mapped through Unicode.

The font's /Widths or /W are never changed: the subset's advances are made to agree with them (WidthsAdjustProgram, the default), so no glyph moves. A new font descriptor is written (a descriptor shared between fonts is never edited) and the base name keeps the document's own name behind a subset tag.

Refusals are [FontEmbedError]s: the program is CFF (EmbedUnsupportedProgram), forbids embedding (EmbedProgramForbidsEmbedding, unless WithIgnoreEmbeddingRestrictions), the font is Type 3 or a Type 0 font that is not CIDFontType2 with Identity (EmbedType3Font, EmbedUnsupportedFont), already has a program (EmbedAlreadyEmbedded, unless WithReplaceProgram), has a code without a glyph with MissingRefuse (EmbedNoGlyphForCode) or widths that differ with WidthsRefuse (EmbedWidthMismatch). Nothing is changed when a call is refused.

func (*Document) EmbedSubstituteFonts

func (d *Document) EmbedSubstituteFonts(opts ...SubstituteOption) (*SubstituteReport, error)

EmbedSubstituteFonts gives every font that has no program one from a provider, as a subset (see Document.EmbedFontProgram for what is written), so the file satisfies ISO 14289-1 7.21.4.1 and ISO 19005-2 6.2.11.4.1 without moving a glyph: the PDF's widths are kept, the face's advances in the subset are made to agree with them, and each glyph keeps its own shape.

The provider is, in order, WithSubstituteProvider, the document's (Document.SetFontProvider), then the registered ones. With none, no font is changed, every one that needs a program gets SubstituteNoProvider and the report says so. Each font is asked of the provider with a FontRequest; for a font that names a standard face the request's Name is the standard name ("Helvetica-Bold" for Arial-BoldMT). When a provider answers with a chain (Symbol, ZapfDingbats), the first face with a glyph for every shown code is used, else the face with the most; codes it lacks are listed as missing. A Type 0 font is only done when it has a /ToUnicode map, to map its codes to glyphs.

The report is about metrics and coverage, not appearance: a face with every glyph and every width can still draw different shapes than the font it stands for.

func (*Document) EmbedSubstituteFontsContext

func (d *Document) EmbedSubstituteFontsContext(ctx context.Context, opts ...SubstituteOption) (*SubstituteReport, error)

EmbedSubstituteFontsContext is Document.EmbedSubstituteFonts with cancellation: the context is checked between pages when finding which codes each font shows and between fonts.

func (*Document) EmbeddedFiles

func (d *Document) EmbeddedFiles() iter.Seq[*EmbeddedFile]

EmbeddedFiles iterates over the files of the /Names /EmbeddedFiles name tree in tree order. An entry that is not a file specification is skipped.

func (*Document) Encrypted

func (d *Document) Encrypted() bool

Encrypted reports whether the trailer has an /Encrypt entry.

func (*Document) Encryption

func (d *Document) Encryption() (EncryptionInfo, bool)

Encryption returns the standard security handler's parameters, and false when the document is not encrypted.

func (*Document) FindNotdefText

func (d *Document) FindNotdefText() ([]NotdefRun, error)

FindNotdefText returns every text operator that shows .notdef, over all pages, with the forms they draw and the annotation appearances. Only embedded fonts that are not stand-ins and not Type 3 can show .notdef. An operator in a form drawn more than once is listed once, under the first page that draws it. Optional content uses the default configuration, and a form hidden by it is not entered.

Example
package main

import (
	"bytes"
	"fmt"
	"os"

	"recursiveai.org/go/onepdf"
)

func exampleFont(name string) *onepdf.FontFile {
	data, err := os.ReadFile("testdata/embed/" + name)
	if err != nil {
		panic(err)
	}
	f, err := onepdf.OpenFontFile(data, 0)
	if err != nil {
		panic(err)
	}
	return f
}

func main() {
	doc, _ := onepdf.New()
	doc.InsertBlankPage(0, 200, 100)
	font, _ := doc.AddFont(exampleFont("kit-text.ttf"))
	pc, _ := doc.BeginContent(0, onepdf.PlaceOver)
	pc.SetFont(font, 12)
	pc.DrawText("A\u65e5B", 10, 50) // the font has no glyph for U+65E5
	pc.Commit()
	var out bytes.Buffer
	doc.Save(&out)

	back, _ := onepdf.OpenBytes(out.Bytes(), onepdf.WithEditing())
	runs, _ := back.FindNotdefText()
	for _, r := range runs {
		fmt.Println(r.Source, "codes", r.Codes, "shown", r.ShownCodes, "visible", r.Visible)
	}
}
Output:
PageContent codes [0] shown [2 0 3] visible true

func (*Document) FindNotdefTextContext

func (d *Document) FindNotdefTextContext(ctx context.Context) ([]NotdefRun, error)

FindNotdefTextContext is Document.FindNotdefText with cancellation, checked between pages.

func (*Document) Flatten

func (d *Document) Flatten(opts ...FlattenOption) (FlattenResult, error)

Flatten bakes the normal appearance of widgets (and, with WithFlattenMarkup, of the other annotations except links and pop-ups) into the page content and removes the annotations (ISO 32000-2 12.5.5).

The appearance's /Matrix-transformed /BBox is fitted onto /Rect and drawn as `q a b c d e f cm /Name Do Q` in a content stream appended to the page; the original content is wrapped in q ... Q so a leaked graphics state cannot move the art. A stored appearance stream is used as the XObject itself (/Subtype /Form is added when missing); a missing one is generated and stored. An annotation with the NoRotate flag on a rotated page stays upright, pinned at the upper left corner of its rectangle. Annotations hidden by optional content are not drawn. Pop-ups go with their parent annotation.

Flattened fields leave the field tree and /CO; parents left without children go too; /AcroForm is dropped when no field is left. Signed signature fields stay with their widgets. Structure tree entries that point at removed widgets are left as they are. Pages and Form values taken before the call are stale.

Example
package main

import (
	"fmt"

	"recursiveai.org/go/onepdf"
)

// exampleFormPDF is a one-page form with a text field and a check box. The file has no
// cross-reference table: the reader rebuilds it.
const exampleFormPDF = `%PDF-1.7
1 0 obj
<</Type /Catalog/Pages 2 0 R/AcroForm <</Fields [5 0 R 6 0 R]/DA (/Helv 0 Tf 0 g)/NeedAppearances true>>>>
endobj
2 0 obj
<</Type /Pages/Kids [3 0 R]/Count 1>>
endobj
3 0 obj
<</Type /Page/Parent 2 0 R/MediaBox [0 0 200 100]/Annots [5 0 R 6 0 R]>>
endobj
5 0 obj
<</Type /Annot/Subtype /Widget/FT /Tx/T (name)/MaxLen 8/Rect [10 60 150 80]/F 4>>
endobj
6 0 obj
<</Type /Annot/Subtype /Widget/FT /Btn/T (agree)/Rect [10 20 30 40]/F 4/AS /Off/V /Off/AP <</N <</Yes 7 0 R/Off 7 0 R>>>>>>
endobj
7 0 obj
<</Type /XObject/Subtype /Form/BBox [0 0 20 20]/Length 14>>
stream
0 0 20 20 re S
endstream
endobj
trailer
<</Root 1 0 R>>
`

func main() {
	doc, _ := onepdf.OpenBytes([]byte(exampleFormPDF), onepdf.WithEditing())
	doc.Form().SetValue("name", "Ada")
	res, err := doc.Flatten()
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println("drawn:", res.Drawn, "removed:", res.Removed, "fields:", res.FieldsRemoved, "form removed:", res.FormRemoved)
}
Output:
drawn: 2 removed: 2 fields: 2 form removed: true

func (*Document) FlattenContext

func (d *Document) FlattenContext(ctx context.Context, opts ...FlattenOption) (FlattenResult, error)

FlattenContext is Flatten that stops with ctx.Err() when ctx is done, between pages. The document then holds the pages already flattened and still lists the others' annotations; close it and reopen the source, or call Flatten again, which finishes the job.

func (*Document) FontProvider

func (d *Document) FontProvider() FontProvider

FontProvider returns the provider set with Document.SetFontProvider, nil if none.

func (*Document) Form

func (d *Document) Form() *AcroForm

Form returns the document's AcroForm, or nil when the catalog has none. A nil *AcroForm is safe to use: Fields, All, Terminal and Find report nothing, and every call that names a field, Fill included, returns an error that matches ErrForm (FormUnknownField) and changes nothing. So a program can write doc.Form().Fill(values) without checking for a form first and still learn that there was none. The field tree is read with an explicit stack; a /Kids loop or a node reached twice is read once, and at most Limits.MaxObjects fields are read.

func (*Document) ImportPages

func (d *Document) ImportPages(src *Document, indexes []int, opts ...ImportOption) error

ImportPages copies pages of src into the document: the pages at indexes, in that order (nil means every page), placed at WithImportAt or at the end. src may be any document, read-only, encrypted or the document itself; it is not changed and not referred to afterwards.

A page brings its content, resources and annotations, each as its own copy, and the entries it inherited from the page tree. Links follow their pages and lose a destination that was left behind; outline items, form fields, named destinations, page labels and tagged-PDF structure of the imported pages are merged (see the Import options). Form fields whose name is taken get "_2", "_3" and so on. A source with /NeedAppearances gets its text and choice fields' appearances generated and stored, instead of setting the flag on the target. The version is raised to the source's when that is higher. Article threads, thumbnails, document JavaScript and the source's metadata are not carried.

An index out of range, or an insertion index out of range, is ErrArgument; a limit is ErrLimit. A failure while the pages are copied leaves the document unchanged. Pages, outlines and other views taken before the call are out of date afterwards: take them again.

Example
package main

import (
	"fmt"

	"recursiveai.org/go/onepdf"
)

// pagesOfWidths returns an editable document whose pages are as wide as the arguments say, which makes
// the page order visible.
func pagesOfWidths(widths ...float64) *onepdf.Document {
	doc, err := onepdf.New()
	if err != nil {
		panic(err)
	}
	for i, w := range widths {
		if err := doc.InsertBlankPage(i, w, 100); err != nil {
			panic(err)
		}
	}
	return doc
}

func widths(doc *onepdf.Document) []float64 {
	var out []float64
	for p := range doc.Pages() {
		out = append(out, p.MediaBox().Width())
	}
	return out
}

func main() {
	dst := pagesOfWidths(100)
	src := pagesOfWidths(10, 20, 30)
	// Pages 2 and 0 of src, in that order, placed first.
	if err := dst.ImportPages(src, []int{2, 0}, onepdf.WithImportAt(0)); err != nil {
		fmt.Println(err)
	}
	fmt.Println(widths(dst))
}
Output:
[30 10 100]

func (*Document) ImportPagesContext

func (d *Document) ImportPagesContext(ctx context.Context, src *Document, indexes []int, opts ...ImportOption) error

ImportPagesContext is ImportPages that stops with ctx.Err() when ctx is done.

func (*Document) Info

func (d *Document) Info() *Info

Info returns the information dictionary the trailer's /Info names, or nil when the file has none (or it is not a dictionary).

Example
package main

import (
	"fmt"

	"recursiveai.org/go/onepdf"
)

// modelExamplePDF is a two-page file with an Info title, a rotated page, an
// outline with a child, and Roman page labels.
func modelExamplePDF() []byte {
	objs := []string{
		"<</Type /Catalog/Pages 2 0 R/Outlines 5 0 R/PageLabels <</Nums [0 <</S /r>>]>>>>",
		"<</Type /Pages/Kids [3 0 R 4 0 R]/Count 2/MediaBox [0 0 612 792]>>",
		"<</Type /Page/Parent 2 0 R>>",
		"<</Type /Page/Parent 2 0 R/Rotate 90/CropBox [0 0 300 200]>>",
		"<</Type /Outlines/First 6 0 R/Last 6 0 R/Count 2>>",
		"<</Title (Chapter 1)/Parent 5 0 R/First 7 0 R/Last 7 0 R/Count 1/Dest [3 0 R /Fit]>>",
		"<</Title (Section 1.1)/Parent 6 0 R/Dest [4 0 R /XYZ 0 200 null]>>",
		"<</Title (Example)/Author (Ada)>>",
	}
	out := []byte("%PDF-1.7\n")
	offs := make([]int, len(objs))
	for i, o := range objs {
		offs[i] = len(out)
		out = append(out, fmt.Sprintf("%d 0 obj\n%s\nendobj\n", i+1, o)...)
	}
	xref := len(out)
	out = append(out, fmt.Sprintf("xref\n0 %d\n0000000000 65535 f \n", len(objs)+1)...)
	for _, o := range offs {
		out = append(out, fmt.Sprintf("%010d 00000 n \n", o)...)
	}
	out = append(out, fmt.Sprintf("trailer\n<</Size %d/Root 1 0 R/Info 8 0 R>>\nstartxref\n%d\n%%%%EOF\n", len(objs)+1, xref)...)
	return out
}

func main() {
	doc, _ := onepdf.OpenBytes(modelExamplePDF())
	fmt.Println(doc.PageCount(), doc.Info().Title(), doc.Info().Author())
}
Output:
2 Example Ada

func (*Document) InsertBlankPage

func (d *Document) InsertBlankPage(index int, width, height float64) error

InsertBlankPage inserts a new page with no content at index, which counts from 0 and may equal the page count to append. The page is width by height points (its MediaBox) and has empty resources. The page tree's /Count entries are updated.

An index out of range, or a width or height that is not a positive finite number, is ErrArgument. It needs a document opened with WithEditing.

func (*Document) IsRedacted

func (d *Document) IsRedacted() bool

IsRedacted reports whether a Redact or ApplyRedactAnnotations call changed this document. After that only a full Save is allowed: SaveIncremental would keep the removed bytes.

func (*Document) IsTagged

func (d *Document) IsTagged() bool

IsTagged reports whether the catalog's /MarkInfo says the document is tagged (/Marked true, ISO 32000-2 14.7.1).

func (*Document) Language

func (d *Document) Language() string

Language returns the catalog's /Lang, the document's natural language as a language tag such as "en-US" (ISO 32000-2 14.9.2.2), or "" when it is missing or empty.

func (*Document) Limits

func (d *Document) Limits() Limits

Limits returns the limits the document was opened with: the defaults for every field the caller left zero.

func (*Document) LostPages

func (d *Document) LostPages() []LostPage

LostPages lists the page-tree entries that did not lead to a page, in the order the tree declares them. The pages themselves are Page and Pages.

func (*Document) MatchEmbeddedFontWidths

func (d *Document) MatchEmbeddedFontWidths(opts ...WidthMatchOption) (*WidthMatchReport, error)

MatchEmbeddedFontWidths gives the glyphs that pages show, in every embedded CFF font (FontFile3 of subtype Type1C or CIDFontType0C, simple or Type 0), the widths the PDF states. Only the width operand of those glyphs' charstrings changes, and defaultWidthX and nominalWidthX become whole numbers (readers differ in how they take fractions), with every other glyph written again so it keeps its width. The new program is read back and compared glyph by glyph with the old one before it replaces it, and the descriptor is replaced by a copy so fonts that shared the old one are not affected. Text positions come from the PDF's widths and do not change.

A glyph that reaches its width through a subroutine call is not handled and leaves the font as it was (WidthRefused). The document must be editable.

Example
package main

import (
	"bytes"
	"fmt"
	"os"

	"recursiveai.org/go/onepdf"
)

func exampleFont(name string) *onepdf.FontFile {
	data, err := os.ReadFile("testdata/embed/" + name)
	if err != nil {
		panic(err)
	}
	f, err := onepdf.OpenFontFile(data, 0)
	if err != nil {
		panic(err)
	}
	return f
}

func main() {
	doc, _ := onepdf.New()
	doc.InsertBlankPage(0, 200, 100)
	font, _ := doc.AddFont(exampleFont("kit-text.otf")) // CFF outlines
	pc, _ := doc.BeginContent(0, onepdf.PlaceOver)
	pc.SetFont(font, 12)
	pc.DrawText("ABC", 10, 50)
	pc.Commit()
	var out bytes.Buffer
	doc.Save(&out)

	back, _ := onepdf.OpenBytes(out.Bytes(), onepdf.WithEditing())
	rep, err := back.MatchEmbeddedFontWidths()
	fmt.Println(err)
	for _, e := range rep.Entries {
		fmt.Println(e.Outcome)
	}
}
Output:
<nil>
AlreadyMatching

func (*Document) MatchEmbeddedFontWidthsContext

func (d *Document) MatchEmbeddedFontWidthsContext(ctx context.Context, opts ...WidthMatchOption) (*WidthMatchReport, error)

MatchEmbeddedFontWidthsContext is Document.MatchEmbeddedFontWidths with cancellation, checked between pages and between fonts.

func (*Document) MovePage

func (d *Document) MovePage(from, to int) error

MovePage moves a page so that it is page index to afterwards. Both indexes count from 0 and must be pages of the document, else ErrArgument. The document must be opened with WithEditing.

Pages views taken earlier (Page, Pages, Outline, Form and the like) are out of date afterwards: take them again.

Example
package main

import (
	"fmt"

	"recursiveai.org/go/onepdf"
)

// pagesOfWidths returns an editable document whose pages are as wide as the arguments say, which makes
// the page order visible.
func pagesOfWidths(widths ...float64) *onepdf.Document {
	doc, err := onepdf.New()
	if err != nil {
		panic(err)
	}
	for i, w := range widths {
		if err := doc.InsertBlankPage(i, w, 100); err != nil {
			panic(err)
		}
	}
	return doc
}

func widths(doc *onepdf.Document) []float64 {
	var out []float64
	for p := range doc.Pages() {
		out = append(out, p.MediaBox().Width())
	}
	return out
}

func main() {
	doc := pagesOfWidths(100, 200, 300, 400)
	// The cover goes to the back: it is page 3 afterwards.
	if err := doc.MovePage(0, 3); err != nil {
		fmt.Println(err)
	}
	fmt.Println(widths(doc))
}
Output:
[200 300 400 100]

func (*Document) NamedDestination

func (d *Document) NamedDestination(name string) (*Destination, bool)

NamedDestination resolves a named destination (ISO 32000-2 12.3.2.3). A name is compared as text, so a name stored as a UTF-16 string is found by its text. ok is false when no such name exists or its value is not a destination.

func (*Document) NamedDestinations

func (d *Document) NamedDestinations() iter.Seq[string]

NamedDestinations iterates over the names of every named destination: the name tree in tree order, then entries only the old catalog /Dests dictionary has.

func (*Document) Object

func (d *Document) Object(num int) (Object, error)

Object returns object number num as the newest revision has it. A number that is free, absent or null gives nil with no error; an object that exists but cannot be read gives an error matching ErrFormat or ErrLimit.

func (*Document) ObjectCount

func (d *Document) ObjectCount() int

ObjectCount returns the number of object numbers the file allots: the larger of the trailer's /Size and the highest number in the cross-reference data plus one.

func (*Document) OptionalContentGroups

func (d *Document) OptionalContentGroups() []OptionalContentGroup

OptionalContentGroups returns the layers listed in /OCProperties /OCGs, in that order, with their default visibility. An entry that is not a dictionary is skipped.

func (*Document) Outline

func (d *Document) Outline() []*OutlineItem

Outline returns the top-level items of the document outline; nil when the catalog has no /Outlines. Each item holds its children, so the result is the whole tree.

The tree is read with an explicit stack, so depth never exhausts the Go stack. A /Next or /First that loops back, or an item reached through two parents, is read once, under its first parent (the document gets a diagnostic). At most Limits.MaxObjects items are read.

func (*Document) Page

func (d *Document) Page(i int) (*Page, error)

Page returns page i, counting from zero, or ErrPageRange. The page tree is read once, on the first call of any page method, and cached.

Example
package main

import (
	"fmt"

	"recursiveai.org/go/onepdf"
)

// modelExamplePDF is a two-page file with an Info title, a rotated page, an
// outline with a child, and Roman page labels.
func modelExamplePDF() []byte {
	objs := []string{
		"<</Type /Catalog/Pages 2 0 R/Outlines 5 0 R/PageLabels <</Nums [0 <</S /r>>]>>>>",
		"<</Type /Pages/Kids [3 0 R 4 0 R]/Count 2/MediaBox [0 0 612 792]>>",
		"<</Type /Page/Parent 2 0 R>>",
		"<</Type /Page/Parent 2 0 R/Rotate 90/CropBox [0 0 300 200]>>",
		"<</Type /Outlines/First 6 0 R/Last 6 0 R/Count 2>>",
		"<</Title (Chapter 1)/Parent 5 0 R/First 7 0 R/Last 7 0 R/Count 1/Dest [3 0 R /Fit]>>",
		"<</Title (Section 1.1)/Parent 6 0 R/Dest [4 0 R /XYZ 0 200 null]>>",
		"<</Title (Example)/Author (Ada)>>",
	}
	out := []byte("%PDF-1.7\n")
	offs := make([]int, len(objs))
	for i, o := range objs {
		offs[i] = len(out)
		out = append(out, fmt.Sprintf("%d 0 obj\n%s\nendobj\n", i+1, o)...)
	}
	xref := len(out)
	out = append(out, fmt.Sprintf("xref\n0 %d\n0000000000 65535 f \n", len(objs)+1)...)
	for _, o := range offs {
		out = append(out, fmt.Sprintf("%010d 00000 n \n", o)...)
	}
	out = append(out, fmt.Sprintf("trailer\n<</Size %d/Root 1 0 R/Info 8 0 R>>\nstartxref\n%d\n%%%%EOF\n", len(objs)+1, xref)...)
	return out
}

func main() {
	doc, _ := onepdf.OpenBytes(modelExamplePDF())
	for p := range doc.Pages() {
		label, _ := p.Label()
		fmt.Println(p.Index(), label, p.CropBox(), p.Rotate())
	}
}
Output:
0 i {0 0 612 792} 0
1 ii {0 0 300 200} 90

func (*Document) PageCount

func (d *Document) PageCount() int

PageCount returns the number of pages in the newest revision.

func (*Document) PageIndex

func (d *Document) PageIndex(num int) int

PageIndex returns the zero-based index of the page whose dictionary is indirect object num, or -1 when no page has that object number.

func (*Document) PageLabels

func (d *Document) PageLabels() *PageLabels

PageLabels returns the page labels the catalog's /PageLabels number tree defines, or nil when the catalog has none. Ranges are in page order; a damaged entry (not a dictionary, a negative first page) is skipped and two ranges for one page keep the first in the tree.

func (*Document) Pages

func (d *Document) Pages() iter.Seq2[*Page, error]

Pages iterates over every page in order, as Page(0), Page(1) and so on yield them. The error is the one Page would return for that index. The page tree is flattened up front and a page that does not read is left out of it (see LostPages), so today it is always nil; it is part of the signature so that a loop written as "for p, err := range doc.Pages()" keeps working if a page can fail to read later. Ranging with one variable, "for p := range doc.Pages()", ignores it.

func (*Document) Permissions

func (d *Document) Permissions() Permissions

Permissions returns the usage flags the file states. A document that is not encrypted has every flag set. They are never enforced.

func (*Document) ReadAction

func (d *Document) ReadAction(a *Dict) *Action

ReadAction reads an action dictionary and the chain its /Next entries start (ISO 32000-2 12.6.2) as described on Action.Next. At most 1024 actions are read. It returns nil for a nil dictionary.

func (*Document) RemoveInfo

func (d *Document) RemoveInfo(key string) error

RemoveInfo removes an entry of the document information dictionary. A missing entry or dictionary is not an error. It fails like SetInfo on a document that cannot be edited.

func (*Document) RemoveNotdefText

func (d *Document) RemoveNotdefText(opts ...NotdefOption) (*NotdefRemoval, error)

RemoveNotdefText takes the .notdef codes out of the text operators Document.FindNotdefText lists. A removed code is replaced by a TJ adjustment of its advance, so the text after it does not move. A stream with a change is written again by the content rewriter: every operator keeps its bytes, one per line, and comments are dropped; a stream with no change is left alone. A changed stream is stored Flate-compressed. Extracted text loses exactly the NotdefText of the removed runs. The document must be editable unless the run is a dry run.

Example
package main

import (
	"bytes"
	"fmt"
	"os"

	"recursiveai.org/go/onepdf"
)

func exampleFont(name string) *onepdf.FontFile {
	data, err := os.ReadFile("testdata/embed/" + name)
	if err != nil {
		panic(err)
	}
	f, err := onepdf.OpenFontFile(data, 0)
	if err != nil {
		panic(err)
	}
	return f
}

func main() {
	doc, _ := onepdf.New()
	doc.InsertBlankPage(0, 200, 100)
	font, _ := doc.AddFont(exampleFont("kit-text.ttf"))
	pc, _ := doc.BeginContent(0, onepdf.PlaceOver)
	pc.SetFont(font, 12)
	pc.DrawText("A\u65e5B", 10, 50)
	pc.Commit()
	var out bytes.Buffer
	doc.Save(&out)

	back, _ := onepdf.OpenBytes(out.Bytes(), onepdf.WithEditing())
	// The default scope removes only text nobody sees; this text is drawn.
	rep, _ := back.RemoveNotdefText(onepdf.WithNotdefScope(onepdf.NotdefAll))
	fmt.Println("removed", rep.GlyphsRemoved, "code in", rep.OperatorsChanged, "operator")
	runs, _ := back.FindNotdefText()
	fmt.Println("left", len(runs))
}
Output:
removed 1 code in 1 operator
left 0

func (*Document) RemoveNotdefTextContext

func (d *Document) RemoveNotdefTextContext(ctx context.Context, opts ...NotdefOption) (*NotdefRemoval, error)

RemoveNotdefTextContext is Document.RemoveNotdefText with cancellation.

func (*Document) RemoveObject

func (d *Document) RemoveObject(num int) error

RemoveObject frees object num: references to it read as null from then on. The number must belong to an object of the document, else ErrArgument. A full save leaves the object out; an incremental save lists it as free.

func (*Document) RemovePage

func (d *Document) RemovePage(index int) error

RemovePage removes the page at index and repairs what led to it: see RemovePages.

func (*Document) RemovePages

func (d *Document) RemovePages(indexes ...int) error

RemovePages removes the pages at indexes (in any order, repeats ignored) from the page tree and repairs what led to them:

  • links on the remaining pages lose a destination or go-to action that led to a removed page;
  • outline items that led to a removed page are removed, except that one with other items below it stays as a heading without a target; /First, /Last, /Prev, /Next and /Count are rewritten;
  • named destinations and the open action that led to a removed page are dropped, and the names tree is rewritten as one sorted node when anything goes;
  • form fields whose widgets were all on removed pages are removed from the form;
  • page labels keep their pages, so the pages that remain are renumbered as before;
  • the structure tree and article threads, which refer to pages from deep inside, are dropped, with a diagnostic.

A full save writes only what the remaining pages reach; an incremental save keeps the old objects. An index out of range is ErrArgument and nothing changes. The document must be opened with WithEditing. Views taken earlier are out of date afterwards.

Example
package main

import (
	"fmt"

	"recursiveai.org/go/onepdf"
)

// pagesOfWidths returns an editable document whose pages are as wide as the arguments say, which makes
// the page order visible.
func pagesOfWidths(widths ...float64) *onepdf.Document {
	doc, err := onepdf.New()
	if err != nil {
		panic(err)
	}
	for i, w := range widths {
		if err := doc.InsertBlankPage(i, w, 100); err != nil {
			panic(err)
		}
	}
	return doc
}

func widths(doc *onepdf.Document) []float64 {
	var out []float64
	for p := range doc.Pages() {
		out = append(out, p.MediaBox().Width())
	}
	return out
}

func main() {
	doc := pagesOfWidths(100, 200, 300, 400)
	// Links, outline items and names that led to these pages are repaired.
	if err := doc.RemovePages(3, 1); err != nil {
		fmt.Println(err)
	}
	fmt.Println(widths(doc))
}
Output:
[100 300]

func (*Document) ReorderPages

func (d *Document) ReorderPages(order []int) error

ReorderPages puts the pages in a new order: order[i] is the current index of the page that becomes page i. order must be a permutation of 0 to PageCount-1, else ErrArgument.

Example
package main

import (
	"fmt"

	"recursiveai.org/go/onepdf"
)

// pagesOfWidths returns an editable document whose pages are as wide as the arguments say, which makes
// the page order visible.
func pagesOfWidths(widths ...float64) *onepdf.Document {
	doc, err := onepdf.New()
	if err != nil {
		panic(err)
	}
	for i, w := range widths {
		if err := doc.InsertBlankPage(i, w, 100); err != nil {
			panic(err)
		}
	}
	return doc
}

func widths(doc *onepdf.Document) []float64 {
	var out []float64
	for p := range doc.Pages() {
		out = append(out, p.MediaBox().Width())
	}
	return out
}

func main() {
	doc := pagesOfWidths(100, 200, 300)
	// order[i] is the current index of the page that becomes page i.
	if err := doc.ReorderPages([]int{2, 0, 1}); err != nil {
		fmt.Println(err)
	}
	fmt.Println(widths(doc))
}
Output:
[300 100 200]

func (*Document) Resolve

func (d *Document) Resolve(o Object) Object

Resolve follows references until it reaches a value that is not one, using the newest revision. A reference to a missing, free or null object, and a chain that loops, give nil. Objects that cannot be read give nil too; Object reports why.

func (*Document) ResolveColorSpace

func (d *Document) ResolveColorSpace(obj Object, resources *Dict) (*ColorSpace, error)

ResolveColorSpace reads a colour space object: a name (a device space, or a key of resources' /ColorSpace dictionary) or an array. resources is the resource dictionary used to look names up, or nil. Every family is understood: DeviceGray/RGB/CMYK, CalGray, CalRGB, Lab, ICCBased, Indexed, Separation, DeviceN and Pattern. As in content streams, an ICC profile that cannot be read stands in as its /Alternate or the device space of the same size, and CalGray and CalRGB convert as their device spaces do.

An object that is not a usable colour space gives an error matching ErrFormat. Resolution is bounded by the document's limits.

Example

A document's colour spaces can be resolved and converted without interpreting a page.

doc, _ := onepdf.OpenBytes(examplePDF())
palette := onepdf.NewArray(onepdf.Name("Indexed"), onepdf.Name("DeviceRGB"), onepdf.Int(1),
	onepdf.String("\x00\x00\x00\xff\x00\x00"))
cs, err := doc.ResolveColorSpace(palette, nil)
if err != nil {
	fmt.Println(err)
	return
}
c, _ := cs.Color(1)
fmt.Println(cs.Family(), cs.Components(), c.Space.Kind == device.RGB, c.Comps[:3])
Output:
Indexed 1 true [1 0 0]

func (*Document) Revisions

func (d *Document) Revisions() []Revision

Revisions returns every revision, oldest first. A hybrid-reference file's table and its cross-reference stream count as one. A linearized file reads as an ordinary file: its first-page section is one more revision.

Example
package main

import (
	"bytes"
	"fmt"

	"recursiveai.org/go/onepdf"
)

// examplePDF writes a two-page file with an incremental update that adds the second page.
func examplePDF() []byte {
	var b bytes.Buffer
	b.WriteString("%PDF-1.7\n")
	offs := map[int]int{}
	obj := func(n int, body string) {
		offs[n] = b.Len()
		fmt.Fprintf(&b, "%d 0 obj\n%s\nendobj\n", n, body)
	}
	obj(1, "<</Type /Catalog/Pages 2 0 R/Lang (en)>>")
	obj(2, "<</Type /Pages/Kids [3 0 R]/Count 1>>")
	obj(3, "<</Type /Page/Parent 2 0 R/MediaBox [0 0 612 792.5]>>")
	first := b.Len()
	fmt.Fprintf(&b, "xref\n0 4\n0000000000 65535 f \n%010d 00000 n \n%010d 00000 n \n%010d 00000 n \ntrailer\n<</Size 4/Root 1 0 R>>\nstartxref\n%d\n%%%%EOF\n", offs[1], offs[2], offs[3], first)
	obj(2, "<</Type /Pages/Kids [3 0 R 4 0 R]/Count 2>>")
	obj(4, "<</Type /Page/Parent 2 0 R/MediaBox [0 0 100 100]>>")
	second := b.Len()
	fmt.Fprintf(&b, "xref\n2 1\n%010d 00000 n \n4 1\n%010d 00000 n \ntrailer\n<</Size 5/Root 1 0 R/Prev %d>>\nstartxref\n%d\n%%%%EOF\n", offs[2], offs[4], first, second)
	return b.Bytes()
}

func main() {
	doc, _ := onepdf.OpenBytes(examplePDF())
	for _, rev := range doc.Revisions() {
		fmt.Println(rev.Index(), "pages:", rev.PageCount())
	}
}
Output:
0 pages: 1
1 pages: 2

func (*Document) RotatePage

func (d *Document) RotatePage(index, degrees int) error

RotatePage adds degrees (a multiple of 90, any sign) to the rotation of the page at index. A page whose rotation is inherited gets its own value. An index out of range or a rotation that is not a multiple of 90 is ErrArgument.

Example
package main

import (
	"fmt"

	"recursiveai.org/go/onepdf"
)

// pagesOfWidths returns an editable document whose pages are as wide as the arguments say, which makes
// the page order visible.
func pagesOfWidths(widths ...float64) *onepdf.Document {
	doc, err := onepdf.New()
	if err != nil {
		panic(err)
	}
	for i, w := range widths {
		if err := doc.InsertBlankPage(i, w, 100); err != nil {
			panic(err)
		}
	}
	return doc
}

func main() {
	doc := pagesOfWidths(100, 200)
	// Rotation is added to the page's own; Page.SetRotate sets it.
	doc.RotatePage(0, 90)
	doc.RotatePage(0, 90)
	p0, _ := doc.Page(0)
	p1, _ := doc.Page(1)
	p1.SetRotate(-90)
	fmt.Println(p0.Rotate(), p1.Rotate())
}
Output:
180 270

func (*Document) Save

func (d *Document) Save(w io.Writer, opts ...SaveOption) error

Save writes the document as a new file: the catalog and the Info dictionary and everything reachable from them, numbered 1, 2, 3 … in the order they are met. Objects nothing refers to, earlier revisions, free entries and the damage of a file that needed repair are not written. A reference to an object that does not exist is written as null.

Streams keep their filters and stored bytes (see WithCompressedStreams); /Length is always direct. The output is the same bytes every time for the same document and options.

Save reads the document as it stands, so it works on a document opened without WithEditing, and concurrently with reads but not with edits.

Example
doc, err := onepdf.OpenBytes(examplePDF(), onepdf.WithEditing())
if err != nil {
	fmt.Println(err)
	return
}
if err := doc.SetInfo("Title", "Quarterly report"); err != nil {
	fmt.Println(err)
	return
}
var out bytes.Buffer
// A clean file with a cross-reference stream and object streams, Flate-compressing what is stored plain.
if err := doc.Save(&out, onepdf.WithXRefFormat(onepdf.XRefStream), onepdf.WithCompressedStreams(true)); err != nil {
	fmt.Println(err)
	return
}
saved, _ := onepdf.OpenBytes(out.Bytes())
fmt.Println("title:", saved.Trailer().Dict("Info").Get("Title").(onepdf.String).Text())
fmt.Println("pages:", saved.PageCount(), "revisions:", len(saved.Revisions()))
Output:
title: Quarterly report
pages: 2 revisions: 1

func (*Document) SaveContext

func (d *Document) SaveContext(ctx context.Context, w io.Writer, opts ...SaveOption) (err error)

SaveContext is Save with cancellation, checked between objects.

func (*Document) SaveFile

func (d *Document) SaveFile(path string, opts ...SaveOption) error

SaveFile writes the document to the file at path as Save does, replacing it. A failed save removes the partial file.

func (*Document) SaveFileContext

func (d *Document) SaveFileContext(ctx context.Context, path string, opts ...SaveOption) error

SaveFileContext is SaveFile that stops with ctx.Err() when ctx is done, as SaveContext does; the partial file is removed.

func (*Document) SaveIncremental

func (d *Document) SaveIncremental(w io.Writer, opts ...SaveOption) error

SaveIncremental writes the original file byte for byte, then an update (ISO 32000-2 7.5.6): the objects changed or added since the document was opened (a changed object keeps its number and generation), the objects removed as free entries chained onto the existing free list, a cross-reference section for them alone and a trailer whose /Prev names the previous section. The update continues the newest revision's cross-reference form unless WithXRefFormat says otherwise; a hybrid-reference file gets a table.

/ID keeps its first string and gets a new second one: the given WithDocumentID, or a SHA-256 of the previous second string and the update. Each call writes the changes since the document was opened, on top of the original file. An update with no changes is still a valid update.

Encryption cannot be added or removed this way: those options are refused with ErrArgument. A file that was rebuilt from a scan has no section to chain to; use Save for it.

Example
original := examplePDF()
doc, _ := onepdf.OpenBytes(original, onepdf.WithEditing())
if err := doc.Catalog().Set("Lang", onepdf.TextString("fr")); err != nil {
	fmt.Println(err)
	return
}
var out bytes.Buffer
if err := doc.SaveIncremental(&out); err != nil {
	fmt.Println(err)
	return
}
updated, _ := onepdf.OpenBytes(out.Bytes())
fmt.Println("starts with the original:", bytes.HasPrefix(out.Bytes(), original))
fmt.Println("revisions:", len(updated.Revisions()))
fmt.Println("lang now:", updated.Catalog().Get("Lang").(onepdf.String))
fmt.Println("lang before:", updated.Revisions()[len(updated.Revisions())-2].Catalog().Get("Lang").(onepdf.String))
Output:
starts with the original: true
revisions: 3
lang now: fr
lang before: en

func (*Document) SaveIncrementalContext

func (d *Document) SaveIncrementalContext(ctx context.Context, w io.Writer, opts ...SaveOption) (err error)

SaveIncrementalContext is SaveIncremental with cancellation, checked between objects.

func (*Document) Scripts

func (d *Document) Scripts() []Script

Scripts returns the document's JavaScript as data: the entries of the /Names /JavaScript name tree in tree order, then the catalog's /OpenAction when it is a JavaScript action. Entries that are not JavaScript actions are skipped. Nothing is executed.

func (*Document) SetFontProvider

func (d *Document) SetFontProvider(p FontProvider)

SetFontProvider sets the provider this document asks first, before the registered ones, for substitutes and for outlines of fonts it does not embed. nil removes it.

func (*Document) SetInfo

func (d *Document) SetInfo(key, value string) error

SetInfo sets an entry of the document information dictionary to a text string, creating the dictionary when the document has none. The text is stored as a PDF text string (PDFDocEncoding when it can be, UTF-16BE otherwise; see TextString).

It needs a document opened with WithEditing (else ErrNotEditable); an empty key is ErrArgument.

func (*Document) SetObject

func (d *Document) SetObject(num int, v Object) error

SetObject replaces the content of object num, keeping its number and generation; v is taken as AddObject takes it. The number must be one the document has allotted (below ObjectCount), else ErrArgument.

func (*Document) SetPrintGeometry

func (d *Document) SetPrintGeometry(bleed, slug PrintMargins, marks *PrinterMarks) error

SetPrintGeometry applies Page.SetPrintGeometry to every page, keeping the trim box each page reports. Nothing changes when the arguments are refused.

func (*Document) SetPrintPreferences

func (d *Document) SetPrintPreferences(scaling PrintScaling, duplex Duplex, copies int) error

SetPrintPreferences sets the print scaling, duplex mode and number of copies in one call, leaving out what is the zero value. It is SetViewerPreferences with those three entries.

func (*Document) SetToUnicode

func (d *Document) SetToUnicode(font *Dict, entries map[int]string, override bool, codeLength int) (bool, error)

SetToUnicode merges entries (code to text) into the font's /ToUnicode map and reports whether anything changed. An entry the map already has stays unless override is set. codeLength is the bytes a code takes in the map; 0 means 1 for a simple font and 2 for a Type 0 font. A font with no map gets one. The document must be editable. The ranges of an existing map that cross a 256-code block are written again as ranges that do not (ISO 32000-2 9.10.3), without changing what any code maps to.

func (*Document) SetViewerPreferences

func (d *Document) SetViewerPreferences(v ViewerPreferences) error

SetViewerPreferences writes the preferences v sets into the catalog's /ViewerPreferences, creating it when needed. Only entries that are Valid (and PrintPageRange when not nil) are written; entries the dictionary already has, including ones this type does not model, stay as they are.

NumCopies must be at least 1; PrintScaling and Duplex must be one of their constants; the page ranges are one-based and inclusive as stored, ascending, not overlapping and within the page count. Anything else is ErrArgument and nothing changes. v.Dict is ignored. The document must be opened with WithEditing.

Example
package main

import (
	"fmt"

	"recursiveai.org/go/onepdf"
)

// pagesOfWidths returns an editable document whose pages are as wide as the arguments say, which makes
// the page order visible.
func pagesOfWidths(widths ...float64) *onepdf.Document {
	doc, err := onepdf.New()
	if err != nil {
		panic(err)
	}
	for i, w := range widths {
		if err := doc.InsertBlankPage(i, w, 100); err != nil {
			panic(err)
		}
	}
	return doc
}

func main() {
	doc := pagesOfWidths(100, 100, 100)
	err := doc.SetViewerPreferences(onepdf.ViewerPreferences{
		PrintScaling:   onepdf.Opt[onepdf.PrintScaling]{Value: onepdf.PrintScalingNone, Valid: true},
		NumCopies:      onepdf.Opt[int]{Value: 2, Valid: true},
		PrintPageRange: [][2]int{{1, 1}, {3, 3}}, // pages 1 and 3, counted from 1 as the file stores them
	})
	if err != nil {
		fmt.Println(err)
		return
	}
	vp := doc.ViewerPreferences()
	fmt.Println(vp.PrintScaling.Value, vp.NumCopies.Value, vp.PrintPageRange)
}
Output:
None 2 [[1 1] [3 3]]

func (*Document) SetXMP

func (d *Document) SetXMP(data []byte) error

SetXMP replaces the document's XMP metadata stream (ISO 32000-2 14.3.2) with data, stored as given and unfiltered, creating the stream and the catalog's /Metadata entry when missing. The packet is not checked or kept in step with the information dictionary.

It fails like SetInfo on a document that cannot be edited.

func (*Document) Source

func (d *Document) Source() io.Reader

Source returns a reader over the bytes the document was opened from, exactly as they are in the file: edits to the document never change them. It reads from the document's source, so it fails with ErrSourceChanged if a file changed after open.

func (*Document) SourceOffset

func (d *Document) SourceOffset(o Object) (offset int64, container int, ok bool)

SourceOffset says where in the source the indirect object o was read from, as the revision it was read under records it. For an object stored in the file it returns the byte offset of its "n g obj" line and container 0. For an object inside an object stream it returns the stream's object number as container and offset 0 (the object has no offset of its own). ok is false for a direct value, an object made or changed in memory, and a reference the document does not list.

func (*Document) StrictError

func (d *Document) StrictError() error

StrictError returns, for a document opened WithStrict, the first damage that a call without an error result (Resolve, for one) met; nil otherwise. Calls that can return an error return the damage themselves.

func (*Document) StructTreeRoot

func (d *Document) StructTreeRoot() *Dict

StructTreeRoot returns the catalog's /StructTreeRoot dictionary, or nil when it is missing or not a dictionary. See Document.Structure for the tree as data.

func (*Document) SystemFonts

func (d *Document) SystemFonts() bool

SystemFonts reports whether the document was opened with WithSystemFonts.

func (*Document) Trailer

func (d *Document) Trailer() *Dict

Trailer returns the newest trailer dictionary (ISO 32000-2 7.5.5): the trailer of the last cross-reference section, or the cross-reference stream's dictionary. It is never nil.

func (*Document) Version

func (d *Document) Version() Version

Version returns the document's PDF version such as 1.7 or 2.0: the header's, raised to the catalog's /Version entry when that is later (ISO 32000-2 7.2.2, Table 29). It is the zero Version for a file with neither, and for one whose version is not a digit, a dot and a digit.

func (*Document) ViewerPreferences

func (d *Document) ViewerPreferences() *ViewerPreferences

ViewerPreferences returns the catalog's viewer preferences, or nil when it has none.

func (*Document) WalkOutline

func (d *Document) WalkOutline() iter.Seq2[int, *OutlineItem]

WalkOutline iterates over every outline item depth first, parents before their children, with its depth (0 for the top level).

Example
package main

import (
	"fmt"

	"recursiveai.org/go/onepdf"
)

// modelExamplePDF is a two-page file with an Info title, a rotated page, an
// outline with a child, and Roman page labels.
func modelExamplePDF() []byte {
	objs := []string{
		"<</Type /Catalog/Pages 2 0 R/Outlines 5 0 R/PageLabels <</Nums [0 <</S /r>>]>>>>",
		"<</Type /Pages/Kids [3 0 R 4 0 R]/Count 2/MediaBox [0 0 612 792]>>",
		"<</Type /Page/Parent 2 0 R>>",
		"<</Type /Page/Parent 2 0 R/Rotate 90/CropBox [0 0 300 200]>>",
		"<</Type /Outlines/First 6 0 R/Last 6 0 R/Count 2>>",
		"<</Title (Chapter 1)/Parent 5 0 R/First 7 0 R/Last 7 0 R/Count 1/Dest [3 0 R /Fit]>>",
		"<</Title (Section 1.1)/Parent 6 0 R/Dest [4 0 R /XYZ 0 200 null]>>",
		"<</Title (Example)/Author (Ada)>>",
	}
	out := []byte("%PDF-1.7\n")
	offs := make([]int, len(objs))
	for i, o := range objs {
		offs[i] = len(out)
		out = append(out, fmt.Sprintf("%d 0 obj\n%s\nendobj\n", i+1, o)...)
	}
	xref := len(out)
	out = append(out, fmt.Sprintf("xref\n0 %d\n0000000000 65535 f \n", len(objs)+1)...)
	for _, o := range offs {
		out = append(out, fmt.Sprintf("%010d 00000 n \n", o)...)
	}
	out = append(out, fmt.Sprintf("trailer\n<</Size %d/Root 1 0 R/Info 8 0 R>>\nstartxref\n%d\n%%%%EOF\n", len(objs)+1, xref)...)
	return out
}

func main() {
	doc, _ := onepdf.OpenBytes(modelExamplePDF())
	for depth, it := range doc.WalkOutline() {
		fmt.Printf("%*s%s -> page %d\n", depth*2, "", it.Title, it.Destination.Page)
	}
}
Output:
Chapter 1 -> page 0
  Section 1.1 -> page 1

func (*Document) XMP

func (d *Document) XMP() *XMP

XMP returns the metadata stream the catalog's /Metadata names, read as XMP, or nil when the catalog has none, it is not a stream, or it cannot be decoded within Limits.MaxMetadata (the reason is a diagnostic).

func (*Document) XRef

func (d *Document) XRef(num int) (XRefEntry, bool)

XRef returns the cross-reference entry for object number num in the newest revision.

type DocumentWriter

type DocumentWriter struct {
	// contains filtered or unexported fields
}

DocumentWriter writes a PDF file to an io.Writer as the calls come in, holding no more than one page, the cross-reference data and the outline in memory: a thousand-page document costs about what ten pages do. Objects are written as they become final; pages are written when committed.

Make one with NewDocumentWriter, add fonts and images, begin a page, draw on it, commit it, repeat, then Finish. The output is reproducible: a fixed document ID and the same calls give the same bytes. It has no encryption; save through a Document for that.

A DocumentWriter is not safe for concurrent use. After a call fails with ErrLimit or an I/O error the writer is unusable.

func NewDocumentWriter

func NewDocumentWriter(out io.Writer, opts ...WriterOption) *DocumentWriter

NewDocumentWriter starts a document that writes to out. Nothing is written until the first page or object.

Example
package main

import (
	"bytes"
	"fmt"

	"recursiveai.org/go/onepdf"
)

func main() {
	var out bytes.Buffer
	w := onepdf.NewDocumentWriter(&out, onepdf.WithDocumentID(bytes.Repeat([]byte{1}, 16)))
	font, _ := w.AddStandardFont(onepdf.FontTimesRoman)
	for i := 0; i < 3; i++ {
		page, _ := w.BeginPage(612, 792, 0)
		page.SetFont(font, 12)
		page.DrawText(fmt.Sprintf("Page %d", i+1), 72, 720)
		page.Commit() // the page is written now
		if i == 0 {
			w.AddBookmark("Start", 0, 0, 0)
		}
	}
	if err := w.Finish(); err != nil {
		fmt.Println(err)
		return
	}
	doc, _ := onepdf.OpenBytes(out.Bytes())
	fmt.Println(doc.PageCount(), "pages,", len(doc.Outline()), "bookmark")
}
Output:
3 pages, 1 bookmark

func (*DocumentWriter) AddBookmark

func (w *DocumentWriter) AddBookmark(title string, level, pageIndex int, top float64) error

AddBookmark adds an outline entry (ISO 32000-2 12.3.3) for the page begun at pageIndex, scrolled to the y position top (0 is the top of the page). Levels start at 0 and rise by at most one from the entry before; anything else, a page not begun yet or a title that is empty is ErrArgument.

func (*DocumentWriter) AddFont

func (w *DocumentWriter) AddFont(file *FontFile, opts ...EmbedOption) (CreatedFont, error)

AddFont embeds a font program for drawing; see Document.AddFont. The font is written when Finish is called, after the last page.

func (*DocumentWriter) AddJPEGImage

func (w *DocumentWriter) AddJPEGImage(data []byte) (*CreatedImage, error)

AddJPEGImage adds a JPEG file as an image; see Document.AddJPEGImage.

func (*DocumentWriter) AddNamedDestination

func (w *DocumentWriter) AddNamedDestination(name string, pageIndex int, top float64) error

AddNamedDestination adds a destination to the name tree (ISO 32000-2 12.3.2.3), which links can name. A name used twice is ErrArgument.

func (*DocumentWriter) AddPNGImage

func (w *DocumentWriter) AddPNGImage(data []byte) (*CreatedImage, error)

AddPNGImage adds a PNG file as an image; see Document.AddPNGImage.

func (*DocumentWriter) AddPageLabelRange

func (w *DocumentWriter) AddPageLabelRange(pageIndex int, style LabelStyle, prefix string, start int) error

AddPageLabelRange starts a range of page labels (ISO 32000-2 12.4.2) at a page begun already: its labels are prefix plus the number, counting from start (1 when start is below 1) in the style. Ranges come in page order; a document whose first range is not at page 0 gets plain decimal labels before it.

func (*DocumentWriter) AddRawImage

func (w *DocumentWriter) AddRawImage(width, height int, color ImageColor, samples, alpha []byte) (*CreatedImage, error)

AddRawImage adds an image from 8-bit samples; see Document.AddRawImage.

func (*DocumentWriter) AddStandardFont

func (w *DocumentWriter) AddStandardFont(font StandardFont) (CreatedFont, error)

AddStandardFont adds a standard font; see Document.AddStandardFont.

func (*DocumentWriter) BeginForm

func (w *DocumentWriter) BeginForm(bbox Rect) (*FormContent, error)

BeginForm starts a new form with the given bounding box; Commit writes it.

func (*DocumentWriter) BeginPage

func (w *DocumentWriter) BeginPage(width, height float64, rotate int) (*StreamPage, error)

BeginPage starts a page whose media box is [0 0 width height]. rotate is the page's /Rotate, a multiple of 90. Only one page is open at a time.

func (*DocumentWriter) BeginPrintPage

func (w *DocumentWriter) BeginPrintPage(trimWidth, trimHeight float64, s PrintSetup) (*StreamPage, error)

BeginPrintPage starts a page for print production. The media box is the trim size plus the bleed and the slug on every side; the bleed box is the media box less the slug; the trim box is the bleed box less the bleed; and there is no crop box, so viewers show the whole media box and the marks in the slug (ISO 32000-2 14.11.2). Drawing coordinates start at the lower left of the media box. With setup.Marks, the marks are drawn first, under what is drawn next; a slug smaller than their MinimumSlug on a side that needs room is ErrArgument.

Example
package main

import (
	"bytes"
	"fmt"

	"recursiveai.org/go/onepdf"
)

func main() {
	var out bytes.Buffer
	w := onepdf.NewDocumentWriter(&out)
	// A 100 x 60 trim size with a 5 point bleed and room for crop marks in the slug.
	page, err := w.BeginPrintPage(100, 60, onepdf.PrintSetup{
		Bleed: onepdf.UniformMargins(5),
		Slug:  onepdf.UniformMargins(20),
		Marks: &onepdf.PrinterMarks{Crop: true},
	})
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(page.Width(), page.Height())
	page.Commit()
	w.Finish()
}
Output:
150 110

func (*DocumentWriter) BeginReservedForm

func (w *DocumentWriter) BeginReservedForm(f *FormXObject) (*FormContent, error)

BeginReservedForm starts the content of a form made with ReserveForm; its Commit writes the form under the reserved reference. A form of another writer, or one already filled, is an error.

func (*DocumentWriter) BeginStructureElement

func (w *DocumentWriter) BeginStructureElement(typ string, o StructureOptions) (*StructNode, error)

BeginStructureElement begins a structure element under the innermost open element (or at the top of the tree). The first one makes the file tagged (ISO 32000-2 14.7, 14.8): /MarkInfo, /StructTreeRoot, /ParentTree and, on pages with tagged content, /StructParents and /Tabs /S. End it with EndStructureElement.

func (*DocumentWriter) BeginStructureElementUnder

func (w *DocumentWriter) BeginStructureElementUnder(parent *StructNode, typ string, o StructureOptions) (*StructNode, error)

BeginStructureElementUnder begins an element under an explicit parent, for content that continues on later pages, where several branches stay open, such as the cells of a table row that splits. Children are listed in the order they were begun. Like any begun element it becomes the innermost; end a specific one with EndStructureElementFor.

func (*DocumentWriter) BookmarkCount

func (w *DocumentWriter) BookmarkCount() int

BookmarkCount is the number of bookmarks added so far.

func (*DocumentWriter) BytesWritten

func (w *DocumentWriter) BytesWritten() int64

BytesWritten is the number of bytes handed to the output so far.

func (*DocumentWriter) CurrentStructureElement

func (w *DocumentWriter) CurrentStructureElement() *StructNode

CurrentStructureElement is the element begun last that has not ended, or nil.

func (*DocumentWriter) Diagnostics

func (w *DocumentWriter) Diagnostics() []Diagnostic

Diagnostics returns the notes made so far, in order: a character a font could not show, a damaged PNG chunk that was dropped.

func (*DocumentWriter) EndStructureElement

func (w *DocumentWriter) EndStructureElement() error

EndStructureElement ends the innermost open element and writes it. With none open it is ErrNotEditable.

func (*DocumentWriter) EndStructureElementFor

func (w *DocumentWriter) EndStructureElementFor(e *StructNode) error

EndStructureElementFor ends a specific element, after its own children, and writes it.

func (*DocumentWriter) Finish

func (w *DocumentWriter) Finish() error

Finish closes the document: it writes the outline, destinations, page labels, structure tree, page tree, catalog, information dictionary and the cross-reference data, and closes the output if WithWriterCloseOutput was given. A page, structure element or reserved form still open is ErrNotEditable and the writer stays usable; so is a second Finish.

func (*DocumentWriter) FinishContext

func (w *DocumentWriter) FinishContext(ctx context.Context) error

FinishContext is Finish that stops when ctx is done. The context is checked before the fonts are finished and before the document structure is written, which is where the work is. A writer that stopped for ctx is failed: its output is incomplete, later calls return ctx's error, and the caller should discard what was written.

Example
package main

import (
	"bytes"
	"context"
	"fmt"

	"recursiveai.org/go/onepdf"
)

func main() {
	var out bytes.Buffer
	w := onepdf.NewDocumentWriter(&out)
	p, _ := w.BeginPage(100, 100, 0)
	p.Commit()
	err := w.FinishContext(context.Background())
	fmt.Println(err)
}
Output:
<nil>

func (*DocumentWriter) MapRole

func (w *DocumentWriter) MapRole(custom, standard string) error

MapRole maps a custom structure type to a standard one (/RoleMap, ISO 32000-2 14.7.4.2).

func (*DocumentWriter) PageCount

func (w *DocumentWriter) PageCount() int

PageCount is the number of pages begun so far.

func (*DocumentWriter) ReserveForm

func (w *DocumentWriter) ReserveForm(bbox Rect) (*FormXObject, error)

ReserveForm gives a form its reference now so pages can draw it before it is filled; fill it with BeginReservedForm before Finish.

func (*DocumentWriter) SetBookmarkElement

func (w *DocumentWriter) SetBookmarkElement(index int, e *StructNode) error

SetBookmarkElement ties the bookmark at index to a structure element (/SE, ISO 32000-2 12.3.3).

func (*DocumentWriter) SetDestinationElement

func (w *DocumentWriter) SetDestinationElement(name string, e *StructNode) error

SetDestinationElement ties the named destination to a structure element.

func (*DocumentWriter) SetInfo

func (w *DocumentWriter) SetInfo(key, value string) error

SetInfo sets an entry of the document information dictionary (ISO 32000-2 14.3.3), such as Title, Author, Subject, Keywords or Creator. The dictionary is written at Finish. An empty key is ErrArgument.

type Duplex

type Duplex uint8

Duplex is the print dialog's duplex preference (ISO 32000-2 Table 147, /Duplex). The zero value means "not set".

const (
	// DuplexSimplex is /Simplex: single-sided.
	DuplexSimplex Duplex = iota + 1
	// DuplexFlipShortEdge is /DuplexFlipShortEdge: double-sided, flipped on the short edge.
	DuplexFlipShortEdge
	// DuplexFlipLongEdge is /DuplexFlipLongEdge: double-sided, flipped on the long edge.
	DuplexFlipLongEdge
)

The duplex values.

func ParseDuplex

func ParseDuplex(name string) (Duplex, error)

ParseDuplex reads "Simplex", "DuplexFlipShortEdge" or "DuplexFlipLongEdge"; anything else is ErrArgument.

func (Duplex) String

func (x Duplex) String() string

String returns the value's PDF name without the slash, or "" for the zero value.

type EmbedOption

type EmbedOption interface {
	// contains filtered or unexported methods
}

EmbedOption configures FontEmbedder and Document.EmbedFontProgram. An option that means nothing to one of them is ignored by it.

func WithBaseFontName

func WithBaseFontName(name string) EmbedOption

WithBaseFontName sets the font's base name, without subset tag. The default is the program's PostScript name, or "Font" when it has none.

func WithCIDsAreGlyphIDs

func WithCIDsAreGlyphIDs() EmbedOption

WithCIDsAreGlyphIDs makes EmbedFontProgram read the character ids of a Type 0 font as glyph indexes of the program instead of mapping them through Unicode.

func WithCodeToUnicode

func WithCodeToUnicode(m map[int]string) EmbedOption

WithCodeToUnicode gives EmbedFontProgram the text of codes the font cannot map itself. A text of one character also picks that character's glyph from the program; longer text only goes to /ToUnicode.

func WithCodes

func WithCodes(codes ...int) EmbedOption

WithCodes limits EmbedFontProgram to the given character codes (character ids for a Type 0 font). The default is the codes the document's pages show with the font, or every code of the font's /FirstChar to /LastChar (the /W entries of a Type 0 font) when no page shows it.

func WithGlyphForCode

func WithGlyphForCode(fn func(code int) int) EmbedOption

WithGlyphForCode picks the program glyph of a code. A result of 0 or less leaves the choice to the usual rules.

func WithIgnoreEmbeddingRestrictions

func WithIgnoreEmbeddingRestrictions() EmbedOption

WithIgnoreEmbeddingRestrictions embeds a font whose fsType forbids it. The licence is then the caller's responsibility.

func WithMissingGlyphs

func WithMissingGlyphs(p MissingGlyphPolicy) EmbedOption

WithMissingGlyphs sets what EmbedFontProgram does with a code the program has no glyph for. The default is MissingUseNotdef.

func WithOverrideToUnicode

func WithOverrideToUnicode() EmbedOption

WithOverrideToUnicode lets text from WithCodeToUnicode replace entries a /ToUnicode map already has; by default existing entries stay.

func WithReplaceProgram

func WithReplaceProgram() EmbedOption

WithReplaceProgram lets EmbedFontProgram swap the program of a font that already has one; without it such a font is refused with EmbedAlreadyEmbedded.

func WithSubsetting

func WithSubsetting(on bool) EmbedOption

WithSubsetting chooses whether only the glyphs in use are written. The default is true. A font whose fsType forbids subsetting is always written whole, whatever this says.

func WithWidthPolicy

func WithWidthPolicy(p WidthPolicy, tolerance float64) EmbedOption

WithWidthPolicy sets what EmbedFontProgram does when advances differ. tolerance is in thousandths of an em and is used by WidthsRefuse; zero or less means 1.

func WithWriteToUnicode

func WithWriteToUnicode(on bool) EmbedOption

WithWriteToUnicode chooses whether EmbedFontProgram writes /ToUnicode where the font's encoding does not already say what its codes mean. The default is true.

type EmbeddedFile

type EmbeddedFile struct {

	// Name is the file name: the specification's /UF, else its /F.
	Name string
	// Description is /Desc, or "".
	Description string
	// MIMEType is the embedded stream's /Subtype, such as "application/pdf", or "".
	MIMEType string
	// Size is /Params /Size, the size the writer states; it is not checked against the data.
	Size Opt[int64]
	// CheckSum is /Params /CheckSum, the MD5 digest the writer states, or nil. It is not verified.
	CheckSum []byte
	// Created and Modified are /Params /CreationDate and /ModDate in UTC; the zero time when absent.
	Created, Modified time.Time
	// Relationship is /AFRelationship (ISO 32000-2 14.13), such as "Source" or "Data", or "".
	Relationship string
	// Page is the zero-based page of the attachment annotation that holds the
	// file, or -1 for a file of the name tree.
	Page int
	// Spec is the file specification dictionary.
	Spec *Dict
	// contains filtered or unexported fields
}

EmbeddedFile is a file attached to the document (ISO 32000-2 7.11.4): an entry of the /EmbeddedFiles name tree, or the file of a file-attachment annotation. The listing reads only the file specification; the bytes are read on request with Content.

func (*EmbeddedFile) Content

func (f *EmbeddedFile) Content() ([]byte, error)

Content decodes and returns the file's bytes. It returns nil and no error for a specification without an embedded stream. The decoded size is bounded by Limits.MaxDecodedStream; an over-limit file gives an error matching ErrLimit.

func (*EmbeddedFile) HasContent

func (f *EmbeddedFile) HasContent() bool

HasContent reports whether the specification names an embedded stream.

func (*EmbeddedFile) Stream

func (f *EmbeddedFile) Stream() *Stream

Stream returns the embedded file stream, or nil when the specification has none.

type EmbeddingRights

type EmbeddingRights int

EmbeddingRights is what a font's OS/2 fsType field permits.

const (
	// RightsInstallable: the font may be embedded and used permanently.
	RightsInstallable EmbeddingRights = iota
	// RightsRestricted: the font must not be embedded (fsType bit 1).
	RightsRestricted
	// RightsPreviewAndPrint: embedding is allowed for viewing and printing only.
	RightsPreviewAndPrint
	// RightsEditable: embedding is allowed and the document may be edited.
	RightsEditable
	// RightsBitmapOnly: only bitmap embedding is allowed (fsType bit 9), so no outlines.
	RightsBitmapOnly
)

The embedding permissions of OpenType OS/2 fsType.

func (EmbeddingRights) String

func (r EmbeddingRights) String() string

String returns the name of the permission.

type EncryptOption

type EncryptOption interface {
	// contains filtered or unexported methods
}

EncryptOption adjusts WithEncryption.

func WithClearMetadata

func WithClearMetadata() EncryptOption

WithClearMetadata leaves the XMP metadata stream unencrypted so that tools can read it without the password (/EncryptMetadata false). The default encrypts it.

func WithPermissions

func WithPermissions(p Permissions) EncryptOption

WithPermissions sets the usage flags written to /P. The default is PermissionsAll. The flags are data for the readers that honour them; this library never enforces them. The bits the standard reserves are set as ISO 32000-2 Table 22 requires.

type EncryptionInfo

type EncryptionInfo struct {
	// Version is the algorithm version /V: 1, 2, 4 or 5.
	Version int
	// Revision is the handler revision /R: 2 to 6.
	Revision int
	// KeyBits is the length of the file encryption key in bits.
	KeyBits int
	// Cipher protects streams; when streams are in the clear it is the strings' cipher.
	Cipher Cipher
	// EncryptMetadata is false when the XMP metadata stream is stored in the clear.
	EncryptMetadata bool
	// RawPermissions is /P as a signed 32-bit value.
	RawPermissions int32
	// HasPerms is true when the file has a /Perms entry to check (revision 5 and 6).
	HasPerms bool
	// PermsValid is true when /Perms decrypts and agrees with /P and /EncryptMetadata.
	// A file whose /Perms is wrong still opens; this only reports it.
	PermsValid bool
}

EncryptionInfo describes the standard security handler of a document.

type EntryKind

type EntryKind uint8

EntryKind says what a cross-reference entry holds (ISO 32000-2 7.5.4, 7.5.8.3).

const (
	// EntryFree is a free object: deleted, or never used.
	EntryFree EntryKind = iota
	// EntryInUse is an object stored in the file at Offset.
	EntryInUse
	// EntryCompressed is an object stored in the object stream Container, at position Index.
	EntryCompressed
)

Entry kinds.

func (EntryKind) String

func (k EntryKind) String() string

String returns "Free", "InUse" or "Compressed".

type Field

type Field struct {
	// contains filtered or unexported fields
}

Field is one node of the form's field tree. Attributes the specification makes inheritable (/FT, /Ff, /V, /DV, /Opt, /MaxLen) are already resolved through the ancestors.

func (*Field) Children

func (f *Field) Children() []*Field

Children returns the sub-fields: kid dictionaries that have a partial name. The slice is the field's own; do not modify it.

func (*Field) Clear

func (fl *Field) Clear(opts ...FillOption) error

Clear removes the value of a text or choice field, or turns a check box or radio group off.

func (*Field) DefaultValue

func (fl *Field) DefaultValue() (string, bool)

DefaultValue returns /DV (inherited) as text; ok is false when absent.

func (*Field) Dict

func (f *Field) Dict() *Dict

Dict returns the field dictionary.

func (*Field) Flags

func (fl *Field) Flags() int64

Flags returns the field flags (/Ff, inherited) as written.

func (*Field) FullName

func (f *Field) FullName() string

FullName joins the partial names from the top with dots (ISO 32000-2 12.7.4.2).

func (*Field) IsMultiSelect

func (fl *Field) IsMultiSelect() bool

IsMultiSelect reports whether the FieldMultiSelect flag bit is set.

func (*Field) IsMultiline

func (fl *Field) IsMultiline() bool

IsMultiline reports whether the FieldMultiline flag bit is set.

func (*Field) IsPassword

func (fl *Field) IsPassword() bool

IsPassword reports whether the FieldPassword flag bit is set.

func (*Field) IsReadOnly

func (fl *Field) IsReadOnly() bool

IsReadOnly reports whether the FieldReadOnly flag bit is set.

func (*Field) IsRequired

func (fl *Field) IsRequired() bool

IsRequired reports whether the FieldRequired flag bit is set.

func (*Field) IsSigned

func (fl *Field) IsSigned() bool

IsSigned reports whether a signature field holds a signature (its /V is a dictionary).

func (*Field) Kind

func (fl *Field) Kind() FieldKind

Kind returns the field's type.

func (*Field) MaxLength

func (fl *Field) MaxLength() (n int, ok bool)

MaxLength returns /MaxLen (inherited); ok is false when absent.

func (*Field) Name

func (f *Field) Name() string

Name returns the partial name, /T as text; "" when the field has none.

func (*Field) Options

func (fl *Field) Options() []FieldOption

Options returns a choice field's /Opt entries (inherited). An entry is a string, or a two-string array of export value and display text; others are skipped.

func (*Field) Parent

func (f *Field) Parent() *Field

Parent returns the enclosing field, or nil for a top-level field.

func (*Field) RawValue

func (fl *Field) RawValue() Object

RawValue returns /V (inherited) as an object, references followed; nil when absent.

func (*Field) Rename

func (fl *Field) Rename(newName string) error

Rename changes the field's partial name /T (ISO 32000-2 12.7.4.2). newName is the last part only: the field stays under its parent and its widgets stay attached. A parent keeps its children, whose full names change with it. Renaming to the current name does nothing. It returns a *FormError and changes nothing when the name is empty or has a period (FormInvalidName), or when the field or a descendant would take the full name of a field outside the renamed subtree (FormNameInUse).

Example
package main

import (
	"fmt"

	"recursiveai.org/go/onepdf"
)

// exampleFormPDF is a one-page form with a text field and a check box. The file has no
// cross-reference table: the reader rebuilds it.
const exampleFormPDF = `%PDF-1.7
1 0 obj
<</Type /Catalog/Pages 2 0 R/AcroForm <</Fields [5 0 R 6 0 R]/DA (/Helv 0 Tf 0 g)/NeedAppearances true>>>>
endobj
2 0 obj
<</Type /Pages/Kids [3 0 R]/Count 1>>
endobj
3 0 obj
<</Type /Page/Parent 2 0 R/MediaBox [0 0 200 100]/Annots [5 0 R 6 0 R]>>
endobj
5 0 obj
<</Type /Annot/Subtype /Widget/FT /Tx/T (name)/MaxLen 8/Rect [10 60 150 80]/F 4>>
endobj
6 0 obj
<</Type /Annot/Subtype /Widget/FT /Btn/T (agree)/Rect [10 20 30 40]/F 4/AS /Off/V /Off/AP <</N <</Yes 7 0 R/Off 7 0 R>>>>>>
endobj
7 0 obj
<</Type /XObject/Subtype /Form/BBox [0 0 20 20]/Length 14>>
stream
0 0 20 20 re S
endstream
endobj
trailer
<</Root 1 0 R>>
`

func main() {
	doc, _ := onepdf.OpenBytes([]byte(exampleFormPDF), onepdf.WithEditing())
	form := doc.Form()
	fmt.Println(form.RenameField("name", "full.name"))
	fmt.Println(form.RenameField("name", "agree"))
	fmt.Println(form.RenameField("name", "fullName"), form.Find("fullName") != nil)
}
Output:
onepdf: form field "name": InvalidName: a partial name is not empty and has no period
onepdf: form field "name": NameInUse: the name "agree" is in use
<nil> true

func (*Field) Reset

func (fl *Field) Reset(opts ...FillOption) error

Reset sets the field back to its default (ISO 32000-2 12.7.4.1 /DV, inherited): the value becomes the default as stored (a default outside the options is kept), or is removed when there is none; a check box turns off; a radio group takes the default state when a widget has it, else turns off. Push buttons and signature fields are FormWrongType; a read-only field is FormReadOnly unless WithFillOverrideReadOnly is given.

func (*Field) SetAppearance

func (fl *Field) SetAppearance(style FieldStyle) (int, error)

SetAppearance changes the settings given in style and rebuilds the stored normal appearance of every widget, so viewers show the change without /NeedAppearances. It returns how many widgets were rebuilt.

Background and BorderColor write /MK /BG and /BC on each widget (a shared indirect /MK is copied first). FontSize and TextColor change the /DA string and keep its font; /DA is inheritable, so each terminal field in scope gets its own, built from the string it inherits. For a parent field every terminal field below it is changed, signature fields skipped; a signature field named directly is FormWrongType. Text, choice and push button widgets are redrawn; for check boxes and radio buttons every state in /AP /N is redrawn, replacing authored art. A font size outside 0..1000, or a transparent text colour, is ErrArgument and changes nothing.

Example
package main

import (
	"fmt"

	"recursiveai.org/go/onepdf"
)

// exampleFormPDF is a one-page form with a text field and a check box. The file has no
// cross-reference table: the reader rebuilds it.
const exampleFormPDF = `%PDF-1.7
1 0 obj
<</Type /Catalog/Pages 2 0 R/AcroForm <</Fields [5 0 R 6 0 R]/DA (/Helv 0 Tf 0 g)/NeedAppearances true>>>>
endobj
2 0 obj
<</Type /Pages/Kids [3 0 R]/Count 1>>
endobj
3 0 obj
<</Type /Page/Parent 2 0 R/MediaBox [0 0 200 100]/Annots [5 0 R 6 0 R]>>
endobj
5 0 obj
<</Type /Annot/Subtype /Widget/FT /Tx/T (name)/MaxLen 8/Rect [10 60 150 80]/F 4>>
endobj
6 0 obj
<</Type /Annot/Subtype /Widget/FT /Btn/T (agree)/Rect [10 20 30 40]/F 4/AS /Off/V /Off/AP <</N <</Yes 7 0 R/Off 7 0 R>>>>>>
endobj
7 0 obj
<</Type /XObject/Subtype /Form/BBox [0 0 20 20]/Length 14>>
stream
0 0 20 20 re S
endstream
endobj
trailer
<</Root 1 0 R>>
`

func main() {
	doc, _ := onepdf.OpenBytes([]byte(exampleFormPDF), onepdf.WithEditing())
	size := 14.0
	yellow := onepdf.FieldRGB(1, 1, 0.8)
	n, err := doc.Form().SetFieldAppearance("name", onepdf.FieldStyle{Background: &yellow, FontSize: &size})
	fmt.Println(n, err)
	da, _ := doc.Form().Find("name").Dict().Text("DA")
	fmt.Println(string(da))
}
Output:
1 <nil>
/Helv 14 Tf 0 g

func (*Field) SetChecked

func (fl *Field) SetChecked(on bool, opts ...FillOption) error

SetChecked checks (true) or clears (false) a check box or a radio group. Checking uses the first widget's on-state, or "Yes" when no widget has an appearance that names one.

func (*Field) SetValue

func (fl *Field) SetValue(value string, opts ...FillOption) error

SetValue stores value in the field and, unless WithFillAppearances is given, regenerates the field's widget appearances; the generator draws /DA, /Q, comb cells and multi-line text from the field's flags.

  • Text: /V becomes a text string (PDFDocEncoding when possible, else UTF-16BE) and a stale /RV is removed. /MaxLen counts code points: a longer value is FormTooLong, or cut with WithFillTruncate.
  • Combo and list boxes: value is matched against the export values in /Opt, then the display texts; /V stores the export value. An editable combo box takes any text.
  • Check boxes and radio buttons: value is an on-state name (a key of a widget's /AP /N other than Off), "Off", or, for a radio group with /Opt, an option text. /V and every widget's /AS are set.

A refused call returns a *FormError and changes nothing; a document that was not opened with WithEditing returns ErrNotEditable. Push buttons and signature fields are FormWrongType.

Example (TooLong)
package main

import (
	"errors"
	"fmt"

	"recursiveai.org/go/onepdf"
)

// exampleFormPDF is a one-page form with a text field and a check box. The file has no
// cross-reference table: the reader rebuilds it.
const exampleFormPDF = `%PDF-1.7
1 0 obj
<</Type /Catalog/Pages 2 0 R/AcroForm <</Fields [5 0 R 6 0 R]/DA (/Helv 0 Tf 0 g)/NeedAppearances true>>>>
endobj
2 0 obj
<</Type /Pages/Kids [3 0 R]/Count 1>>
endobj
3 0 obj
<</Type /Page/Parent 2 0 R/MediaBox [0 0 200 100]/Annots [5 0 R 6 0 R]>>
endobj
5 0 obj
<</Type /Annot/Subtype /Widget/FT /Tx/T (name)/MaxLen 8/Rect [10 60 150 80]/F 4>>
endobj
6 0 obj
<</Type /Annot/Subtype /Widget/FT /Btn/T (agree)/Rect [10 20 30 40]/F 4/AS /Off/V /Off/AP <</N <</Yes 7 0 R/Off 7 0 R>>>>>>
endobj
7 0 obj
<</Type /XObject/Subtype /Form/BBox [0 0 20 20]/Length 14>>
stream
0 0 20 20 re S
endstream
endobj
trailer
<</Root 1 0 R>>
`

func main() {
	doc, _ := onepdf.OpenBytes([]byte(exampleFormPDF), onepdf.WithEditing())
	field := doc.Form().Find("name")
	err := field.SetValue("abcdefghijklmnop")
	fmt.Println(errors.Is(err, onepdf.ErrForm))
	// /MaxLen counts code points; WithFillTruncate cuts the value instead of refusing it.
	fmt.Println(field.SetValue("abcdefghijklmnop", onepdf.WithFillTruncate()))
	v, _ := field.Value()
	fmt.Println(v)
}
Output:
true
<nil>
abcdefgh

func (*Field) SetValues

func (fl *Field) SetValues(values []string, opts ...FillOption) error

SetValues stores several values, for a multi-select list box: /V is an array of export values and /I the selected indices, both in option order with duplicates dropped. Any other field takes zero values (as Clear) or one (as SetValue); more is FormNotMultiSelect.

func (*Field) Value

func (fl *Field) Value() (string, bool)

Value returns the field's value as text: a string, a name (a check box state), the text of a stream, or the first element of an array. ok is false when the field has no text value, as for a signature or a field with no /V.

func (*Field) Values

func (fl *Field) Values() []string

Values returns every value of the field as text: one for a single value, all of them for a multi-select list box's array; none when there is no text value.

func (*Field) Widgets

func (f *Field) Widgets() []*Dict

Widgets returns the widget annotations of the field: the unnamed kids, or the field's own dictionary when it is merged with its widget. The slice is the field's own; do not modify it.

type FieldColor

type FieldColor struct {
	// contains filtered or unexported fields
}

FieldColor is a colour for a field's background, border or text: gray, RGB or CMYK components in 0..1, or transparent.

func FieldCMYK

func FieldCMYK(c, m, y, k float64) FieldColor

FieldCMYK is a DeviceCMYK colour.

func FieldGray

func FieldGray(g float64) FieldColor

FieldGray is a DeviceGray colour.

func FieldRGB

func FieldRGB(r, g, b float64) FieldColor

FieldRGB is a DeviceRGB colour.

func FieldTransparent

func FieldTransparent() FieldColor

FieldTransparent removes a background or border (/MK /BG, /BC). It is not a valid text colour.

type FieldKind

type FieldKind int

FieldKind is the type of an AcroForm field (ISO 32000-2 12.7.4).

const (
	FieldUnknown FieldKind = iota
	FieldText
	FieldCheckBox
	FieldRadioButton
	FieldPushButton
	FieldComboBox
	FieldListBox
	FieldSignature
)

Field kinds. A field with no usable /FT, such as a node that only groups children, is FieldUnknown.

func (FieldKind) String

func (k FieldKind) String() string

String returns the kind's name.

type FieldOption

type FieldOption struct {
	// Export is the value written to /V when the option is chosen.
	Export string
	// Display is the text shown; it equals Export for a plain string entry.
	Display string
}

FieldOption is one entry of a choice field's /Opt: the value stored and the text shown.

type FieldStyle

type FieldStyle struct {
	// Background is /MK /BG; FieldTransparent removes it.
	Background *FieldColor
	// BorderColor is /MK /BC; FieldTransparent removes it.
	BorderColor *FieldColor
	// TextColor replaces the colour operator of /DA. It must not be transparent.
	TextColor *FieldColor
	// FontSize is the /DA font size in points: 0 is automatic, at most 1000.
	FontSize *float64
}

FieldStyle lists the appearance settings to change; a nil setting is left alone.

type FillOption

type FillOption interface {
	// contains filtered or unexported methods
}

FillOption changes how a fill, reset or clear call behaves.

func WithFillAppearances

func WithFillAppearances(on bool) FillOption

WithFillAppearances says whether the call generates appearance streams for the widgets it fills (the default, true). With false it changes only /V and /AS: no appearance streams are generated and /NeedAppearances is left as it is.

func WithFillOverrideReadOnly

func WithFillOverrideReadOnly() FillOption

WithFillOverrideReadOnly fills a field that has the read-only flag.

func WithFillTruncate

func WithFillTruncate() FillOption

WithFillTruncate cuts a text value to its first /MaxLen code points instead of refusing it.

type Filter

type Filter struct {
	// Name is the filter's full name; an abbreviation such as Fl is expanded.
	Name Name
	// Params is the filter's decode parameters, or nil.
	Params *Dict
}

Filter is one step of a stream's decoding.

type FlattenOption

type FlattenOption interface {
	// contains filtered or unexported methods
}

FlattenOption configures Flatten.

func WithFlattenFieldNames

func WithFlattenFieldNames(names ...string) FlattenOption

WithFlattenFieldNames limits field flattening to the named fields and the fields under them. Without this option every field is flattened, widgets outside the field tree included. An unknown name is a *FormError (FormUnknownField).

func WithFlattenFields

func WithFlattenFields(on bool) FlattenOption

WithFlattenFields sets whether form fields are flattened (default true).

func WithFlattenGeneratedAppearances

func WithFlattenGeneratedAppearances(on bool) FlattenOption

WithFlattenGeneratedAppearances sets whether a widget or markup annotation with no stored appearance gets one generated and drawn (default true), as Interpret does, including the /NeedAppearances rule.

func WithFlattenMarkup

func WithFlattenMarkup() FlattenOption

WithFlattenMarkup also flattens every annotation other than widgets, links and pop-ups (off by default).

func WithFlattenVisibility

func WithFlattenVisibility(m AnnotationMode) FlattenOption

WithFlattenVisibility chooses which annotations are drawn: AnnotationsView (the default) draws what is not Hidden and not NoView; AnnotationsPrint draws what has the Print flag and is not Hidden. AnnotationsNone is refused with ErrArgument. Annotations that are not drawn are still removed.

type FlattenResult

type FlattenResult struct {
	// Drawn is the number of annotation appearances drawn into the page content.
	Drawn int
	// Removed is the number of annotations taken off the pages, drawn or not (hidden ones and pop-ups included).
	Removed int
	// FieldsRemoved is the number of fields taken out of the form.
	FieldsRemoved int
	// SignedKept is the number of signed signature fields left in the form with their widgets.
	SignedKept int
	// FormRemoved reports that the document has no form afterwards: /AcroForm was dropped because
	// no field was left, or the document had none.
	FormRemoved bool
}

FlattenResult counts what Flatten did.

type FontEmbedError

type FontEmbedError struct {
	Reason FontEmbedReason
	// Codes are the character codes or glyphs the refusal is about, ascending.
	Codes   []int
	Message string
}

FontEmbedError is returned when a font program or font dictionary is refused. Use errors.As for the reason and the codes involved.

func (*FontEmbedError) Error

func (e *FontEmbedError) Error() string

Error returns the reason the font program could not be embedded.

func (*FontEmbedError) Is

func (e *FontEmbedError) Is(target error) bool

Is reports a match with ErrFontEmbed.

type FontEmbedReason

type FontEmbedReason int

FontEmbedReason says why a font program was refused.

const (
	// EmbedNoGlyphForCode: the program has no glyph for a code the caller asked for.
	EmbedNoGlyphForCode FontEmbedReason = iota + 1
	// EmbedProgramForbidsEmbedding: the program's fsType forbids embedding.
	EmbedProgramForbidsEmbedding
	// EmbedAlreadyEmbedded: the font already has a program and replacing was not asked for.
	EmbedAlreadyEmbedded
	// EmbedType3Font: Type 3 fonts have no font program.
	EmbedType3Font
	// EmbedUnsupportedFont: the font dictionary is not one a program can be put into.
	EmbedUnsupportedFont
	// EmbedUnsupportedProgram: the program is not one this operation can write (for example CFF into a simple font).
	EmbedUnsupportedProgram
	// EmbedWidthMismatch: the program's advances differ from the PDF's by more than allowed.
	EmbedWidthMismatch
	// EmbedTooLarge: the program or the glyph set exceeds the format's maxima.
	EmbedTooLarge
)

The reasons a font program is refused.

func (FontEmbedReason) String

func (r FontEmbedReason) String() string

String returns the reason's name, such as "NoGlyphForCode".

type FontEmbedResult

type FontEmbedResult struct {
	// BaseFont is the font's new base name, with its subset tag when the
	// program is a subset.
	BaseFont string
	// Symbolic is true when the font was embedded as a symbolic font: no
	// /Encoding, codes mapped through the program's (3,0) cmap.
	Symbolic bool
	// ToUnicodeWritten is true when a /ToUnicode map was written or extended.
	ToUnicodeWritten bool
	// FontFile is the stream holding the program.
	FontFile Ref
	// EmbeddedCodes are the codes that got a glyph of their own; MissingCodes
	// the codes the program has no glyph for, which draw .notdef.
	EmbeddedCodes, MissingCodes []int
	// WidthConflicts are codes that share a glyph with an earlier code of a
	// different width; the glyph keeps the earlier width.
	WidthConflicts []int
	// CodesWithoutUnicode are embedded codes no text is known for.
	CodesWithoutUnicode []int
	// WidthChanges lists codes whose PDF width and program advance differ by
	// more than half a thousandth of an em.
	WidthChanges []FontWidthChange
}

FontEmbedResult says what EmbedFontProgram did.

type FontEmbedder

type FontEmbedder struct {
	// contains filtered or unexported fields
}

A FontEmbedder writes one font program into a document as a Type 0 font with the Identity-H encoding, for callers that lay out text themselves and select glyphs by glyph index.

The caller shows text with two-byte codes that are glyph indexes of the original font, as returned by shaping (<0042> shows glyph 66). It records each glyph it shows with FontEmbedder.Use, then calls FontEmbedder.Finish once, and puts the returned reference under a page's /Resources /Font with a name of its own. Because the subset renumbers glyphs, the embedder tells the caller nothing about the new numbering: the written font maps the codes the caller used (original glyph indexes) to the subset's glyphs through its /CIDToGIDMap or its charset.

A FontEmbedder is not safe for concurrent use.

Example
package main

import (
	"fmt"
	"os"

	"recursiveai.org/go/onepdf"
)

func exampleFont(name string) *onepdf.FontFile {
	data, err := os.ReadFile("testdata/embed/" + name)
	if err != nil {
		panic(err)
	}
	f, err := onepdf.OpenFontFile(data, 0)
	if err != nil {
		panic(err)
	}
	return f
}

func main() {
	doc, _ := onepdf.New()
	f := exampleFont("kit-text.ttf")
	emb, err := onepdf.NewFontEmbedder(f)
	if err != nil {
		fmt.Println(err)
		return
	}
	// Two glyphs that a shaper chose, and the text they stand for.
	a, b := f.GlyphForUnicode('A'), f.GlyphForUnicode('B')
	emb.Use(a, "A")
	emb.UseCluster([]int{b}, "B")
	fmt.Println("advance of A:", emb.Advance(a), "thousandths of an em")
	ref, err := emb.Finish(doc) // the Type 0 font; name it in a page's /Resources
	fmt.Println(err, ref.Number > 0)
}
Output:
advance of A: 600 thousandths of an em
<nil> true

func NewFontEmbedder

func NewFontEmbedder(file *FontFile, opts ...EmbedOption) (*FontEmbedder, error)

NewFontEmbedder starts an embedder for a font. It returns a FontEmbedError with EmbedProgramForbidsEmbedding when fsType forbids embedding, unless WithIgnoreEmbeddingRestrictions is given.

func (*FontEmbedder) Advance

func (e *FontEmbedder) Advance(gid int) float64

Advance returns the advance of a glyph in thousandths of an em, as a whole number: round(units * 1000 / unitsPerEm), exactly the value Finish writes to /W, so a caller that positions text with it (TJ adjustments, line breaking) agrees with the font. It is 0 for a glyph outside the font.

func (*FontEmbedder) Finish

func (e *FontEmbedder) Finish(doc *Document) (Ref, error)

Finish writes the font into doc and returns the reference of its Type 0 font dictionary. The document must be editable (WithEditing or New). It writes, in this order and with the next free object numbers: the font program, the font descriptor, the descendant CIDFont (CIDFontType2 for glyf outlines, CIDFontType0 for CFF), a /CIDToGIDMap or CFF charset, /W for the glyphs in use, and the Type 0 font with /ToUnicode.

The output depends only on the font and what was recorded: glyphs are written in ascending order, the subset tag is derived from the font name and the glyph set, and nothing reads the clock. A font is written once; a second call returns the same reference.

func (*FontEmbedder) Use

func (e *FontEmbedder) Use(gid int, text string) error

Use records that glyph gid is shown and stands for text. text may be empty (the glyph then has no /ToUnicode entry) and may hold several characters, as a ligature does ("fi"). A glyph recorded again keeps its first non-empty text. A glyph outside the font is an error matching ErrArgument; Use after FontEmbedder.Finish is ErrNotEditable-free and also an ErrArgument.

func (*FontEmbedder) UseCluster

func (e *FontEmbedder) UseCluster(gids []int, text string) error

UseCluster records glyphs that together stand for text, as the glyphs of one cluster do after shaping (a reordered Indic syllable, a base letter with marks). A /ToUnicode map is a map from one code to text, so it cannot say that three glyphs make one syllable: the first glyph gets the whole text and the others get no entry, which extraction reads back as the text once, in order. Use FontEmbedder.Use for one glyph per text.

type FontFile

type FontFile struct {
	// contains filtered or unexported fields
}

A FontFile is a font program read for embedding: TrueType, OpenType with TrueType or CFF outlines, or bare CFF. It is immutable and safe for concurrent use once opened.

func OpenFontFile

func OpenFontFile(data []byte, face int) (*FontFile, error)

OpenFontFile reads a font program. A collection (TTC) is read at face, the index of the font in it; every other format has only face 0. The bytes are kept, not copied: the caller must not change them afterwards.

A damaged program, or a face index past the collection, returns an error matching ErrFormat; a negative face is ErrArgument.

Example
package main

import (
	"fmt"
	"os"

	"recursiveai.org/go/onepdf"
)

func exampleFont(name string) *onepdf.FontFile {
	data, err := os.ReadFile("testdata/embed/" + name)
	if err != nil {
		panic(err)
	}
	f, err := onepdf.OpenFontFile(data, 0)
	if err != nil {
		panic(err)
	}
	return f
}

func main() {
	f := exampleFont("kit-text.ttf")
	fmt.Println(f.Kind(), f.PostScriptName(), f.GlyphCount(), "glyphs")
	fmt.Println(f.EmbeddingRights(), f.AllowsSubsetting())
	gid := f.GlyphForUnicode('A')
	w, _ := f.AdvanceWidth(gid)
	fmt.Println("A is glyph", gid, "and advances", w)
}
Output:
TrueType KitText 70 glyphs
Installable true
A is glyph 2 and advances 600

func (*FontFile) AdvanceWidth

func (f *FontFile) AdvanceWidth(gid int) (float64, error)

AdvanceWidth returns the advance of a glyph in thousandths of an em. A glyph the font does not have is an error matching ErrArgument.

func (*FontFile) AllowsEmbedding

func (f *FontFile) AllowsEmbedding() bool

AllowsEmbedding reports whether fsType lets the font be embedded at all: it is false for RightsRestricted and RightsBitmapOnly.

func (*FontFile) AllowsSubsetting

func (f *FontFile) AllowsSubsetting() bool

AllowsSubsetting reports whether fsType leaves bit 8 (no subsetting) clear.

func (*FontFile) Ascent

func (f *FontFile) Ascent() float64

Ascent is the distance from the baseline to the top of the line in em, from the horizontal header (OpenType hhea). A program without one, such as bare CFF, gets 0.9.

func (*FontFile) Data

func (f *FontFile) Data() []byte

Data returns the font file as it was given.

func (*FontFile) Descent

func (f *FontFile) Descent() float64

Descent is the distance from the baseline to the bottom of the line in em, zero or negative, from hhea; -0.2 when the program has none.

func (*FontFile) EmbeddingRights

func (f *FontFile) EmbeddingRights() EmbeddingRights

EmbeddingRights returns the permission fsType gives. Bits 1 to 3 of the OS/2 table are meant to be exclusive, and the OpenType specification says Restricted License embedding takes effect only when bit 1 is the one bit set there. When several are set, the least restrictive permission wins (the rule OS/2 versions 0 to 2 state, and what the specification says applications may assume): 0x0006 is RightsPreviewAndPrint, 0x000C and 0x000E are RightsEditable. Bit 0 is reserved and ignored. Bit 9 (bitmaps only) gives RightsBitmapOnly unless bit 1 stands alone.

func (*FontFile) Face

func (f *FontFile) Face() int

Face returns the collection index the font was opened at.

func (*FontFile) FsType

func (f *FontFile) FsType() int

FsType returns the OS/2 embedding flags, 0 when the font has none (bare CFF has no OS/2 table).

func (*FontFile) GlyphCount

func (f *FontFile) GlyphCount() int

GlyphCount returns the number of glyphs, .notdef included.

func (*FontFile) GlyphForName

func (f *FontFile) GlyphForName(name string) int

GlyphForName returns the glyph with a glyph name, 0 when there is none.

func (*FontFile) GlyphForSymbolicCode

func (f *FontFile) GlyphForSymbolicCode(code int) int

GlyphForSymbolicCode returns the glyph a (3,0) character map gives a one-byte code, also trying the 0xF000, 0xF100 and 0xF200 offsets symbol fonts use (ISO 32000-2 9.6.5.4); 0 when none.

func (*FontFile) GlyphForUnicode

func (f *FontFile) GlyphForUnicode(cp int) int

GlyphForUnicode returns the glyph the Unicode character map gives a code point, 0 when there is none (or no character map).

func (*FontFile) GlyphName

func (f *FontFile) GlyphName(gid int) string

GlyphName returns the name of a glyph, "" when unnamed or out of range; glyph 0 is ".notdef".

func (*FontFile) HasGlyphNames

func (f *FontFile) HasGlyphNames() bool

HasGlyphNames reports whether glyphs have names (a post table with names, or a CFF charset of a font that is not CID-keyed).

func (*FontFile) HasSymbolicCmap

func (f *FontFile) HasSymbolicCmap() bool

HasSymbolicCmap reports whether the font has a (3,0) character map.

func (*FontFile) HasUnicodeCmap

func (f *FontFile) HasUnicodeCmap() bool

HasUnicodeCmap reports whether the font has a Unicode character map.

func (*FontFile) Kind

func (f *FontFile) Kind() FontKind

Kind returns the program format.

func (*FontFile) PostScriptName

func (f *FontFile) PostScriptName() string

PostScriptName returns the PostScript name (name ID 6, or the CFF font name), "" if the font has none.

func (*FontFile) TryAdvanceWidth

func (f *FontFile) TryAdvanceWidth(gid int) (float64, bool)

TryAdvanceWidth is FontFile.AdvanceWidth without the error: it returns 0 and false for a glyph the font does not have.

func (*FontFile) UnitsPerEm

func (f *FontFile) UnitsPerEm() int

UnitsPerEm returns the size of the em square in font units (1000 for CFF programs without a FontMatrix).

type FontKind

type FontKind int

FontKind is the format of a font program read by OpenFontFile.

const (
	// FontTrueType is an sfnt with glyf outlines.
	FontTrueType FontKind = iota + 1
	// FontOpenTypeCFF is an sfnt whose outlines are a CFF table.
	FontOpenTypeCFF
	// FontCFF is a bare Compact Font Format program.
	FontCFF
)

The program formats a FontFile reads.

func (FontKind) String

func (k FontKind) String() string

String returns "TrueType", "OpenTypeCff" or "Cff".

type FontProvider

type FontProvider interface {
	// FindFont returns the face for a request, or false for none.
	FindFont(req FontRequest) (*Substitute, bool)
}

A FontProvider supplies a stand-in program for fonts a PDF does not embed. The library finds glyphs by name, then by Unicode, and scales them horizontally to the widths the PDF gives, within 0.4 to 2.5 times. A provider must be safe for concurrent use and must not fetch anything.

func DefaultFontProvider

func DefaultFontProvider() FontProvider

DefaultFontProvider returns the providers every document without one of its own uses, as one: the registered providers in registration order. It is nil when there are none. Installed fonts are not part of it; a document opened with WithSystemFonts consults them as well.

func SystemFontProvider

func SystemFontProvider(dirs ...string) FontProvider

SystemFontProvider returns a provider over installed fonts, whatever the document says. With no directories it reads the platform's font directories and ONEPDF_FONT_DIRS; with directories, only those. The directories are listed on the first request, up to 8 levels deep and 50,000 files; only the name tables are read for the listing, and a program is read whole when it is chosen.

Example
package main

import (
	"fmt"
	"os"

	"recursiveai.org/go/onepdf"
)

func exampleFont(name string) *onepdf.FontFile {
	data, err := os.ReadFile("testdata/embed/" + name)
	if err != nil {
		panic(err)
	}
	f, err := onepdf.OpenFontFile(data, 0)
	if err != nil {
		panic(err)
	}
	return f
}

func main() {
	// Installed fonts are read only when asked for: from the directories named
	// here, or with no argument from the platform's font directories and
	// those in ONEPDF_FONT_DIRS.
	p := onepdf.SystemFontProvider("testdata/embed")
	sub, ok := p.FindFont(onepdf.FontRequest{Name: exampleFont("kit-text.ttf").PostScriptName()})
	fmt.Println(ok, sub.FaceIndex)
}
Output:
true 0

type FontRequest

type FontRequest struct {
	// Name is the BaseFont without its subset tag.
	Name string
	// Family is the font family; it is the Name when the font gives none.
	Family string
	// Standard14 is the standard face the name stands for ("Helvetica-Bold"), "" if none.
	Standard14 string
	// Flags from the font descriptor, as booleans.
	Bold, Italic, Serif, FixedPitch, Symbolic bool
	// Ordering is the character collection of a CID font ("Japan1", "GB1",
	// "CNS1", "Korea1", "KR"), "" otherwise.
	Ordering string
	// Vertical is true for a font used in vertical writing mode.
	Vertical bool
	// AnyFace is set when the font is being drawn, not embedded: a provider
	// may then answer a name it does not know with a generic face chosen by
	// the descriptor flags (ISO 32000-2 9.6.2.2, 9.8.2): serif, fixed pitch,
	// else sans serif. Embedding leaves it unset, so a font with no
	// metric-compatible face stays without one.
	AnyFace bool
}

FontRequest describes a font a document uses without embedding it, for a FontProvider to answer.

type FontWidthChange

type FontWidthChange struct {
	Code int
	// PDFWidth and ProgramWidth are in thousandths of an em.
	PDFWidth, ProgramWidth float64
}

FontWidthChange is a code whose width in the PDF differs from the advance of the glyph the program has for it.

type FormContent

type FormContent struct {
	*ContentBuilder
	// contains filtered or unexported fields
}

FormContent is a ContentBuilder that makes a Form XObject. Commit stores the form and returns it.

func (*FormContent) Commit

func (f *FormContent) Commit() (*FormXObject, error)

Commit stores the form and closes the builder. It returns the first error a call recorded, in which case nothing is stored.

func (*FormContent) SetTransparencyGroup

func (f *FormContent) SetTransparencyGroup(isolated, knockout bool)

SetTransparencyGroup makes the form a transparency group (ISO 32000-2 11.6.6): isolated groups do not see what is behind them, knockout groups let each object replace the ones before it.

type FormError

type FormError struct {
	// Reason says why the call was refused.
	Reason FormReason
	// Field is the fully qualified name the call was about.
	Field string
	// Message describes the refusal.
	Message string
}

FormError is the error of every refused form call. It matches ErrForm and ErrArgument.

func (*FormError) Error

func (e *FormError) Error() string

Error returns the failure message, naming the field when one is involved.

func (*FormError) Is

func (e *FormError) Is(target error) bool

Is reports a match with ErrForm and ErrArgument.

type FormReason

type FormReason int

FormReason says why a form call was refused.

const (
	// FormUnknownField: no field has that fully qualified name.
	FormUnknownField FormReason = iota + 1
	// FormWrongType: the call does not fit the field (a check for a text field, a value for a push button or signature).
	FormWrongType
	// FormReadOnly: the field has the read-only flag; WithFillOverrideReadOnly fills it anyway.
	FormReadOnly
	// FormNotInOptions: the value is not in /Opt (combo and list boxes), or not an on-state of the widgets (check boxes and radio buttons).
	FormNotInOptions
	// FormTooLong: a text value is longer than /MaxLen code points; WithFillTruncate cuts it instead.
	FormTooLong
	// FormNotMultiSelect: several values for a field that is not a multi-select list box.
	FormNotMultiSelect
	// FormNotTerminal: the field has child fields; fill the leaves.
	FormNotTerminal
	// FormInvalidName: a new partial name that is empty or contains a period.
	FormInvalidName
	// FormNameInUse: renaming would give a field the full name of a field outside the renamed subtree.
	FormNameInUse
)

The reasons a form call is refused. A refused call changes nothing.

func (FormReason) String

func (r FormReason) String() string

String returns the reason's name without the Form prefix, such as "NotInOptions".

type FormXObject

type FormXObject struct {
	// contains filtered or unexported fields
}

FormXObject is a Form XObject a document or writer holds: a piece of content drawn any number of times, on any pages, with ContentBuilder.DrawForm.

func (*FormXObject) BoundingBox

func (f *FormXObject) BoundingBox() Rect

BoundingBox is the form's /BBox in its own space.

func (*FormXObject) Ref

func (f *FormXObject) Ref() Ref

Ref is the reference of the form.

type FormatError

type FormatError struct {
	// Object is the number of the object where the damage was found, or -1.
	Object int
	// Offset is the byte offset of the damage in the source, or -1.
	Offset int64
	// Message says what is wrong.
	Message string
}

FormatError describes where a document is damaged. It matches ErrFormat.

func (*FormatError) Error

func (e *FormatError) Error() string

Error returns the problem, with the byte offset and object number where they are known.

func (*FormatError) Is

func (e *FormatError) Is(target error) bool

Is reports a match with ErrFormat.

type GeneratedAppearance

type GeneratedAppearance struct {
	// Stream is the Form XObject: its dictionary (/BBox, /Matrix, /Resources)
	// and content. It belongs to no document; add it with the writer to store it.
	Stream *Stream
	// Dict is Stream's dictionary.
	Dict *Dict
	// Rect is the annotation rectangle the appearance fits, in default user
	// space. It can differ from the annotation's /Rect, for instance when a
	// line's ends or the border's width grow it.
	Rect Rect
	// Content is the content stream's bytes.
	Content []byte
}

GeneratedAppearance is a normal appearance built from an annotation's dictionary, for annotations that have no stored one.

type Gradient

type Gradient struct {
	// contains filtered or unexported fields
}

Gradient is a smooth colour transition, painted over the current clipping region with ContentBuilder.PaintGradient (the sh operator, ISO 32000-2 8.7.4.2). A Gradient is immutable and may be used by any number of builders. Make one with NewAxialGradient or NewRadialGradient.

func NewAxialGradient

func NewAxialGradient(x0, y0, x1, y1 float64, stops []GradientStop, opts ...GradientOption) (*Gradient, error)

NewAxialGradient makes a gradient along the line from (x0, y0) to (x1, y1). Coordinates are in the user space current where the gradient is painted.

The stops must be at least two, in one colour space, with positions from 0 to 1 that do not decrease; the colour before the first and after the last is held, and two stops at one position make a hard edge. Two stops become one exponential function (type 2), more become a stitching function (type 3). Anything else is ErrArgument.

Example
package main

import (
	"fmt"

	"recursiveai.org/go/onepdf"
)

func main() {
	doc, _ := onepdf.New()
	doc.InsertBlankPage(0, 200, 100)
	red, blue := onepdf.RGBColor(1, 0, 0), onepdf.RGBColor(0, 0, 1)
	g, err := onepdf.NewAxialGradient(0, 0, 200, 0, []onepdf.GradientStop{{Position: 0, Color: red}, {Position: 1, Color: blue}})
	if err != nil {
		fmt.Println(err)
		return
	}
	pc, _ := doc.BeginContent(0, onepdf.PlaceOver)
	pc.FillRectangle(0, 0, 200, 100, g)
	fmt.Println(pc.Commit())
	// A gradient with decreasing stops is refused.
	_, err = onepdf.NewAxialGradient(0, 0, 1, 0, []onepdf.GradientStop{{Position: 0.8, Color: red}, {Position: 0.2, Color: blue}})
	fmt.Println(err)
}
Output:
<nil>
onepdf: invalid argument: stop 1: positions must not decrease

func NewRadialGradient

func NewRadialGradient(x0, y0, r0, x1, y1, r1 float64, stops []GradientStop, opts ...GradientOption) (*Gradient, error)

NewRadialGradient makes a gradient between the circle at (x0, y0) of radius r0 and the circle at (x1, y1) of radius r1. The radii cannot be negative. Stops and options are as for NewAxialGradient.

type GradientColor

type GradientColor struct {
	// contains filtered or unexported fields
}

GradientColor is a colour in one of the device colour spaces, for the stops of a Gradient.

func CMYKColor

func CMYKColor(c, m, y, k float64) GradientColor

CMYKColor is a DeviceCMYK colour.

func GrayColor

func GrayColor(g float64) GradientColor

GrayColor is a DeviceGray colour, 0 (black) to 1 (white).

func RGBColor

func RGBColor(r, g, b float64) GradientColor

RGBColor is a DeviceRGB colour.

type GradientOption

type GradientOption interface {
	// contains filtered or unexported methods
}

GradientOption changes how a gradient is made.

func WithGradientExtend

func WithGradientExtend(start, end bool) GradientOption

WithGradientExtend says whether the end colours continue past the start and the end of the axis, or past the circles of a radial gradient. Both default to true.

type GradientStop

type GradientStop struct {
	Position float64
	Color    GradientColor
}

GradientStop is a colour at a position along a gradient, 0 at the start and 1 at the end.

type Image

type Image struct {
	Kind          ImageKind
	Width, Height int
	// Space is the colour space of Samples.
	Space ImageSpace
	// Samples has Width*Height*Space.Components bytes for ImageDecoded.
	Samples []byte
	// Coverage has Width*Height bytes for ImageStencil.
	Coverage []byte
	// Alpha is the opacity from a soft mask, explicit mask, colour-key mask
	// or SMaskInData; it may be smaller or larger than the image. Nil for an
	// opaque image.
	Alpha *ImagePlane
	// Interpolate is the /Interpolate flag.
	Interpolate bool
	// Intent is the /Intent name, or "".
	Intent Name
	// BitsPerComponent is the depth the samples were stored at.
	BitsPerComponent int
	// AdobeTransform is the Adobe APP14 transform flag a DCT decoder
	// reported (0, 1 or 2), or -1. It is data only: the samples are as the
	// decoder gave them, and only /Decode inverts Adobe CMYK (ISO 32000-2 8.9.5.2).
	AdobeTransform int

	// Encoded is the stream's stored bytes for an ImageEncoded image; Filter
	// names the codec that was not applied and Globals holds the decoded
	// JBIG2Globals stream, if any.
	Encoded []byte
	Filter  Name
	Globals []byte
	// Semantics holds what the dictionary says about encoded samples, so a
	// device that decodes the codec itself can apply the PDF rules. Set for ImageEncoded.
	Semantics *ImageSemantics
}

Image is an image stream with every PDF image rule applied except the final colour conversion.

type ImageColor

type ImageColor int

ImageColor is the colour model of the samples AddRawImage takes.

const (
	ImageGray ImageColor = iota
	ImageRGB
	ImageCMYK
)

The colour models: 8-bit samples, interleaved, rows top to bottom.

func (ImageColor) String

func (c ImageColor) String() string

String returns "Gray", "RGB" or "CMYK".

type ImageDecoder

type ImageDecoder interface {
	DecodeImage(req *ImageRequest) (*DecodedImage, error)
}

ImageDecoder decodes one image codec's data into raw samples. An implementation must be safe for concurrent use and must treat Data as untrusted. A returned error leaves the image undecoded and noted as a diagnostic; a panic is recovered and treated the same way.

type ImageDecoderFunc

type ImageDecoderFunc func(req *ImageRequest) (*DecodedImage, error)

ImageDecoderFunc adapts a function to ImageDecoder.

func (ImageDecoderFunc) DecodeImage

func (f ImageDecoderFunc) DecodeImage(req *ImageRequest) (*DecodedImage, error)

DecodeImage calls f.

type ImageDecoders

type ImageDecoders struct {
	// contains filtered or unexported fields
}

ImageDecoders is a set of image decoders keyed by codec. The zero value is not ready; use NewImageDecoders. It is safe for concurrent use.

func DefaultImageDecoders

func DefaultImageDecoders() *ImageDecoders

DefaultImageDecoders returns the set a document uses when it is not opened with WithImageDecoders. It is one set for the process, and it starts empty: onepdf ships no codec, so a program (or the package that provides the codecs) registers them, usually through RegisterImageDecoder. Registering in it affects every document that uses it; for a set of your own use NewImageDecoders or Clone and WithImageDecoders.

func NewImageDecoders

func NewImageDecoders() *ImageDecoders

NewImageDecoders returns an empty set.

func (*ImageDecoders) Clone

func (r *ImageDecoders) Clone() *ImageDecoders

Clone returns an independent copy: later changes to either set do not reach the other.

func (*ImageDecoders) Has

func (r *ImageDecoders) Has(name string) bool

Has reports whether a decoder is registered for filter.

func (*ImageDecoders) Lookup

func (r *ImageDecoders) Lookup(name string) (ImageDecoder, bool)

Lookup returns the decoder for filter.

func (*ImageDecoders) Register

func (r *ImageDecoders) Register(name string, d ImageDecoder) error

Register sets the decoder for filter, replacing any earlier one; a nil decoder removes it. A name that is not an image codec returns ErrNotImageCodec.

func (*ImageDecoders) Unregister

func (r *ImageDecoders) Unregister(name string) bool

Unregister removes the decoder for filter and reports whether there was one.

type ImageKind

type ImageKind = device.ImageKind

ImageKind says what an Image holds. It is the device package's type.

type ImageOptions

type ImageOptions struct {
	// Space overrides the image's own /ColorSpace, for a caller that has
	// already resolved it (an inline image naming a page resource, say).
	Space *ImageSpace
	// Resources looks up a named colour space in the page's resources.
	Resources func(Name) Object
	// PreferEncoded leaves DCT and JPX images undecoded: the result is
	// ImageEncoded with the stored bytes and Semantics. Other images are unaffected.
	PreferEncoded bool
	// TargetWidth and TargetHeight, when positive, say how many pixels the
	// image will be drawn at. They go to the codec's decoder as a hint (see
	// ImageRequest), and a decoder that honours them returns a smaller image:
	// the result's Width and Height are then smaller than the dictionary's.
	// Zero, the default, means full size.
	TargetWidth, TargetHeight int
}

ImageOptions tune DecodeImage. The zero value decodes everything it can.

type ImagePlane

type ImagePlane struct {
	Width, Height int
	Pix           []byte
}

ImagePlane is a one-channel 8-bit raster, rows top to bottom with no padding.

type ImageRequest

type ImageRequest struct {
	// Filter is the codec's full name: "DCTDecode", "JPXDecode" or "JBIG2Decode".
	Filter string
	// Data is the codec's input: the stream's bytes after any filters that
	// come before the codec in the /Filter array have been undone.
	Data []byte
	// Globals is the decoded /JBIG2Globals stream, or nil.
	Globals []byte
	// Width, Height and BitsPerComponent are the image dictionary's values
	// (0 when absent). The codestream is authoritative; these are hints.
	Width, Height, BitsPerComponent int
	// ColorTransform is the DCT filter's /ColorTransform parameter, or -1 when it is absent.
	ColorTransform int
	// MaxPixels is the most pixels the image may have (0 means no limit). A
	// decoder should refuse a larger image before allocating it.
	MaxPixels int64
	// TargetWidth and TargetHeight, when positive, are the size in pixels the
	// image will be drawn at: a hint that lets a decoder that can (DCT with
	// scaled decoding, JPX with fewer resolution levels, JBIG2 by
	// subsampling) return a smaller image and save work. A decoder may ignore
	// them and return the full size; if it reduces, it should stay at least as
	// large as the target. onepdf uses the width and height of the
	// DecodedImage it gets, and masks and the device fit it to the image
	// rectangle either way. Both are 0 when the caller did not say, and a
	// decoder then decodes at full size.
	TargetWidth, TargetHeight int
}

ImageRequest is what a decoder is asked to decode.

type ImageSemantics

type ImageSemantics struct {
	Decode         []float64
	ColorKey       []int
	Matte          []float64
	SMaskInData    int
	BitsPerComp    int
	AdobeTransform int // -1 when there is no APP14 marker or the data was not decoded
}

ImageSemantics are the dictionary entries that govern how raw samples become colours (ISO 32000-2 8.9.5).

type ImageSpace

type ImageSpace struct {
	// Family is the colour space family: DeviceGray, DeviceRGB, DeviceCMYK,
	// CalGray, CalRGB, Lab, ICCBased, Indexed, Separation or DeviceN.
	Family Name
	// Components is the number of samples per pixel.
	Components int
	// Range holds a min and max per component: the span the finished 8-bit
	// samples stand for. [0 1] for most spaces; Lab and ICC /Range differ.
	// Unused for Indexed.
	Range []float64
	// HiVal is the largest index of an Indexed space.
	HiVal int
	// Base is the base space of an Indexed space.
	Base *ImageSpace
	// Object is the colour space object as the file wrote it (a name or an
	// array), for a caller that builds its own colour conversion.
	Object Object
}

ImageSpace describes the colour space of an image's samples: how many components a pixel has and what range they cover. Converting samples to a final colour (Indexed lookup, Separation and DeviceN tint transforms, ICC, Lab) is the caller's job; the space object is kept for that.

func DeviceImageSpace

func DeviceImageSpace(n int) (ImageSpace, bool)

DeviceImageSpace returns the DeviceGray, DeviceRGB or DeviceCMYK space with n = 1, 3 or 4 components, and false for any other n.

func JPXImageSpace

func JPXImageSpace(method int, enumCS uint32, profile []byte, components int) (sp ImageSpace, ok bool)

JPXImageSpace builds the ImageSpace for a JPEG 2000 colour specification box (ISO/IEC 15444-1 I.5.3.3), for a decoder to report in DecodedImage.Space. method is the METH field: 1 for an enumerated colour space, 2 for a restricted ICC profile. For method 1, enumCS is EnumCS: 16 (sRGB) gives DeviceRGB, 17 (greyscale) DeviceGray and 12 (CMYK) DeviceCMYK; other values, sYCC (18) included, give ok false, so a decoder converts sYCC to RGB itself and reports 16. For method 2, profile is the ICC profile and components its channel count (1, 3 or 4); a profile that does not fit components is refused. components is the number of colour channels the decoder returns. When ok is false the decoder leaves Space nil.

Example

A decoder reports the colour space its codestream declares, and is told the size the image will be drawn at.

sp, ok := onepdf.JPXImageSpace(1, 16, nil, 3) // enumerated colour space 16: sRGB
fmt.Println(sp.Family, ok)

set := onepdf.NewImageDecoders()
set.Register("JPXDecode", onepdf.ImageDecoderFunc(func(req *onepdf.ImageRequest) (*onepdf.DecodedImage, error) {
	fmt.Println("target", req.TargetWidth, req.TargetHeight)
	return &onepdf.DecodedImage{Width: 1, Height: 1, Components: 3, BitsPerComponent: 8,
		Samples: []byte{1, 2, 3}, Space: &sp}, nil
}))
doc, _ := onepdf.OpenBytes(examplePDF(), onepdf.WithImageDecoders(set), onepdf.WithEditing())
dict := onepdf.NewDict()
dict.Set("Width", onepdf.Int(64))
dict.Set("Height", onepdf.Int(64))
dict.Set("Filter", onepdf.Name("JPXDecode"))
// A stream added to the document is decoded with the document's decoders.
ref, _ := doc.AddObject(onepdf.NewStream(dict, []byte("jp2")))
obj, _ := doc.Object(ref.Number)
img, _ := obj.(*onepdf.Stream).DecodeImageContext(context.Background(),
	onepdf.ImageOptions{TargetWidth: 8, TargetHeight: 8})
fmt.Println(img.Space.Family, img.Width, img.Height)
Output:
DeviceRGB true
target 8 8
DeviceRGB 1 1

func ResolveImageSpace

func ResolveImageSpace(obj Object, resource func(Name) Object) (sp ImageSpace, ok bool)

ResolveImageSpace reads a /ColorSpace value (a name or an array, with abbreviations G, RGB, CMYK and I accepted as inline images write them). resource, when not nil, looks a name up in the page's ColorSpace resources; it is asked for any name that is not a device space. ok is false when the value does not describe a space an image can use (Pattern, an unknown name, a malformed array).

func (ImageSpace) Indexed

func (s ImageSpace) Indexed() bool

Indexed reports whether the samples are palette indices.

type ImportOption

type ImportOption interface {
	// contains filtered or unexported methods
}

ImportOption configures ImportPages and Merge.

func WithImportAt

func WithImportAt(index int) ImportOption

WithImportAt sets where the imported pages go: their index in the target afterwards. The default is the end. An index outside 0 to the page count is ErrArgument.

func WithImportFields

func WithImportFields(on bool) ImportOption

WithImportFields sets whether the form fields of the imported pages' widgets are merged into the target's form. The default is true. With false the widgets still come along as plain annotations that draw their stored appearance.

func WithImportOutlines

func WithImportOutlines(on bool) ImportOption

WithImportOutlines sets whether the source's outline items that lead to imported pages are appended to the target's outline. The default is true.

func WithImportStructure

func WithImportStructure(on bool) ImportOption

WithImportStructure sets whether the tagged-PDF structure of the imported pages is added to the target's structure tree. The default is true.

type Info

type Info struct {
	// contains filtered or unexported fields
}

Info is the document information dictionary (ISO 32000-2 14.3.3): the classic title, author and dates. Newer files keep the same facts in XMP (see Document.XMP); this reads only /Info.

Every method is safe on a nil *Info and then reports nothing, so doc.Info().Title() works for a file with no information dictionary.

func (*Info) Author

func (i *Info) Author() string

Author is /Author, or "" when absent.

func (*Info) CreationDate

func (i *Info) CreationDate() (t time.Time, ok bool)

CreationDate is /CreationDate as a UTC instant; ok is false when it is absent or not a date ParseDate accepts.

func (*Info) Creator

func (i *Info) Creator() string

Creator is /Creator, the program that made the original document, or "" when absent.

func (*Info) Dict

func (i *Info) Dict() *Dict

Dict returns the underlying dictionary, or nil.

func (*Info) Entries

func (i *Info) Entries() iter.Seq2[string, string]

Entries iterates over every entry whose value is a string, in file order, with the value read as a PDF text string.

func (*Info) Get

func (i *Info) Get(key string) (string, bool)

Get returns an entry as text, and whether it is present as a string or name. The empty string is a value: a title of "" is present.

func (*Info) Has

func (i *Info) Has(key string) bool

Has reports whether the dictionary has a string or name value under key.

func (*Info) Keywords

func (i *Info) Keywords() string

Keywords is /Keywords, or "" when absent.

func (*Info) ModDate

func (i *Info) ModDate() (t time.Time, ok bool)

ModDate is /ModDate as a UTC instant; ok is false when it is absent or not a date ParseDate accepts.

func (*Info) Producer

func (i *Info) Producer() string

Producer is /Producer, the program that made the PDF, or "" when absent.

func (*Info) Subject

func (i *Info) Subject() string

Subject is /Subject, or "" when absent.

func (*Info) Title

func (i *Info) Title() string

Title is /Title, or "" when absent.

func (*Info) Trapped

func (i *Info) Trapped() string

Trapped is /Trapped: "True", "False" or "Unknown", or "" when absent.

type Int

type Int int64

Int is a PDF integer. A number written with more digits than 64 bits can hold is clamped to the 64-bit range.

func (Int) String

func (n Int) String() string

String returns the decimal form, as the object is written.

type InterpretOption

type InterpretOption interface {
	// contains filtered or unexported methods
}

InterpretOption configures Interpret.

func WithAnnotations

func WithAnnotations(m AnnotationMode) InterpretOption

WithAnnotations chooses which annotation appearances are drawn after the page content (default AnnotationsView).

Example
package main

import (
	"bytes"
	"fmt"
	"strings"

	"recursiveai.org/go/onepdf"
)

// drawingPDF is one 100 x 100 page whose content is the given operators.
func drawingPDF(content, pageEntries string, extra ...string) []byte {
	var b bytes.Buffer
	b.WriteString("%PDF-1.7\n")
	offs := make([]int, 5+len(extra))
	obj := func(n int, body string) {
		offs[n] = b.Len()
		fmt.Fprintf(&b, "%d 0 obj\n%s\nendobj\n", n, body)
	}
	obj(1, "<</Type /Catalog/Pages 2 0 R>>")
	obj(2, "<</Type /Pages/Kids [3 0 R]/Count 1>>")
	obj(3, "<</Type /Page/Parent 2 0 R/MediaBox [0 0 100 100]/Contents 4 0 R"+pageEntries+">>")
	obj(4, fmt.Sprintf("<</Length %d>>\nstream\n%s\nendstream", len(content), content))
	for i, body := range extra {
		obj(5+i, body)
	}
	x := b.Len()
	fmt.Fprintf(&b, "xref\n0 %d\n0000000000 65535 f \n", len(offs))
	for _, o := range offs[1:] {
		fmt.Fprintf(&b, "%010d 00000 n \n", o)
	}
	fmt.Fprintf(&b, "trailer\n<</Size %d/Root 1 0 R>>\nstartxref\n%d\n%%%%EOF\n", len(offs), x)
	return b.Bytes()
}

func main() {
	annot := "<</Type /Annot/Subtype /Square/Rect [10 10 30 30]/C [1 0 0]/F 4>>"
	doc, err := onepdf.OpenBytes(drawingPDF("0 0 5 5 re f", "/Annots [5 0 R]", annot))
	if err != nil {
		fmt.Println(err)
		return
	}
	page, _ := doc.Page(0)
	for _, mode := range []onepdf.AnnotationMode{onepdf.AnnotationsView, onepdf.AnnotationsNone} {
		list, _ := page.InterpretToList(onepdf.WithAnnotations(mode))
		fmt.Println(mode, strings.Contains(list.Text(), "begin-annot"))
	}
}
Output:
view true
none false

func WithBox

func WithBox(b device.PageBox) InterpretOption

WithBox selects the page box that defines the output area: MediaBox, CropBox (the default), BleedBox, TrimBox or ArtBox. A box the page does not carry reads as its default (ISO 32000-2 14.11.2): the crop box for the three print boxes, the media box for the crop box.

Example
package main

import (
	"bytes"
	"fmt"

	"recursiveai.org/go/onepdf"
	"recursiveai.org/go/onepdf/device"
)

// drawingPDF is one 100 x 100 page whose content is the given operators.
func drawingPDF(content, pageEntries string, extra ...string) []byte {
	var b bytes.Buffer
	b.WriteString("%PDF-1.7\n")
	offs := make([]int, 5+len(extra))
	obj := func(n int, body string) {
		offs[n] = b.Len()
		fmt.Fprintf(&b, "%d 0 obj\n%s\nendobj\n", n, body)
	}
	obj(1, "<</Type /Catalog/Pages 2 0 R>>")
	obj(2, "<</Type /Pages/Kids [3 0 R]/Count 1>>")
	obj(3, "<</Type /Page/Parent 2 0 R/MediaBox [0 0 100 100]/Contents 4 0 R"+pageEntries+">>")
	obj(4, fmt.Sprintf("<</Length %d>>\nstream\n%s\nendstream", len(content), content))
	for i, body := range extra {
		obj(5+i, body)
	}
	x := b.Len()
	fmt.Fprintf(&b, "xref\n0 %d\n0000000000 65535 f \n", len(offs))
	for _, o := range offs[1:] {
		fmt.Fprintf(&b, "%010d 00000 n \n", o)
	}
	fmt.Fprintf(&b, "trailer\n<</Size %d/Root 1 0 R>>\nstartxref\n%d\n%%%%EOF\n", len(offs), x)
	return b.Bytes()
}

func main() {
	doc, err := onepdf.OpenBytes(drawingPDF("0 0 10 10 re f", "/CropBox [10 10 60 40]"))
	if err != nil {
		fmt.Println(err)
		return
	}
	page, _ := doc.Page(0)
	for _, box := range []device.PageBox{device.CropBox, device.MediaBox} {
		rec := &sizeDevice{}
		if err := page.Interpret(rec, onepdf.WithBox(box)); err != nil {
			fmt.Println(err)
		}
		fmt.Println(box, rec.w, rec.h)
	}
}

type sizeDevice struct {
	device.Base
	w, h float64
}

func (d *sizeDevice) BeginPage(p *device.Page) { d.w, d.h = p.Width, p.Height }
Output:
CropBox 50 30
MediaBox 100 100

func WithDPI

func WithDPI(dpi float64) InterpretOption

WithDPI sets the output resolution; a positive value replaces any scale with dpi/72.

func WithGeneratedAppearances

func WithGeneratedAppearances(on bool) InterpretOption

WithGeneratedAppearances sets whether an annotation with no stored normal appearance gets one generated from its dictionary (default true). Off, such an annotation draws nothing.

func WithGlyphOutlines

func WithGlyphOutlines(on bool) InterpretOption

WithGlyphOutlines sets whether glyph runs carry em-space outlines (default true).

func WithOptionalContent

func WithOptionalContent(fn func(group *Dict) (visible, decided bool)) InterpretOption

WithOptionalContent overrides the visibility of optional content groups. fn is called with an optional content group dictionary; when it returns decided true, visible replaces what the document's default configuration says for that group.

Example
package main

import (
	"bytes"
	"fmt"
	"strings"

	"recursiveai.org/go/onepdf"
)

// drawingPDF is one 100 x 100 page whose content is the given operators.
func drawingPDF(content, pageEntries string, extra ...string) []byte {
	var b bytes.Buffer
	b.WriteString("%PDF-1.7\n")
	offs := make([]int, 5+len(extra))
	obj := func(n int, body string) {
		offs[n] = b.Len()
		fmt.Fprintf(&b, "%d 0 obj\n%s\nendobj\n", n, body)
	}
	obj(1, "<</Type /Catalog/Pages 2 0 R>>")
	obj(2, "<</Type /Pages/Kids [3 0 R]/Count 1>>")
	obj(3, "<</Type /Page/Parent 2 0 R/MediaBox [0 0 100 100]/Contents 4 0 R"+pageEntries+">>")
	obj(4, fmt.Sprintf("<</Length %d>>\nstream\n%s\nendstream", len(content), content))
	for i, body := range extra {
		obj(5+i, body)
	}
	x := b.Len()
	fmt.Fprintf(&b, "xref\n0 %d\n0000000000 65535 f \n", len(offs))
	for _, o := range offs[1:] {
		fmt.Fprintf(&b, "%010d 00000 n \n", o)
	}
	fmt.Fprintf(&b, "trailer\n<</Size %d/Root 1 0 R>>\nstartxref\n%d\n%%%%EOF\n", len(offs), x)
	return b.Bytes()
}

func main() {
	content := "/OC /L BDC 1 0 0 rg 0 0 10 10 re f EMC"
	doc, err := onepdf.OpenBytes(drawingPDF(content, "/Resources<</Properties<</L<</Type/OCG/Name(Notes)>>>>>>"))
	if err != nil {
		fmt.Println(err)
		return
	}
	page, _ := doc.Page(0)
	hide := onepdf.WithOptionalContent(func(group *onepdf.Dict) (visible, decided bool) {
		name, _ := group.Text("Name")
		return false, string(name) == "Notes"
	})
	list, _ := page.InterpretToList(hide)
	fmt.Println(strings.Contains(list.Text(), "fill"))
	list, _ = page.InterpretToList()
	fmt.Println(strings.Contains(list.Text(), "fill"))
}
Output:
false
true

func WithRotation

func WithRotation(apply bool) InterpretOption

WithRotation sets whether the page's /Rotate is applied (default true).

func WithScale

func WithScale(s float64) InterpretOption

WithScale sets the scale from default user space units to output units (default 1). A value that is not positive and finite is ignored.

func WithUserUnit

func WithUserUnit(apply bool) InterpretOption

WithUserUnit sets whether the page's /UserUnit scales the output (default true).

type LabelRange

type LabelRange struct {
	FirstPage int
	Style     LabelStyle
	// Prefix is put before the number.
	Prefix string
	// Start is the number of the first page in the range, at least 1.
	Start int
}

LabelRange is one entry of the page-label tree: pages from FirstPage (zero-based) until the next range.

type LabelStyle

type LabelStyle byte

LabelStyle is the numbering style of a page-label range (ISO 32000-2 12.4.2, Table 159).

const (
	LabelNone       LabelStyle = 0
	LabelDecimal    LabelStyle = 'D'
	LabelUpperRoman LabelStyle = 'R'
	LabelLowerRoman LabelStyle = 'r'
	LabelUpperAlpha LabelStyle = 'A'
	LabelLowerAlpha LabelStyle = 'a'
)

Numbering styles. LabelNone numbers nothing: the label is the prefix alone.

type LimitError

type LimitError struct {
	// Limit is the name of the Limits field.
	Limit string
	// Max is the bound that was reached.
	Max int64
	// Object is the number of the object whose data hit the bound, or 0 when
	// the bound is not about one object.
	Object int
	// Offset is the byte offset in the source where that object's data
	// starts; it means something only when Object is not 0.
	Offset int64
}

LimitError names the bound that stopped a read. It matches ErrLimit.

func (*LimitError) Error

func (e *LimitError) Error() string

Error names the limit that was exceeded and where.

func (*LimitError) Is

func (e *LimitError) Is(target error) bool

Is reports a match with ErrLimit.

type Limits

type Limits struct {
	// MaxDecodedStream is the most bytes one stream may decode to. Default 256 MiB.
	MaxDecodedStream int64
	// MaxExpansionRatio is the largest decoded-to-stored size ratio allowed for
	// Flate and LZW once the output passes 16 MiB. Default 1100.
	MaxExpansionRatio int64
	// MaxNesting is the deepest nesting of arrays and dictionaries inside one object. Default 256.
	MaxNesting int
	// MaxRecursion is the deepest chain of form XObjects, patterns, Type 3
	// glyphs and annotations that one page may follow. Default 32.
	MaxRecursion int
	// MaxObjects is the most indirect objects a file may hold: the highest
	// object number plus one, and the number of cross-reference entries. Default 2^23.
	MaxObjects int
	// MaxFilterChain is the most filters one stream's /Filter array may list.
	// A longer chain fails with an error matching ErrLimit before any filter
	// runs. Real files use at most six. Default 32.
	MaxFilterChain int
	// MaxOperators is the most content-stream operators one page may run. Default 2^24.
	MaxOperators int
	// MaxDeviceCalls is the most calls one page may make to its device (paths,
	// clips, glyph runs, images, shadings and groups). Nested forms can draw one
	// shape a billion times inside the nesting bound, so the operator count
	// alone does not keep a recording device small. Past it the page stops with
	// an error matching ErrLimit after the device has received what came before.
	// Default 2^21.
	MaxDeviceCalls int
	// MaxGlyphs is the most glyphs one page may show, counted before each is
	// built so one string of millions of characters stops at the bound. Text
	// extraction applies it too. Default 2^19.
	MaxGlyphs int
	// MaxFunctionOps is the most operations one evaluation of a PostScript
	// calculator function may run. A calculator function has no loops, so its
	// longest path is known when it is read, and a function whose longest path
	// is past the bound is flagged. A shading that needs one is not delivered to
	// the device, and a soft-mask transfer function is ignored; a tint
	// transform is still used, because the paint it colours is real. Each
	// records a warning that its colours are not reliable, an error matching
	// ErrLimit in a strict document. Default 100,000.
	MaxFunctionOps int
	// MaxImagePixels is the most pixels one image may have. Default 2^28.
	MaxImagePixels int64
	// MaxMetadata is the most bytes of XMP metadata read. Default 64 MiB.
	MaxMetadata int64
	// ExpansionThreshold is the output size below which MaxExpansionRatio is not applied. Default 16 MiB.
	ExpansionThreshold int64
	// MaxAppearanceItems is the most items (such as quadrilaterals) one generated
	// annotation appearance may draw. Default 65,536.
	MaxAppearanceItems int
	// MaxAppearanceText is the most characters of text one generated annotation
	// appearance may show. Default 65,536.
	MaxAppearanceText int
}

Limits bound what a document may make the library do. They are checked before memory is allocated and apply to every document opened with them.

A zero field takes the default shown; a negative field removes that bound. Hostile input is the reason the defaults are on: raise them only for files you trust.

func DefaultLimits

func DefaultLimits() Limits

DefaultLimits returns the limits a document gets when none are given.

func UnboundedLimits

func UnboundedLimits() Limits

UnboundedLimits returns limits with every bound removed (every field negative). Use it only for files you trust: a hostile file can then make the library allocate without end.

type LineCap

type LineCap = device.LineCap

LineCap is the shape at the ends of open subpaths (ISO 32000-2 8.4.3.3). It is the device package's type; the constants keep the PDF's names.

type LineJoin

type LineJoin = device.LineJoin

LineJoin is the shape at the corners of a stroked path (ISO 32000-2 8.4.3.4). It is the device package's type; the constants keep the PDF's names.

type LostPage

type LostPage struct {
	// Index is the position the entry would have had if every entry were a
	// page. The pages after a lost entry are numbered without it.
	Index int
	// Reason says why the entry is lost.
	Reason LostPageReason
	// Object is the number of the object the entry points at, or 0 for a direct value.
	Object int
	// Parent is the number of the page-tree node that lists the entry, or 0 when that node is direct.
	Parent int
}

LostPage is a page-tree entry that did not lead to a page. A repaired file can declare pages it no longer holds; the tree still lists them.

type LostPageReason

type LostPageReason int

LostPageReason says why a page-tree entry did not lead to a page.

const (
	// LostNull is a direct null in /Kids.
	LostNull LostPageReason = iota
	// LostMissingObject is a reference to an object the file does not hold.
	LostMissingObject
	// LostNotADictionary is a number, name, array or other non-dictionary.
	LostNotADictionary
	// LostNotAPage is a dictionary that is neither a page nor a page-tree node.
	LostNotAPage
	// LostRepeated is a node already visited: a page listed twice, or a cycle.
	LostRepeated
	// LostTooDeep is a node nested deeper than Limits.MaxNesting.
	LostTooDeep
)

Reasons a page-tree entry is lost.

func (LostPageReason) String

func (r LostPageReason) String() string

String returns the reason as a lowercase hyphenated phrase, such as "missing-object".

type MarkupKind

type MarkupKind int

MarkupKind is the subtype of a text markup annotation that AddMarkup writes.

const (
	// MarkupHighlight is a Highlight annotation, drawn with the Multiply blend mode.
	MarkupHighlight MarkupKind = iota
	// MarkupStrikeOut is a StrikeOut annotation.
	MarkupStrikeOut
	// MarkupUnderline is an Underline annotation.
	MarkupUnderline
	// MarkupSquiggly is a Squiggly annotation.
	MarkupSquiggly
	// MarkupCaret is a Caret annotation. It has no quadrilaterals: MarkupRect says where it goes.
	MarkupCaret
)

The markup kinds (ISO 32000-2 12.5.6.10 and 12.5.6.11).

func (MarkupKind) String

func (k MarkupKind) String() string

String returns the annotation subtype: "Highlight", "StrikeOut", "Underline", "Squiggly" or "Caret".

type MarkupOption

type MarkupOption interface {
	// contains filtered or unexported methods
}

MarkupOption sets a property of the annotation AddMarkup writes.

func WithMarkupCaretParagraph

func WithMarkupCaretParagraph() MarkupOption

WithMarkupCaretParagraph sets a caret's /Sy to P (a new paragraph); the default is none. It has no effect on the other kinds.

func WithMarkupColor

func WithMarkupColor(c ...float64) MarkupOption

WithMarkupColor sets /C and the colour of the appearance: 1, 3 or 4 components in 0..1 (gray, RGB, CMYK). The default leaves /C out and the appearance draws yellow for a highlight and black for the others.

func WithMarkupContents

func WithMarkupContents(s string) MarkupOption

WithMarkupContents sets /Contents, the note shown with the annotation. The default leaves it out.

func WithMarkupFlags

func WithMarkupFlags(f int) MarkupOption

WithMarkupFlags sets /F from the Annot flag constants. The default is AnnotPrint.

func WithMarkupModified

func WithMarkupModified(t time.Time) MarkupOption

WithMarkupModified sets /M, written in UTC. The default leaves it out: nothing comes from the clock.

func WithMarkupName

func WithMarkupName(s string) MarkupOption

WithMarkupName sets /NM, the name that identifies the annotation on its page. The default leaves it out.

func WithMarkupOpacity

func WithMarkupOpacity(o float64) MarkupOption

WithMarkupOpacity sets /CA, in (0, 1]. The default leaves it out (opaque).

func WithMarkupPopup

func WithMarkupPopup(r Rect, open bool) MarkupOption

WithMarkupPopup adds a Popup annotation with the given rectangle, linked both ways to the markup and appended to the page after it (ISO 32000-2 12.5.6.14).

func WithMarkupRect

func WithMarkupRect(r Rect) MarkupOption

WithMarkupRect sets /Rect. For a caret it is required; for the other kinds the default is the bounds of the quadrilaterals. Either way the rectangle grows to hold what the appearance draws.

func WithMarkupRectDiff

func WithMarkupRectDiff(left, bottom, right, top float64) MarkupOption

WithMarkupRectDiff sets a caret's /RD, the distances between /Rect and the caret itself (left, bottom, right, top). It has no effect on the other kinds.

func WithMarkupTitle

func WithMarkupTitle(s string) MarkupOption

WithMarkupTitle sets /T, the author. The default leaves it out.

type MissingGlyphPolicy

type MissingGlyphPolicy int

MissingGlyphPolicy says what to do with a code the program has no glyph for.

const (
	// MissingUseNotdef draws .notdef for the code and lists it in the result.
	MissingUseNotdef MissingGlyphPolicy = iota
	// MissingRefuse refuses the program with [EmbedNoGlyphForCode].
	MissingRefuse
)

func (MissingGlyphPolicy) String

func (p MissingGlyphPolicy) String() string

String returns "UseNotdef" or "Refuse".

type Name

type Name string

Name is a PDF name without its leading slash, after "#xx" decoding. A name whose bytes are not valid UTF-8 is read as Latin-1 (the family rule for names), so a Name read from a file is always valid UTF-8.

type NotdefKeepReason

type NotdefKeepReason int

NotdefKeepReason says why a run was left alone.

const (
	// NotdefKeptVisible: the text is drawn and the scope is NotdefInvisible.
	NotdefKeptVisible NotdefKeepReason = iota
	// NotdefKeptExcluded: the include function said no.
	NotdefKeptExcluded
)

func (NotdefKeepReason) String

func (r NotdefKeepReason) String() string

String returns "Visible" or "ExcludedByCaller".

type NotdefKept

type NotdefKept struct {
	Reason NotdefKeepReason
	Run    NotdefRun
}

A NotdefKept is a run RemoveNotdefText left as it was.

type NotdefOption

type NotdefOption interface {
	// contains filtered or unexported methods
}

NotdefOption configures Document.RemoveNotdefText.

func WithNotdefDryRun

func WithNotdefDryRun() NotdefOption

WithNotdefDryRun reports what would be removed and changes nothing.

func WithNotdefInclude

func WithNotdefInclude(fn func(NotdefRun) bool) NotdefOption

WithNotdefInclude limits removal to the runs the function accepts; the others are kept with NotdefKeptExcluded. The function is called once per run, before the scope is applied.

func WithNotdefScope

func WithNotdefScope(s NotdefScope) NotdefOption

WithNotdefScope sets the scope; the default is NotdefInvisible.

type NotdefRemoval

type NotdefRemoval struct {
	// Removed lists the runs whose .notdef codes were taken out (or would be,
	// in a dry run); Kept the runs left alone.
	Removed []NotdefRun
	Kept    []NotdefKept
	// GlyphsRemoved counts the codes removed, OperatorsChanged the operators
	// rewritten and StreamsChanged the content streams that changed.
	GlyphsRemoved, OperatorsChanged, StreamsChanged int
}

NotdefRemoval says what Document.RemoveNotdefText did.

type NotdefRun

type NotdefRun struct {
	// Page is the zero-based index of the first page on which the operator was found.
	Page int
	// Font is the font dictionary; FontName its BaseFont without a subset tag
	// and FontResource the name the content selects it by.
	Font         *Dict
	FontName     string
	FontResource string
	Source       NotdefSource
	// Stream holds the operator, and Offset is where its first operand starts
	// in the decoded stream. For page content Stream is the one content
	// stream of the page that holds it.
	Stream *Stream
	Offset int
	// Operator is "Tj", "TJ", "'" or "\"".
	Operator string
	// Codes are the codes that draw .notdef, in order of appearance;
	// ShownCodes are all codes the operator shows.
	Codes, ShownCodes []int
	// Text is the text the shown codes extract as; NotdefText the part of it
	// that belongs to the .notdef codes.
	Text, NotdefText string
	RenderMode       device.RenderMode
	// Visible is false for text that is never seen: render mode 3 or hidden
	// optional content. Clipping modes count as drawn.
	Visible bool
	// OCVisible is false when optional content hides the operator.
	OCVisible bool
	// Groups names the optional content groups around the operator.
	Groups []string
}

A NotdefRun is one text-showing operator (Tj, TJ, ' or ") that shows at least one code the font draws as .notdef.

type NotdefScope

type NotdefScope int

NotdefScope chooses which .notdef text Document.RemoveNotdefText removes.

const (
	// NotdefInvisible removes only text that is never seen: render mode 3 or
	// hidden optional content. The picture does not change. This is the default.
	NotdefInvisible NotdefScope = iota
	// NotdefAll removes drawn text too, which changes what is visible.
	NotdefAll
)

func (NotdefScope) String

func (s NotdefScope) String() string

String returns "Invisible" or "All".

type NotdefSource

type NotdefSource int

NotdefSource says where a text operator was found.

const (
	// NotdefInPage is the page's own content.
	NotdefInPage NotdefSource = iota
	// NotdefInForm is a Form XObject the page or another form draws.
	NotdefInForm
	// NotdefInAppearance is an annotation's appearance stream.
	NotdefInAppearance
)

func (NotdefSource) String

func (s NotdefSource) String() string

String returns "PageContent", "Form" or "AnnotationAppearance".

type Object

type Object interface {
	// contains filtered or unexported methods
}

Object is a PDF object (ISO 32000-2 7.3): one of Bool, Int, Real, String, Name, Ref, *Array, *Dict or *Stream. The PDF null object is the Go value nil.

The set is closed: only this package defines Object types.

type Opt

type Opt[T any] struct {
	// Value is the value; meaningful only when Valid.
	Value T
	// Valid is false for a null or missing value.
	Valid bool
}

Opt is a value that may be absent: a destination's null parameters, a viewer preference the file does not set.

func (Opt[T]) Get

func (o Opt[T]) Get() (T, bool)

Get returns the value and whether it is present.

type Option

type Option interface {
	// contains filtered or unexported methods
}

Option configures Open and its variants. Options are values made by the With functions; the set is closed so that one option can serve every call that takes them.

func WithEditing

func WithEditing() Option

WithEditing opens the document so that it can be changed and saved: the mutators of objects and of the document work, and every object the document reads stays in memory so that a change cannot be lost. Without it every mutator returns ErrNotEditable and the document only reads (Save and SaveIncremental still work and write what was read).

func WithImageDecoders

func WithImageDecoders(set *ImageDecoders) Option

WithImageDecoders gives the document its own decoder set in place of DefaultImageDecoders(), so that a program's choice does not depend on what else registered globally. The set is used by reference: registering in it later affects the document.

func WithObjectCacheBytes

func WithObjectCacheBytes(n int64) Option

WithObjectCacheBytes sets the approximate number of bytes the document's cache may hold: parsed objects, decoded object streams and decoded stream data. When the cache is full the least recently used entries go first, and a value larger than a quarter of the budget is not kept (decoded stream data) or larger than the budget (anything else). Zero keeps the default, 128 MiB; a negative value removes the bound. The figure counts what the library can measure, not the Go heap's overhead. A document opened with WithEditing also keeps every object it has read, outside the cache.

Example
// Keep at most about 1 MiB of parsed objects and decoded streams; the least
// recently used go first. A negative value would remove the bound.
doc, err := onepdf.OpenBytes(examplePDF(), onepdf.WithObjectCacheBytes(1<<20))
if err != nil {
	fmt.Println(err)
	return
}
fmt.Println(doc.PageCount())
Output:
2

func WithPassword

func WithPassword(password string) Option

WithPassword gives the password to try for an encrypted document. It may be the user or the owner password; without it the empty user password is tried.

Example
data := encFile(&testing.T{}, encSpec{rev: 4, user: "reader", owner: "boss", encMeta: true, perms: -3904})

_, err := OpenBytes(data)
fmt.Println("no password:", errors.Is(err, ErrPassword))

doc, err := OpenBytes(data, WithPassword("reader"))
if err != nil {
	fmt.Println(err)
	return
}
info, _ := doc.Encryption()
fmt.Println("access:", doc.Access(), info.Cipher, info.KeyBits)
// Permissions are data; nothing here is enforced.
fmt.Println("may print:", doc.Permissions().Has(PermPrint))

doc, _ = OpenBytes(data, WithPassword("boss"))
fmt.Println("access:", doc.Access())
Output:
no password: true
access: user aes128 128
may print: false
access: owner

func WithStrict

func WithStrict() Option

WithStrict makes the document refuse damage instead of repairing it: every repair that would be a warning diagnostic is an error matching ErrFormat, from Open when the damage is in the structure, or from the read that meets it. Informational notes never fail. Limits are never repaired either way.

func WithSystemFonts

func WithSystemFonts() Option

WithSystemFonts lets the document use installed fonts for every font it draws or embeds a stand-in for. It is off by default: without it the output does not depend on the machine it was made on.

When on, the document asks installed fonts in three steps: a close match by name, then its own provider (Document.SetFontProvider) and the registered providers, then a generic installed family chosen by the descriptor flags (serif, fixed pitch, symbolic, CJK collection). The fonts are found in the platform's font directories and in those listed in the ONEPDF_FONT_DIRS environment variable (a path list); the library reads them and nothing else, never fetches, and lists them once per process. It affects Open and its variants; Save and NewDocumentWriter ignore it.

Example
plain, _ := onepdf.OpenBytes(examplePDF())
fmt.Println(plain.SystemFonts()) // off: output does not depend on the machine
withSystem, _ := onepdf.OpenBytes(examplePDF(), onepdf.WithSystemFonts())
fmt.Println(withSystem.SystemFonts())
Output:
false
true

type OptionalContentGroup

type OptionalContentGroup struct {
	// Dict is the group dictionary.
	Dict *Dict
	// Name is /Name as text.
	Name string
	// VisibleByDefault is the group's state in the default configuration
	// (/OCProperties /D): the /BaseState (ON when missing), then the /ON list
	// turns groups on and the /OFF list turns them off.
	VisibleByDefault bool
}

OptionalContentGroup is a layer (ISO 32000-2 8.11.2): content a viewer can show or hide.

type OutlineItem

type OutlineItem struct {
	// Title is the item's text; "" when it has none.
	Title string
	// Open reports that a viewer shows the item's children expanded. An item
	// with no children is never open.
	Open bool
	// Bold and Italic are the item's style flags.
	Bold, Italic bool
	// Color is the title colour as red, green and blue in 0..1; HasColor says whether the item sets one.
	Color    [3]float64
	HasColor bool
	// Destination is the item's /Dest, resolved; nil when the item has none.
	// An item led by an action keeps the action in Action instead.
	Destination *Destination
	// Action is the item's /A action; nil when it has none.
	Action *Action
	// Children are the item's sub-items in order.
	Children []*OutlineItem
	// Dict is the outline item dictionary.
	Dict *Dict
}

OutlineItem is one entry of the document outline, the bookmarks tree (ISO 32000-2 12.3.3).

type Page

type Page struct {
	// contains filtered or unexported fields
}

Page is one page of a document, read through the page tree with the inherited attributes (media box, crop box, rotation and resources) already applied (ISO 32000-2 7.7.3.4). Pages are cheap values owned by the Document: Document.Page returns the same *Page every time. A Page is safe for concurrent use.

The page's own dictionary is Dict. Further per-page data (annotations, content streams, resources) is read lazily from it. The interpreter adds its methods to this type.

func (*Page) AddMarkup

func (p *Page) AddMarkup(kind MarkupKind, quads []Quad, opts ...MarkupOption) (*Annotation, error)

AddMarkup writes a text markup annotation onto the page, with a generated normal appearance, and returns it. The document must have been opened with WithEditing. The annotation is appended to the page's /Annots (and so is its pop-up, when asked for), the new objects take the next free numbers in the order annotation, appearance, pop-up, and nothing comes from the clock or a random source, so the same calls give the same bytes.

quads are the marked areas; a highlight, strike-out, underline or squiggly needs at least one, a caret none (use WithMarkupRect). Invalid input is ErrArgument and nothing is added: no quadrilaterals, quadrilaterals on a caret, a caret without a rectangle, a coordinate that is not finite or beyond 10^7, a colour that is not 1, 3 or 4 components in 0..1, an opacity outside (0, 1], an empty pop-up rectangle. More quadrilaterals than Limits.MaxAppearanceItems is ErrLimit.

The written annotation's /Rect is grown to hold the appearance and the appearance's /BBox equals it. A full Save writes the file again; SaveIncremental appends an update and leaves earlier bytes, and so earlier signatures, in place.

Example

AddMarkup writes a highlight with its appearance. SaveIncremental appends the change and leaves the original bytes as they were.

package main

import (
	"bytes"
	"fmt"

	"recursiveai.org/go/onepdf"
)

// markupPDF is one page with two lines of Courier text.
func markupPDF() []byte {
	return drawingPDF(
		"BT /F1 10 Tf 10 80 Td (public line) Tj 0 -20 Td (account 1234) Tj ET",
		"/Resources <</Font <</F1 5 0 R>>>>",
		"<</Type /Font/Subtype /Type1/BaseFont /Courier>>")
}

// AddMarkup writes a highlight with its appearance. SaveIncremental appends
// the change and leaves the original bytes as they were.
func main() {
	original := markupPDF()
	doc, err := onepdf.OpenBytes(original, onepdf.WithEditing())
	if err != nil {
		fmt.Println(err)
		return
	}
	page, _ := doc.Page(0)
	quad := onepdf.QuadFromRect(onepdf.NewRect(10, 78, 70, 90))
	ann, err := page.AddMarkup(onepdf.MarkupHighlight, []onepdf.Quad{quad},
		onepdf.WithMarkupColor(1, 1, 0), onepdf.WithMarkupContents("check this"))
	if err != nil {
		fmt.Println(err)
		return
	}
	var out bytes.Buffer
	if err := doc.SaveIncremental(&out); err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(ann.Subtype, ann.Contents)
	fmt.Println(bytes.HasPrefix(out.Bytes(), original))
	reread, _ := onepdf.OpenBytes(out.Bytes())
	p, _ := reread.Page(0)
	for _, a := range p.Annotations() {
		fmt.Println(a.Subtype, a.HasAppearance())
	}
}
Output:
Highlight check this
true
Highlight true

func (*Page) Annotations

func (p *Page) Annotations() []*Annotation

Annotations returns the page's annotations in /Annots order. Entries that are not dictionaries are skipped. The slice is shared; do not modify it.

func (*Page) ArtBox

func (p *Page) ArtBox() Rect

ArtBox returns the art box, clipped to the media box; it defaults to the crop box.

func (*Page) BleedBox

func (p *Page) BleedBox() Rect

BleedBox returns the bleed box, clipped to the media box; it defaults to the crop box.

func (*Page) Box

func (p *Page) Box(b PageBox) Rect

Box returns the effective rectangle of the named box. An unknown box gives the crop box.

func (*Page) BoxColor

func (p *Page) BoxColor(b PageBox) (c BoxColor, ok bool)

BoxColor returns the page's /BoxColorInfo entry for the crop, bleed, trim or art box, with the defaults of Table 395 filled in. ok is false when the page has none (the media box never has one).

func (*Page) ClearBox

func (p *Page) ClearBox(b PageBox) error

ClearBox returns a box to its default: the crop box to the media box, the others to the crop box. A crop box the page inherits is overridden on the page with the media box. The media box has no default, so clearing it is ErrArgument.

func (*Page) ClearBoxColor

func (p *Page) ClearBoxColor(b PageBox) error

ClearBoxColor removes the page's colour information for a box.

func (*Page) ClearRotate

func (p *Page) ClearRotate() error

ClearRotate returns the page to no rotation: its own /Rotate is removed, and a rotation inherited from the page tree is overridden with 0.

func (*Page) ClearUserUnit

func (p *Page) ClearUserUnit() error

ClearUserUnit removes /UserUnit: a unit is 1/72 inch again.

func (*Page) Contents

func (p *Page) Contents() []*Stream

Contents returns the page's content streams in drawing order (ISO 32000-2 7.7.3.3). /Contents may be one stream or an array of them; entries that are not streams are skipped. A stream listed twice appears twice.

func (*Page) CropBox

func (p *Page) CropBox() Rect

CropBox returns the region a viewer shows: the crop box clipped to the media box, or the media box when the page has none (ISO 32000-2 7.7.3.3).

func (*Page) Dict

func (p *Page) Dict() *Dict

Dict returns the page's own dictionary (without inherited entries).

func (*Page) DisplaySize

func (p *Page) DisplaySize(b PageBox, applyRotate, applyUserUnit bool) PageSize

DisplaySize returns the size of the box as a viewer shows it. With applyRotate, width and height swap for a page rotated by 90 or 270. With applyUserUnit, both are multiplied by the page's UserUnit.

func (*Page) Document

func (p *Page) Document() *Document

Document returns the document the page belongs to.

func (*Page) HasBox

func (p *Page) HasBox(b PageBox) bool

HasBox reports whether the page stores a usable entry for the box, directly or through the page tree, as opposed to reading the default. The media box counts as stored when it is valid.

func (*Page) Index

func (p *Page) Index() int

Index returns the page's zero-based position in the document.

func (*Page) Interpret

func (p *Page) Interpret(dev device.Device, opts ...InterpretOption) error

Interpret runs the page's content stream and its annotation appearances against dev, in content order. Everything PDF-specific is resolved first: fonts, colour spaces, functions, shadings, patterns, images, optional content. See the device package for what dev receives.

Interpretation is lenient. A bad operator, a missing resource or a damaged stream is skipped and recorded in the document's Diagnostics; only a limit (Limits.MaxOperators) stops the page, with an error matching ErrLimit after dev has received what came before it, with every bracket closed. Nothing here runs document code.

Example
package main

import (
	"bytes"
	"fmt"

	"recursiveai.org/go/onepdf"
	"recursiveai.org/go/onepdf/device"
)

// drawingPDF is one 100 x 100 page whose content is the given operators.
func drawingPDF(content, pageEntries string, extra ...string) []byte {
	var b bytes.Buffer
	b.WriteString("%PDF-1.7\n")
	offs := make([]int, 5+len(extra))
	obj := func(n int, body string) {
		offs[n] = b.Len()
		fmt.Fprintf(&b, "%d 0 obj\n%s\nendobj\n", n, body)
	}
	obj(1, "<</Type /Catalog/Pages 2 0 R>>")
	obj(2, "<</Type /Pages/Kids [3 0 R]/Count 1>>")
	obj(3, "<</Type /Page/Parent 2 0 R/MediaBox [0 0 100 100]/Contents 4 0 R"+pageEntries+">>")
	obj(4, fmt.Sprintf("<</Length %d>>\nstream\n%s\nendstream", len(content), content))
	for i, body := range extra {
		obj(5+i, body)
	}
	x := b.Len()
	fmt.Fprintf(&b, "xref\n0 %d\n0000000000 65535 f \n", len(offs))
	for _, o := range offs[1:] {
		fmt.Fprintf(&b, "%010d 00000 n \n", o)
	}
	fmt.Fprintf(&b, "trailer\n<</Size %d/Root 1 0 R>>\nstartxref\n%d\n%%%%EOF\n", len(offs), x)
	return b.Bytes()
}

// boxDevice prints each filled path's colour and device-space bounds.
type boxDevice struct{ device.Base }

func (boxDevice) FillPath(p *device.Path, _ device.FillRule, st *device.State) {
	fmt.Printf("fill %v at %v\n", st.Fill.Comps[:3], p.Bounds().Transform(st.CTM))
}

func main() {
	doc, err := onepdf.OpenBytes(drawingPDF("1 0 0 rg 10 10 30 20 re f", ""))
	if err != nil {
		fmt.Println(err)
		return
	}
	page, err := doc.Page(0)
	if err != nil {
		fmt.Println(err)
		return
	}
	// The device sees paths in user space with the full matrix; the matrix
	// here flips y so that the origin is the top left of the page.
	if err := page.Interpret(boxDevice{}); err != nil {
		fmt.Println(err)
	}
}
Output:
fill [1 0 0] at {10 70 40 90}

func (*Page) InterpretContext

func (p *Page) InterpretContext(ctx context.Context, dev device.Device, opts ...InterpretOption) (err error)

InterpretContext is Interpret with cancellation: a context that is already done returns its error before anything is drawn, and one that ends during the page stops it within 1024 operators; ctx's error is returned and the device has received a balanced prefix.

func (*Page) InterpretToList

func (p *Page) InterpretToList(opts ...InterpretOption) (*displaylist.List, error)

InterpretToList interprets the page into a display list.

Example
package main

import (
	"bytes"
	"fmt"
	"strings"

	"recursiveai.org/go/onepdf"
)

// drawingPDF is one 100 x 100 page whose content is the given operators.
func drawingPDF(content, pageEntries string, extra ...string) []byte {
	var b bytes.Buffer
	b.WriteString("%PDF-1.7\n")
	offs := make([]int, 5+len(extra))
	obj := func(n int, body string) {
		offs[n] = b.Len()
		fmt.Fprintf(&b, "%d 0 obj\n%s\nendobj\n", n, body)
	}
	obj(1, "<</Type /Catalog/Pages 2 0 R>>")
	obj(2, "<</Type /Pages/Kids [3 0 R]/Count 1>>")
	obj(3, "<</Type /Page/Parent 2 0 R/MediaBox [0 0 100 100]/Contents 4 0 R"+pageEntries+">>")
	obj(4, fmt.Sprintf("<</Length %d>>\nstream\n%s\nendstream", len(content), content))
	for i, body := range extra {
		obj(5+i, body)
	}
	x := b.Len()
	fmt.Fprintf(&b, "xref\n0 %d\n0000000000 65535 f \n", len(offs))
	for _, o := range offs[1:] {
		fmt.Fprintf(&b, "%010d 00000 n \n", o)
	}
	fmt.Fprintf(&b, "trailer\n<</Size %d/Root 1 0 R>>\nstartxref\n%d\n%%%%EOF\n", len(offs), x)
	return b.Bytes()
}

func main() {
	doc, err := onepdf.OpenBytes(drawingPDF("0 0 1 rg 10 10 30 20 re f 0 g 5 w 0 0 m 100 100 l S", ""))
	if err != nil {
		fmt.Println(err)
		return
	}
	page, _ := doc.Page(0)
	list, err := page.InterpretToList(onepdf.WithScale(2))
	if err != nil {
		fmt.Println(err)
		return
	}
	for _, line := range strings.Split(list.Text(), "\n") {
		line = strings.TrimSpace(line)
		if strings.HasPrefix(line, "page ") || strings.HasPrefix(line, "fill ") || strings.HasPrefix(line, "stroke ") {
			fmt.Println(line)
		}
	}
}
Output:
page box=0 0 100 100 name=CropBox rotate=0 unit=1 scale=2 size=200 200 base=[2 0 0 -2 0 200]
fill nonzero M 10 10 L 40 10 L 40 30 L 10 30 Z
stroke M 0 0 L 100 100

func (*Page) Label

func (p *Page) Label() (string, bool)

Label returns the page's label, and false when the document has no page-label tree.

func (p *Page) Links() []*Annotation

Links returns the page's annotations whose subtype is Link.

func (*Page) MediaBox

func (p *Page) MediaBox() Rect

MediaBox returns the page's media box: the physical page size. It is inherited, normalised, and defaults to US Letter when missing or malformed.

func (*Page) Ref

func (p *Page) Ref() Ref

Ref returns the page dictionary's reference, or the zero Ref for a direct page.

func (*Page) Resources

func (p *Page) Resources() *Dict

Resources returns the page's resource dictionary, inherited from the page tree when the page has none of its own (ISO 32000-2 7.7.3.4). Resources of the page and its ancestors are not merged: the nearest one wins. It is nil when no level has a dictionary.

func (*Page) Rotate

func (p *Page) Rotate() int

Rotate returns the clockwise rotation viewers apply when showing the page: 0, 90, 180 or 270. It is inherited; any multiple of 90 is reduced, and a value that is not a multiple of 90 reads as 0.

func (*Page) SetBox

func (p *Page) SetBox(b PageBox, r Rect) error

SetBox sets one of the page's boxes. Any two opposite corners are accepted. A rectangle that is not finite or has no area is ErrArgument and nothing changes. Setting the media box also clips the page's own crop, bleed, trim and art boxes to it and removes one that no longer overlaps it, so what is stored matches what a reader reports.

Example
package main

import (
	"fmt"

	"recursiveai.org/go/onepdf"
)

// pagesOfWidths returns an editable document whose pages are as wide as the arguments say, which makes
// the page order visible.
func pagesOfWidths(widths ...float64) *onepdf.Document {
	doc, err := onepdf.New()
	if err != nil {
		panic(err)
	}
	for i, w := range widths {
		if err := doc.InsertBlankPage(i, w, 100); err != nil {
			panic(err)
		}
	}
	return doc
}

func main() {
	doc := pagesOfWidths(200)
	p, _ := doc.Page(0)
	// Any two opposite corners do; an empty rectangle is refused.
	p.SetBox(onepdf.TrimBox, onepdf.Rect{X0: 170, Y0: 90, X1: 30, Y1: 30})
	fmt.Println(p.TrimBox())
	fmt.Println(p.SetBox(onepdf.ArtBox, onepdf.Rect{X0: 5, Y0: 5, X1: 5, Y1: 50}) != nil)
}
Output:
{30 30 170 90}
true

func (*Page) SetBoxColor

func (p *Page) SetBoxColor(b PageBox, c BoxColor) error

SetBoxColor sets how a viewer outlines the crop, bleed, trim or art box (ISO 32000-2 14.11.2.2). The media box has none, and colours outside 0 to 1 or a negative or non-finite line width are ErrArgument.

func (*Page) SetPrintGeometry

func (p *Page) SetPrintGeometry(trim Rect, bleed, slug PrintMargins, marks *PrinterMarks) error

SetPrintGeometry sets up a page for printing: the trim box is trim, the bleed box is the trim box grown by bleed, and the media box is the bleed box grown by slug, the room outside the bleed for marks and job information. The crop box is cleared, not set to the bleed box: the crop box is what a viewer displays and prints (14.11.2.2), and it would hide the slug. Content keeps its coordinates. With marks, they are added over the page's content as separate streams.

trim must be finite with an area, bleed and slug finite and not negative, and a slug must be at least marks.MinimumSlug() on every side when marks are asked for; else ErrArgument and nothing changes.

Example
package main

import (
	"fmt"

	"recursiveai.org/go/onepdf"
)

// pagesOfWidths returns an editable document whose pages are as wide as the arguments say, which makes
// the page order visible.
func pagesOfWidths(widths ...float64) *onepdf.Document {
	doc, err := onepdf.New()
	if err != nil {
		panic(err)
	}
	for i, w := range widths {
		if err := doc.InsertBlankPage(i, w, 100); err != nil {
			panic(err)
		}
	}
	return doc
}

func main() {
	doc := pagesOfWidths(200)
	p, _ := doc.Page(0)
	trim := onepdf.Rect{X0: 36, Y0: 36, X1: 164, Y1: 164}
	// 9 pt of bleed and 20 pt of slug around the trim box, with crop marks in the slug.
	err := p.SetPrintGeometry(trim, onepdf.UniformMargins(9), onepdf.UniformMargins(20), &onepdf.PrinterMarks{Crop: true})
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println("media", p.MediaBox(), "bleed", p.BleedBox(), "trim", p.TrimBox())
}
Output:
media {7 7 193 193} bleed {27 27 173 173} trim {36 36 164 164}

func (*Page) SetRotate

func (p *Page) SetRotate(degrees int) error

SetRotate sets the page's clockwise rotation in degrees. It must be a multiple of 90; negative values and values over 360 are normalised to 0, 90, 180 or 270. Anything else is ErrArgument.

func (*Page) SetUserUnit

func (p *Page) SetUserUnit(u float64) error

SetUserUnit sets /UserUnit, the size of a default user space unit in 1/72 inch (ISO 32000-2 Table 31). It must be finite and positive, else ErrArgument. The document's version is raised to 1.6.

func (*Page) TrimBox

func (p *Page) TrimBox() Rect

TrimBox returns the trim box, clipped to the media box; it defaults to the crop box.

func (*Page) UserUnit

func (p *Page) UserUnit() float64

UserUnit returns the size of a default user space unit in 1/72 inch (ISO 32000-2 Table 31). It is 1 when missing, zero, negative or not finite.

type PageBox

type PageBox = device.PageBox

PageBox names one of a page's five boxes (ISO 32000-2 14.11.2). It is the device package's type, so the same value selects a box for Page.Box and for the WithBox interpreter option. Its value is the box's key in the page dictionary, such as "CropBox". The zero value, and any unknown name, reads as the crop box, the one viewers show.

type PageContent

type PageContent struct {
	*ContentBuilder
	// contains filtered or unexported fields
}

PageContent is a ContentBuilder that writes onto an existing page. Nothing reaches the page before Commit; Close discards what was drawn.

func (*PageContent) Commit

func (c *PageContent) Commit() error

Commit writes the drawn content onto the page and closes the builder. Open Save levels and marked-content sequences are closed first. It returns the first error a call recorded, in which case nothing is written; a second Commit is ErrNotEditable.

type PageLabels

type PageLabels struct {
	// contains filtered or unexported fields
}

PageLabels is the document's page-label tree (ISO 32000-2 12.4.2).

func (*PageLabels) Label

func (l *PageLabels) Label(i int) string

Label returns the label of page i (zero-based). A page before the first range, or any page of a document with no ranges, is labelled with its decimal number, i+1.

func (*PageLabels) Ranges

func (l *PageLabels) Ranges() []LabelRange

Ranges returns the label ranges in page order. The slice must not be modified.

type PageRange

type PageRange struct {
	Start, Count int
}

PageRange is a run of pages: Count pages from the zero-based index Start.

type PageSize

type PageSize struct{ Width, Height float64 }

PageSize is a size in points (1/72 inch).

func (PageSize) HeightInches

func (s PageSize) HeightInches() float64

HeightInches is the height in inches.

func (PageSize) HeightMillimeters

func (s PageSize) HeightMillimeters() float64

HeightMillimeters is the height in millimetres.

func (PageSize) WidthInches

func (s PageSize) WidthInches() float64

WidthInches is the width in inches.

func (PageSize) WidthMillimeters

func (s PageSize) WidthMillimeters() float64

WidthMillimeters is the width in millimetres.

type PasswordError

type PasswordError struct {
	// Required is true when the document was opened without a password and needs one; false when a
	// password was given and does not open it.
	Required bool
}

PasswordError is returned by Open when no password opens the document. It matches ErrPassword. A program that prompts for a password tells the two cases apart with errors.As: ask when Required is true, and say the password was wrong when it is false.

func (*PasswordError) Error

func (e *PasswordError) Error() string

Error says whether a password was needed or the one given was wrong.

func (*PasswordError) Is

func (e *PasswordError) Is(target error) bool

Is reports a match with ErrPassword.

type Permissions

type Permissions uint32

Permissions are the usage flags of the standard security handler (ISO 32000-2 Table 22). They are data: this library never enforces them, and an application that wants to honour them decides for itself. The owner password lifts every restriction, so check Document.Access as well.

const (
	PermPrint            Permissions = 1 << 2  // print (bit 3)
	PermModify           Permissions = 1 << 3  // modify the contents (bit 4)
	PermCopy             Permissions = 1 << 4  // copy or extract text and graphics (bit 5)
	PermAnnotate         Permissions = 1 << 5  // add or change annotations (bit 6)
	PermFillForms        Permissions = 1 << 8  // fill in form fields (bit 9)
	PermAccessibility    Permissions = 1 << 9  // extract for accessibility (bit 10)
	PermAssemble         Permissions = 1 << 10 // insert, rotate or delete pages (bit 11)
	PermPrintHighQuality Permissions = 1 << 11 // print at full quality (bit 12)

)

Permission flags, with the bit values the file stores in /P.

func (Permissions) Has

func (p Permissions) Has(f Permissions) bool

Has reports whether every flag in f is set.

func (Permissions) String

func (p Permissions) String() string

String lists the permissions set, joined with "|", such as "Print|Copy"; "none" when no named bit is set.

type PrintMargins

type PrintMargins struct{ Left, Bottom, Right, Top float64 }

PrintMargins are widths on the four sides of a page, in points.

func UniformMargins

func UniformMargins(v float64) PrintMargins

Uniform returns margins of the same width on every side.

type PrintScaling

type PrintScaling uint8

PrintScaling is the print dialog's page scaling preference (ISO 32000-2 Table 147, /PrintScaling). The zero value means "not set".

const (
	// PrintScalingAppDefault is /AppDefault: the viewer's own scaling.
	PrintScalingAppDefault PrintScaling = iota + 1
	// PrintScalingNone is /None: print at the page's size.
	PrintScalingNone
)

The print scaling values.

func ParsePrintScaling

func ParsePrintScaling(name string) (PrintScaling, error)

ParsePrintScaling reads "AppDefault" or "None"; anything else is ErrArgument.

func (PrintScaling) String

func (s PrintScaling) String() string

String returns the value's PDF name without the slash ("AppDefault" or "None"), or "" for the zero value.

type PrintSetup

type PrintSetup struct {
	Bleed, Slug PrintMargins
	Rotate      int
	Marks       *PrinterMarks
}

PrintSetup describes the geometry of a print page: bleed and slug on each side, the rotation, and optional printer's marks.

type PrinterMarks

type PrinterMarks struct {
	Crop, Registration bool
	// Offset is the gap between the bleed box and a mark; 3 when zero.
	Offset float64
	// Length of a crop mark; 14 when zero.
	Length float64
	// Circle is the diameter of a registration mark's circle; 10 when zero.
	Circle float64
	// LineWidth of the marks; 0.25 when zero.
	LineWidth float64
}

PrinterMarks says which printer's marks are drawn in the slug. Crop marks are a horizontal and a vertical line at each trim corner reaching away from the page; registration marks are a circle with a cross hair centred on each side's trim edge. All of it is stroked in the registration colour as an artifact of type Page (ISO 32000-2 14.8.2.2), so tagged output ignores it.

func (PrinterMarks) MinimumSlug

func (m PrinterMarks) MinimumSlug() float64

MinimumSlug is the room the marks need on every side: the gap, the longest mark (a cross hair is 1.5 times its circle) and half the line width.

type Quad

type Quad [4]device.Point

Quad is one quadrilateral of /QuadPoints: four points, the corners in the order viewers write them, upper left, upper right, lower left and lower right (ISO 32000-2 Table 181 describes a counterclockwise order, but files do not follow it).

func QuadFromRect

func QuadFromRect(r Rect) Quad

QuadFromRect returns the quadrilateral of r in the order viewers write.

type Real

type Real float64

Real is a PDF real number.

type Rect

type Rect = device.Rect

Rect is a rectangle in default user space units (ISO 32000-2 7.9.5), the device package's type: X0, Y0 is the lower left corner and X1, Y1 the upper right, in the order of the PDF rectangle array [llx lly urx ury]. Page boxes, annotation rectangles and every other rectangle of the API use it. Build a normalised one with NewRect.

func NewRect

func NewRect(x0, y0, x1, y1 float64) Rect

NewRect builds the rectangle with the two given diagonally opposite corners, in any of the four orders PDF allows (ISO 32000-2 7.9.5).

type Ref

type Ref struct {
	Number     int
	Generation int
}

Ref is an indirect reference (7.3.10): object number and generation. Object numbers start at 1; the zero Ref refers to no object.

func (Ref) IsZero

func (r Ref) IsZero() bool

IsZero reports whether r is the zero Ref, which names no object.

type Revision

type Revision struct {
	// contains filtered or unexported fields
}

Revision is the file as it stood at the end of one cross-reference section (ISO 32000-2 7.5.6): the original write or one incremental update. The objects, trailer and catalog it returns are those of that revision, whatever later updates replaced or deleted.

func (Revision) Catalog

func (r Revision) Catalog() *Dict

Catalog returns the catalog this revision's trailer names, or nil.

func (Revision) EndOffset

func (r Revision) EndOffset() int64

EndOffset returns the offset just past the %%EOF that ends the revision.

func (Revision) Index

func (r Revision) Index() int

Index returns the revision's position, 0 being the oldest.

func (Revision) IsXRefStream

func (r Revision) IsXRefStream() bool

IsXRefStream reports whether the revision's cross-reference data is a stream rather than a table.

func (Revision) Lookup

func (r Revision) Lookup(num int) (XRefEntry, bool)

Lookup returns the cross-reference entry for num as this revision has it.

func (Revision) Object

func (r Revision) Object(num int) (Object, error)

Object returns object number num as this revision has it; see Document.Object.

func (Revision) Objects

func (r Revision) Objects() iter.Seq[int]

Objects yields the number of every object the revision holds that is not free, in increasing order.

func (Revision) PageCount

func (r Revision) PageCount() int

PageCount returns the number of pages in the revision's page tree. It counts leaves, not the /Count entries, which files often get wrong, and never follows a cycle.

func (Revision) Resolve

func (r Revision) Resolve(o Object) Object

Resolve follows references as this revision has them.

func (Revision) Trailer

func (r Revision) Trailer() *Dict

Trailer returns the trailer dictionary of the revision.

func (Revision) XRefOffset

func (r Revision) XRefOffset() int64

XRefOffset returns the offset the revision's cross-reference section is stated at (the startxref or /Prev value).

type SaveOption

type SaveOption interface {
	// contains filtered or unexported methods
}

SaveOption configures Save and SaveIncremental.

func WithCompressedStreams

func WithCompressedStreams(on bool) SaveOption

WithCompressedStreams makes the save Flate-compress every stream written that has no filter, except metadata and when compression would not make it smaller. The default is false: streams are written as they are stored.

func WithEncryption

func WithEncryption(c Cipher, userPassword, ownerPassword string, opts ...EncryptOption) SaveOption

WithEncryption makes a full save encrypt the file with the standard security handler under new passwords, whatever the document had. cipher is CipherAES128 (revision 4, PDF 1.6) or CipherAES256 (revision 6, PDF 2.0); any other cipher is refused with ErrArgument at save, because RC4 is only ever written by keeping an RC4 file's own encryption. An empty owner password means the user password; an empty user password lets anyone open the file. The file key, salts and initialisation vectors are random, so encrypted output differs from run to run.

The default of a save is to keep the document's encryption (a plain document stays plain). An incremental save refuses WithEncryption and WithoutEncryption with ErrArgument.

Example
doc, _ := onepdf.OpenBytes(examplePDF(), onepdf.WithEditing())
var out bytes.Buffer
err := doc.Save(&out, onepdf.WithEncryption(onepdf.CipherAES256, "open sesame", "", onepdf.WithPermissions(onepdf.PermPrint)))
if err != nil {
	fmt.Println(err)
	return
}
_, err = onepdf.OpenBytes(out.Bytes())
fmt.Println("without the password:", err)
enc, _ := onepdf.OpenBytes(out.Bytes(), onepdf.WithPassword("open sesame"))
info, _ := enc.Encryption()
fmt.Println("revision:", info.Revision, "cipher:", info.Cipher, "may copy:", enc.Permissions().Has(onepdf.PermCopy))
Output:
without the password: onepdf: the document needs a password
revision: 6 cipher: aes256 may copy: false

func WithObjectStreams

func WithObjectStreams(on bool) SaveOption

WithObjectStreams says whether a full save with a cross-reference stream packs small objects into object streams of up to 100 objects or 1 MiB. The default is true. It has no effect with a classic table. The catalog, streams and the encryption dictionary are never packed (7.5.7).

func WithXRefFormat

func WithXRefFormat(f XRefFormat) SaveOption

WithXRefFormat sets the cross-reference format. The default is XRefAuto. An incremental save continues the newest revision's form unless a format is given.

func WithoutEncryption

func WithoutEncryption() SaveOption

WithoutEncryption makes a full save write an unencrypted file. The document is already open, so access has been granted; the passwords are not needed.

type Script

type Script struct {
	// Name is the key in the /Names /JavaScript name tree; "" for the script of an open action.
	Name string
	// Script is the source text.
	Script string
}

Script is a document-level JavaScript script (ISO 32000-2 12.6.4.17), data only: this library never runs it.

type ShapedGlyph

type ShapedGlyph struct {
	// GID is the glyph index in the font.
	GID int
	// Cluster is the UTF-16 index in the run's text of the first character the
	// glyph stands for. A cluster's text runs to the next larger cluster index
	// present in the run, or to the end of the text.
	Cluster int
	// Advance is how far the pen moves after the glyph.
	Advance float64
	// DX and DY offset the glyph from the pen without moving it.
	DX, DY float64
}

ShapedGlyph is one glyph a shaping engine has chosen and placed, for DrawGlyphRun. Advance, DX and DY are in thousandths of the font size.

type SharedOption

type SharedOption interface {
	Option
	SaveOption
	WriterOption
}

SharedOption is an option that more than one call understands: the constructors that return it (WithLimits, WithDocumentID and WithMinimumVersion) can be passed to Open and its variants, to Save, or to NewDocumentWriter, wherever the option means something. Where one does not apply to the call it is given to, it is ignored, and its documentation says which calls it affects.

func WithDocumentID

func WithDocumentID(id []byte) SharedOption

WithDocumentID sets the file identifier (14.4): a full save writes it as both strings of /ID; an incremental save keeps the first string and writes it as the second. Without it a document that has an /ID keeps it, and a new one is derived from a SHA-256 hash of the bytes written, so that saving the same document twice gives the same file. NewDocumentWriter takes it too and writes it as both strings of /ID (ISO 32000-2 14.4); without it the writer derives one from a SHA-256 hash of the bytes written, so the same calls give the same file. Open ignores it.

func WithLimits

func WithLimits(l Limits) SharedOption

WithLimits sets the limits for the document (see Limits for how zero and negative fields read). Without it DefaultLimits apply. It affects Open and its variants, and NewDocumentWriter, where it bounds the objects the writer keeps; Save ignores it. UnboundedLimits removes every bound.

Example
package main

import (
	"bytes"
	"errors"
	"fmt"

	"recursiveai.org/go/onepdf"
)

// examplePDF writes a two-page file with an incremental update that adds the second page.
func examplePDF() []byte {
	var b bytes.Buffer
	b.WriteString("%PDF-1.7\n")
	offs := map[int]int{}
	obj := func(n int, body string) {
		offs[n] = b.Len()
		fmt.Fprintf(&b, "%d 0 obj\n%s\nendobj\n", n, body)
	}
	obj(1, "<</Type /Catalog/Pages 2 0 R/Lang (en)>>")
	obj(2, "<</Type /Pages/Kids [3 0 R]/Count 1>>")
	obj(3, "<</Type /Page/Parent 2 0 R/MediaBox [0 0 612 792.5]>>")
	first := b.Len()
	fmt.Fprintf(&b, "xref\n0 4\n0000000000 65535 f \n%010d 00000 n \n%010d 00000 n \n%010d 00000 n \ntrailer\n<</Size 4/Root 1 0 R>>\nstartxref\n%d\n%%%%EOF\n", offs[1], offs[2], offs[3], first)
	obj(2, "<</Type /Pages/Kids [3 0 R 4 0 R]/Count 2>>")
	obj(4, "<</Type /Page/Parent 2 0 R/MediaBox [0 0 100 100]>>")
	second := b.Len()
	fmt.Fprintf(&b, "xref\n2 1\n%010d 00000 n \n4 1\n%010d 00000 n \ntrailer\n<</Size 5/Root 1 0 R/Prev %d>>\nstartxref\n%d\n%%%%EOF\n", offs[2], offs[4], first, second)
	return b.Bytes()
}

func main() {
	_, err := onepdf.OpenBytes(examplePDF(), onepdf.WithLimits(onepdf.Limits{MaxObjects: 3}))
	var le *onepdf.LimitError
	fmt.Println(errors.As(err, &le), le.Limit)
}
Output:
true MaxObjects

func WithMinimumVersion

func WithMinimumVersion(v Version) SharedOption

WithMinimumVersion raises the version of a full save to at least v, such as PDF17. It never lowers it: the save writes the highest of the document's version, v and what the chosen features need (1.5 for a cross-reference stream). An incremental save keeps the header it copies. For NewDocumentWriter it sets the header's version (default 1.7, range 1.0 to 2.0); a cross-reference stream raises it to 1.5. Open ignores it. A version that is not 0.0 to 9.9 is ignored.

type SoftMaskKind

type SoftMaskKind int

SoftMaskKind says what a soft mask takes from its form (ISO 32000-2 11.5.2).

const (
	// MaskAlpha uses the form's alpha.
	MaskAlpha SoftMaskKind = iota
	// MaskLuminosity uses the form's luminosity.
	MaskLuminosity
)

The soft mask kinds.

func (SoftMaskKind) String

func (k SoftMaskKind) String() string

String returns "Alpha" or "Luminosity".

type SpanOptions

type SpanOptions struct {
	// ActualText is the text the span stands for (ISO 32000-2 14.9.4).
	ActualText string
	// NoText writes an empty /ActualText: the span stands for no text, as a
	// further colour layer of a glyph already shown does. It is ignored when
	// ActualText is set.
	NoText bool
	// Alt is alternate text.
	Alt string
	// Lang is a language tag such as "en-US".
	Lang string
	// Expansion expands an abbreviation.
	Expansion string
}

SpanOptions are the properties of a Span sequence. Empty fields are left out, so the zero value is a span with no properties.

type StampOption

type StampOption interface {
	// contains filtered or unexported methods
}

StampOption places and paints a stamp. Without options a stamp is opaque black, upright, centred on the page's crop box, over the page's content, on every page.

func WithStampBlend

func WithStampBlend(m BlendMode) StampOption

WithStampBlend sets the blend mode; the default is BlendNormal.

func WithStampCenter

func WithStampCenter(x, y float64) StampOption

WithStampCenter places the stamp's centre at x, y in the page's default user space instead of at the centre of the crop box.

func WithStampCenterX

func WithStampCenterX(x float64) StampOption

WithStampCenterX places the stamp's centre at x in the page's default user space; the vertical centre stays that of the crop box unless WithStampCenterY or WithStampCenter says otherwise.

func WithStampCenterY

func WithStampCenterY(y float64) StampOption

WithStampCenterY places the stamp's centre at y; see WithStampCenterX.

func WithStampColor

func WithStampColor(r, g, b float64) StampOption

WithStampColor sets the fill colour of a text stamp, as red, green and blue from 0 to 1. The default is black.

func WithStampOpacity

func WithStampOpacity(a float64) StampOption

WithStampOpacity sets the opacity, 0 to 1. The default is 1; 0 also means 1.

func WithStampPages

func WithStampPages(pages ...int) StampOption

WithStampPages limits the stamp to the pages with these zero-based indexes, in the order given. Without it every page is stamped. An index out of range is ErrArgument.

func WithStampPlacement

func WithStampPlacement(p ContentPlacement) StampOption

WithStampPlacement puts the stamp over (the default) or under the page's content.

func WithStampRotation

func WithStampRotation(degrees float64) StampOption

WithStampRotation turns the stamp counter-clockwise, in degrees, as it reads on the displayed page: the page's /Rotate is compensated.

type StandardFont

type StandardFont uint8

StandardFont is one of the 14 standard fonts of PDF (ISO 32000-2 9.6.2.2), which a viewer supplies and a file need not embed. The zero value is not a font.

const (
	FontCourier StandardFont = iota + 1
	FontCourierBold
	FontCourierOblique
	FontCourierBoldOblique
	FontHelvetica
	FontHelveticaBold
	FontHelveticaOblique
	FontHelveticaBoldOblique
	FontTimesRoman
	FontTimesBold
	FontTimesItalic
	FontTimesBoldItalic
	FontSymbol
	FontZapfDingbats
)

The 14 standard fonts.

func ParseStandardFont

func ParseStandardFont(name string) (StandardFont, error)

ParseStandardFont finds the standard font that name stands for: the 14 PostScript names and the usual aliases (Arial, ArialMT, "Arial,Bold", TimesNewRoman, CourierNew, ...). Any other name is ErrArgument.

func (StandardFont) String

func (f StandardFont) String() string

String returns the font's PostScript name, such as "Helvetica-Bold", or "" for a value that is not one of the 14.

type Stream

type Stream struct {
	// contains filtered or unexported fields
}

Stream is a PDF stream (7.3.8): a dictionary and a run of bytes.

Raw gives the bytes as stored (after decryption); Decode runs the stream's filters. Neither is read from the file until it is called.

func NewInlineImage

func NewInlineImage(dict *Dict, data []byte) *Stream

NewInlineImage makes a stream of the kind DecodeImage reads from the dictionary and data of an inline image (the BI ... ID ... EI of a content stream). dict may use the abbreviated keys (W, H, BPC, CS, F, DP, D, IM, I) and abbreviated colour space names (G, RGB, CMYK, I); the returned stream has the full names throughout. Filter abbreviations are expanded when the filters are read, in a /Filter written either way. When both /DP and /DecodeParms are present, /DecodeParms wins. data is the bytes between ID and EI, still filtered; finding where EI is belongs to the content-stream reader.

The result belongs to no document, so its images are decoded with DefaultImageDecoders() and a diagnostic has nowhere to go.

func NewStream

func NewStream(dict *Dict, data []byte) *Stream

NewStream returns a stream with the given dictionary and stored bytes. It belongs to no document. The caller must keep dict's /Length in step, or leave it out.

func (*Stream) DataOffset

func (s *Stream) DataOffset() (offset int64, ok bool)

DataOffset returns the byte offset in the document's source where the stream's stored bytes start. ok is false for a stream that was not read from a document, whose data was replaced, or whose data is external.

func (*Stream) Decode

func (s *Stream) Decode() ([]byte, error)

Decode returns the stream's data with every filter undone. An image codec (DCTDecode, JPXDecode, JBIG2Decode) is not decoded here: Decode then returns the bytes as they stand before it together with ErrUnsupported; see DecodePartial. The result may alias the stored bytes when there are no filters, and must not be modified.

When the data is damaged, Decode returns the bytes it could decode with an error matching ErrFormat; a limit gives ErrLimit.

func (*Stream) DecodeContext

func (s *Stream) DecodeContext(ctx context.Context) ([]byte, error)

DecodeContext is Decode that stops when ctx is done. The context is checked before each filter of the chain, so a long chain (or a caller that gives up on a page) returns promptly with ctx.Err(); a single filter that has started runs to its end, bounded by the document's limits. Data decoded so far is not returned on cancellation.

func (*Stream) DecodeImage

func (s *Stream) DecodeImage(opt ImageOptions) (*Image, error)

DecodeImage turns an image XObject, or an inline image made by NewInlineImage, into finished samples and an opacity plane: bit depths 1, 2, 4, 8 and 16, /Decode, /ImageMask, colour-key masks, /Mask streams, /SMask with /Matte, and /SMaskInData. DCT, JPX and JBIG2 data goes through the document's decoders (see WithImageDecoders); without one the result is ImageEncoded and the document gets a diagnostic.

A damaged or short stream gives an image padded with zero samples (white for CCITT data) and a diagnostic, not an error. A dictionary that cannot describe an image gives Kind ImageNone. The error is non-nil only for problems in reading the stream itself (a limit, unreadable bytes).

func (*Stream) DecodeImageContext

func (s *Stream) DecodeImageContext(ctx context.Context, opt ImageOptions) (*Image, error)

DecodeImageContext is DecodeImage that stops when ctx is done: the filters before the codec are checked as in DecodeContext, the codec's decoder gets ctx when it implements ContextImageDecoder, and soft and explicit masks are decoded under the same context. A cancelled decode returns ctx.Err() and no image; it is not recorded as a damaged image.

func (*Stream) DecodePartial

func (s *Stream) DecodePartial() (data []byte, rest []Filter, err error)

DecodePartial undoes filters up to the first image codec and returns the data so far with the filters left to apply (empty when all were undone).

func (*Stream) DecodePartialContext

func (s *Stream) DecodePartialContext(ctx context.Context) (data []byte, rest []Filter, err error)

DecodePartialContext is DecodePartial that stops when ctx is done, with the same checking as DecodeContext.

func (*Stream) Dict

func (s *Stream) Dict() *Dict

Dict returns the stream's dictionary.

func (*Stream) Filters

func (s *Stream) Filters() []Filter

Filters returns the stream's filters in the order they were applied when writing; decoding runs them in the same order (7.3.8.2: /Filter, /DecodeParms).

func (*Stream) IsExternal

func (s *Stream) IsExternal() bool

IsExternal reports whether the stream's data is in another file, named by its /F entry (ISO 32000-2 7.3.8.4). The library never opens that file: such a stream reads as empty.

Example
package main

import (
	"bytes"
	"fmt"

	"recursiveai.org/go/onepdf"
)

func main() {
	pdf := []byte("%PDF-1.7\n" +
		"1 0 obj\n<</Type /Catalog/Pages 2 0 R>>\nendobj\n" +
		"2 0 obj\n<</Type /Pages/Kids []/Count 0>>\nendobj\n" +
		"5 0 obj\n<</F (data.bin)/Length 0>>\nstream\n\nendstream\nendobj\n" +
		"trailer\n<</Root 1 0 R>>\n")
	doc, err := onepdf.OpenBytes(pdf)
	if err != nil {
		fmt.Println(err)
		return
	}
	o, _ := doc.Object(5)
	s := o.(*onepdf.Stream)
	off, _, ok := doc.SourceOffset(s)
	fmt.Println(s.IsExternal(), ok, bytes.HasPrefix(pdf[off:], []byte("5 0 obj")))
}
Output:
true true true

func (*Stream) Raw

func (s *Stream) Raw() ([]byte, error)

Raw returns the stored bytes, still filtered. The result must not be modified.

func (*Stream) Ref

func (s *Stream) Ref() Ref

Ref returns the reference the stream was read through, or the zero Ref.

func (*Stream) SetData

func (s *Stream) SetData(data []byte, compress bool) error

SetData replaces the stream's data with data, which is taken as the unfiltered content. The /Filter and /DecodeParms entries are removed and, when compress is set, the data is stored Flate-compressed with /Filter /FlateDecode. /Length is written at save time.

It works on streams being built (NewStream) and, like Dict.Set, on streams of a document opened with WithEditing.

func (*Stream) SetStoredBytes

func (s *Stream) SetStoredBytes(data []byte) error

SetStoredBytes replaces the stream's stored bytes with data exactly as given. The caller keeps /Filter and /DecodeParms in step with them.

func (*Stream) StoredLength

func (s *Stream) StoredLength() int64

StoredLength returns the number of stored bytes, which can differ from the dictionary's /Length when that was wrong.

type StreamPage

type StreamPage struct {
	*ContentBuilder
	// contains filtered or unexported fields
}

StreamPage is a ContentBuilder for one page of a DocumentWriter. The page is written when it is committed. Before Commit it takes page boxes, links and tagged content.

func (p *StreamPage) AddLink(area Rect, uri string, element *StructNode, description string) error

AddLink adds a link annotation over area that opens a URI. element, when not nil, is the structure element (of type Link) the annotation belongs to, tied with an object reference (ISO 32000-2 14.7.5.3); description is the annotation's /Contents, an alternate description for assistive technology.

func (*StreamPage) AddLinkToDestination

func (p *StreamPage) AddLinkToDestination(area Rect, destination string, element *StructNode, description string) error

AddLinkToDestination adds a link annotation that goes to a named destination, which may be defined before or after the link.

func (*StreamPage) BeginTaggedContent

func (p *StreamPage) BeginTaggedContent(e *StructNode, tag string) (int, error)

BeginTaggedContent begins a marked-content sequence for the element on this page and returns its identifier (/MCID); end it with EndMarkedContent. The tag is the element's type when empty. An element can take content from several pages. An element that has ended is ErrNotEditable.

func (*StreamPage) Close

func (p *StreamPage) Close() error

Close drops the page without writing it. The page's reference stays reserved and is left free in the file; pages begun before keep their numbers. A page with tagged content cannot be dropped.

func (*StreamPage) Commit

func (p *StreamPage) Commit() error

Commit writes the page: its content stream, its annotations and its page object. Open Save levels and marked-content sequences are closed first. It returns the first error a call recorded, in which case the page is dropped.

func (*StreamPage) Height

func (p *StreamPage) Height() float64

Height is the page's media box height.

func (*StreamPage) IsCommitted

func (p *StreamPage) IsCommitted() bool

IsCommitted reports whether the page has been written.

func (*StreamPage) PageIndex

func (p *StreamPage) PageIndex() int

PageIndex is the zero-based position of the page in the document.

func (*StreamPage) Reference

func (p *StreamPage) Reference() Ref

Reference is the reference the page is written under; it is valid before and after Commit.

func (*StreamPage) SetArtBox

func (p *StreamPage) SetArtBox(r Rect) error

SetArtBox sets the page's ArtBox, the meaningful content.

func (*StreamPage) SetBleedBox

func (p *StreamPage) SetBleedBox(r Rect) error

SetBleedBox sets the page's BleedBox.

func (*StreamPage) SetBoxColor

func (p *StreamPage) SetBoxColor(box PageBox, c BoxColor) error

SetBoxColor sets how viewers outline a page box (/BoxColorInfo, ISO 32000-2 14.11.2.2): colour, line width, and a solid or dashed line with its dash array, as Page.SetBoxColor does for a read document. The media box has none; a colour component outside 0 to 1, or a negative or non-finite width or dash, is ErrArgument. A second call for the same box replaces the first.

Example
package main

import (
	"bytes"
	"fmt"

	"recursiveai.org/go/onepdf"
)

func main() {
	var out bytes.Buffer
	w := onepdf.NewDocumentWriter(&out)
	p, _ := w.BeginPage(200, 200, 0)
	// Trim box outlined in orange with a dashed line.
	err := p.SetBoxColor(onepdf.TrimBox, onepdf.BoxColor{R: 1, G: 0.5, LineWidth: 1, Style: onepdf.BoxDashed, Dash: []float64{3, 2}})
	if err != nil {
		fmt.Println(err)
		return
	}
	p.Commit()
	if err := w.Finish(); err != nil {
		fmt.Println(err)
		return
	}
	doc, _ := onepdf.OpenBytes(out.Bytes())
	page, _ := doc.Page(0)
	c, _ := page.BoxColor(onepdf.TrimBox)
	fmt.Println(c.Style == onepdf.BoxDashed, c.Dash)
}
Output:
true [3 2]

func (*StreamPage) SetBoxColorInfo

func (p *StreamPage) SetBoxColorInfo(box PageBox, r, g, b, lineWidth float64) error

SetBoxColorInfo is SetBoxColor for a solid line given as red, green, blue and width. Components outside 0 to 1 are clamped.

func (*StreamPage) SetCropBox

func (p *StreamPage) SetCropBox(r Rect) error

SetCropBox sets the page's CropBox, the region a viewer shows.

func (*StreamPage) SetTrimBox

func (p *StreamPage) SetTrimBox(r Rect) error

SetTrimBox sets the page's TrimBox, the finished page size.

func (*StreamPage) SetUserUnit

func (p *StreamPage) SetUserUnit(u float64) error

SetUserUnit sets /UserUnit, the size of a unit in 1/72 inch (PDF 1.6).

func (*StreamPage) Width

func (p *StreamPage) Width() float64

Width is the page's media box width.

type String

type String string

String is a PDF string: the bytes after escape and hexadecimal decoding, never text. Text reads them as a PDF text string.

func TextString

func TextString(text string) String

TextString returns text as a PDF text string: PDFDocEncoding when every character has a code in it, otherwise UTF-16BE with a byte-order mark.

Example
package main

import (
	"fmt"

	"recursiveai.org/go/onepdf"
)

func main() {
	s := onepdf.TextString("café – 日本")
	fmt.Println(s.Text())
	fmt.Println(onepdf.TextString("plain") == "plain")
}
Output:
café – 日本
true

func (String) Text

func (s String) Text() string

Text reads s as a PDF text string (ISO 32000-2 7.9.2.2): UTF-16BE or UTF-16LE after a byte-order mark, UTF-8 after its mark, and PDFDocEncoding otherwise. Language escapes in UTF-16 are dropped. A byte that PDFDocEncoding leaves undefined (0x7F, 0x9F, 0xAD) reads as U+FFFD, and so does an unpaired surrogate.

type StructNode

type StructNode struct {
	// contains filtered or unexported fields
}

StructNode is a node of the structure tree a DocumentWriter writes. It is written when it ends, so memory follows the nesting depth, not the size of the document.

func (*StructNode) Type

func (e *StructNode) Type() string

Type is the element's structure type, such as "P" or "Table".

type StructureOptions

type StructureOptions struct {
	// ID is the element's /ID, unique in the document.
	ID string
	// Title is /T, a human-readable title.
	Title string
	// ActualText is the text the element stands for.
	ActualText string
	// Alt is alternate text, for a figure.
	Alt string
	// Lang is a language tag for the element's content.
	Lang string
	// Expansion expands an abbreviation (/E).
	Expansion string
	// Attributes is an attribute object (/A), such as TableHeaderAttributes.
	Attributes *Dict
}

StructureOptions are the optional entries of a structure element. The zero value is valid and adds none: empty fields are left out.

type Substitute

type Substitute struct {
	// Name identifies the face ("LiberationSans-Regular").
	Name string
	// CacheKey identifies the program for caches; equal keys mean equal
	// programs. It defaults to Name.
	CacheKey string
	// Data is a TrueType, OpenType or bare CFF program; FaceIndex picks the
	// font of a collection. Read the program with Bytes, which also covers Load.
	Data []byte
	// Load, when Data is empty, returns the program on first use, so that a
	// provider offering many faces reads a file only for the face that is
	// used. The library calls it at most once per Substitute value, and
	// the result is kept; it may be called from any goroutine. An error means
	// the face is unusable. Data wins when both are set.
	Load      func() ([]byte, error)
	FaceIndex int
	// Fallbacks are faces to try, in order, for characters Data has no glyph for.
	Fallbacks []*Substitute
	// MapCodePoint, when set, maps a Unicode value to the one the face's
	// character map is asked for (a face that holds Symbol's characters at
	// other code points).
	MapCodePoint func(cp int) int
	// contains filtered or unexported fields
}

A Substitute is a font program a FontProvider offers for a font the document does not embed.

func (*Substitute) Bytes

func (s *Substitute) Bytes() []byte

Bytes returns the face's program: Data, or what Load returns the first time it is asked. It is nil when the face has neither or Load failed.

Example
package main

import (
	"fmt"

	"recursiveai.org/go/onepdf"
)

func main() {
	loads := 0
	s := &onepdf.Substitute{Name: "Lazy", Load: func() ([]byte, error) {
		loads++
		return []byte("font program"), nil
	}}
	fmt.Println("loads before use:", loads)
	fmt.Println(string(s.Bytes()), string(s.Bytes()), "loads:", loads)
}
Output:
loads before use: 0
font program font program loads: 1

type SubstituteEntry

type SubstituteEntry struct {
	// Object is the font's object number and BaseFont its /BaseFont as the
	// document had it.
	Object   int
	BaseFont string
	Outcome  SubstituteOutcome
	// Substitute is the face embedded, "" when none.
	Substitute string
	// Failure is the reason of a refusal, 0 otherwise; Message explains the
	// outcome in words.
	Failure FontEmbedReason
	Message string
	// FromCaller is true when the face came from [WithFaceForFont].
	FromCaller bool
	// MissingCodes are shown codes the face has no glyph for (they draw
	// .notdef); WidthConflicts and WidthChanges are as in [FontEmbedResult].
	MissingCodes, WidthConflicts []int
	WidthChanges                 []FontWidthChange
}

SubstituteEntry reports one font.

type SubstituteOption

type SubstituteOption interface {
	// contains filtered or unexported methods
}

SubstituteOption configures Document.EmbedSubstituteFonts.

func WithFaceForFont

func WithFaceForFont(fn func(SubstituteRequest) *FontFile) SubstituteOption

WithFaceForFont supplies a face of the caller's for fonts the provider has none for (Verdana, Calibri and most other faces have no metric-compatible substitute). It is asked only for those fonts. The face must have TrueType outlines; licensing is the caller's, but fsType is checked. A nil result means no face.

func WithSubstituteProvider

func WithSubstituteProvider(p FontProvider) SubstituteOption

WithSubstituteProvider takes the faces from p for this call, instead of the document's provider and the registered ones.

func WithSubstituteSubsetting

func WithSubstituteSubsetting(on bool) SubstituteOption

WithSubstituteSubsetting chooses between a subset of each face (the default) and the whole face.

func WithSubstituteWidths

func WithSubstituteWidths(p WidthPolicy) SubstituteOption

WithSubstituteWidths sets the width policy (default WidthsAdjustProgram).

type SubstituteOutcome

type SubstituteOutcome int

SubstituteOutcome says what EmbedSubstituteFonts did with one font.

const (
	// SubstituteEmbedded: a substitute subset was written into the font.
	SubstituteEmbedded SubstituteOutcome = iota + 1
	// SubstituteAlreadyEmbedded: the font has a program; nothing was done.
	SubstituteAlreadyEmbedded
	// SubstituteNone: no provider face and no caller face fits the font.
	SubstituteNone
	// SubstituteNoProvider: no font provider is set at all.
	SubstituteNoProvider
	// SubstituteRefused: a face was found but could not be embedded; see Failure.
	SubstituteRefused
)

The outcomes for a font.

func (SubstituteOutcome) String

func (o SubstituteOutcome) String() string

String returns "Embedded", "AlreadyEmbedded", "NoSubstitute", "NoFontProvider" or "Refused".

type SubstituteReport

type SubstituteReport struct {
	// ProviderMissing is true when no provider was set, per call, on the
	// document or registered.
	ProviderMissing bool
	// ProviderMessage says how to supply one; it is "" when there is one.
	ProviderMessage string
	EmbeddedCount   int
	Entries         []SubstituteEntry
}

SubstituteReport is what EmbedSubstituteFonts did.

type SubstituteRequest

type SubstituteRequest struct {
	// FontName is the base font without subset tag; BaseFont as the document has it.
	FontName, BaseFont                                   string
	Bold, Italic, Serif, FixedPitch, Symbolic, Composite bool
}

SubstituteRequest describes a font to WithFaceForFont.

type TextAlignment

type TextAlignment int

TextAlignment places a line of text in a span or box.

const (
	AlignLeft TextAlignment = iota
	AlignCenter
	AlignRight
	AlignJustify
)

The alignments. Justify widens the gaps between words so a line fills the width; the last line of a paragraph stays left aligned.

func (TextAlignment) String

func (a TextAlignment) String() string

String returns the alignment's name.

type TextRenderMode

type TextRenderMode int

TextRenderMode says how glyphs are painted (ISO 32000-2 9.3.6).

const (
	TextFill TextRenderMode = iota
	TextStroke
	TextFillStroke
	TextInvisible
	TextFillClip
	TextStrokeClip
	TextFillStrokeClip
	TextClip
)

The text rendering modes. The clip modes add the glyph outlines to the clipping region when the text object ends.

func (TextRenderMode) String

func (m TextRenderMode) String() string

String returns the mode's name.

type ToUnicodeChooser

type ToUnicodeChooser func(UnmappedCode) string

ToUnicodeChooser returns the text for a code the Unicode chain cannot read, or "" to leave it unmapped.

type ToUnicodeEntry

type ToUnicodeEntry struct {
	// Object is the font's object number; Font its dictionary.
	Object   int
	Font     *Dict
	BaseFont string
	// CodesAdded counts codes given an entry; CodesFromCaller those whose
	// text came from the chooser.
	CodesAdded, CodesFromCaller int
	// MapRewritten is true when an existing map's ranges were rewritten
	// because they crossed a block of 256 codes.
	MapRewritten bool
	// CodesWithoutUnicode are shown codes no text is known for.
	CodesWithoutUnicode []int
}

ToUnicodeEntry is what AddMissingToUnicode did for one font.

type ToUnicodeOption

type ToUnicodeOption interface {
	// contains filtered or unexported methods
}

ToUnicodeOption configures Document.AddMissingToUnicode.

func WithToUnicodeChooser

func WithToUnicodeChooser(fn ToUnicodeChooser) ToUnicodeOption

WithToUnicodeChooser lets the caller supply text for codes the chain cannot read. It is asked once for each such shown code; the text is written to the font's /ToUnicode.

type ToUnicodeReport

type ToUnicodeReport struct {
	CodesAdded, FontsChanged, FontsWithUnknownCodes int
	Entries                                         []ToUnicodeEntry
}

ToUnicodeReport is what AddMissingToUnicode did.

type UnmappedCode

type UnmappedCode struct {
	BaseFont  string
	Code      int
	GlyphName string
	GlyphID   int
	Width     float64
}

UnmappedCode describes a shown code no text could be found for, for a ToUnicodeChooser.

type Version

type Version struct {
	Major, Minor int
}

Version is a PDF version such as 1.7 or 2.0 (ISO 32000-2 7.2.2). The zero Version means "none": a file without a usable header version, or no requirement. Versions compare with ==, and Less orders them.

func ParseVersion

func ParseVersion(s string) (Version, error)

ParseVersion reads "1.7" or "2.0": a single digit, a dot and a single digit, the form of a header or of the catalog's /Version name. Anything else is ErrArgument.

func (Version) Less

func (v Version) Less(w Version) bool

Less reports whether v is an earlier version than w.

func (Version) String

func (v Version) String() string

String returns "1.7", or "" for the zero Version.

type ViewerPreferences

type ViewerPreferences struct {
	HideToolbar, HideMenubar, HideWindowUI, FitWindow, CenterWindow, DisplayDocTitle Opt[bool]
	// PickTrayByPDFSize is /PickTrayByPDFSize.
	PickTrayByPDFSize Opt[bool]
	// PrintScaling is PrintScalingAppDefault or PrintScalingNone.
	PrintScaling Opt[PrintScaling]
	// Duplex is DuplexSimplex, DuplexFlipShortEdge or DuplexFlipLongEdge.
	Duplex Opt[Duplex]
	// NumCopies is /NumCopies.
	NumCopies Opt[int]
	// PrintPageRange is /PrintPageRange as first and last page pairs, one-based as stored;
	// nil when absent or when the array has an odd length.
	PrintPageRange [][2]int
	// ViewArea, ViewClip, PrintArea and PrintClip name a page box.
	ViewArea, ViewClip, PrintArea, PrintClip Opt[PageBox]
	// Dict is the whole dictionary, unknown entries included.
	Dict *Dict
}

ViewerPreferences are the catalog's /ViewerPreferences (ISO 32000-2 12.2, Table 147) as data. A preference the file does not set, or sets with the wrong type or an unknown name, is not Valid.

type WidthMatchEntry

type WidthMatchEntry struct {
	// Object is the font dictionary's object number, 0 for a direct dictionary.
	Object   int
	Font     *Dict
	BaseFont string
	Outcome  WidthMatchOutcome
	// WidthChanges lists the shown codes whose width differed by more than
	// the tolerance, with the program's advance before the rewrite.
	WidthChanges []FontWidthChange
	// Note says why a font was refused.
	Note string
}

A WidthMatchEntry is the result for one font dictionary with an embedded program.

type WidthMatchOption

type WidthMatchOption interface {
	// contains filtered or unexported methods
}

WidthMatchOption configures Document.MatchEmbeddedFontWidths.

func WithWidthTolerance

func WithWidthTolerance(t float64) WidthMatchOption

WithWidthTolerance sets how large a difference between the PDF's width and the program's, in thousandths of an em, is ignored. The default is 0.01.

type WidthMatchOutcome

type WidthMatchOutcome int

WidthMatchOutcome says what MatchEmbeddedFontWidths did with one font.

const (
	// WidthMatched: the program was rewritten and now agrees with the PDF.
	WidthMatched WidthMatchOutcome = iota + 1
	// WidthAlreadyMatching: every shown glyph already has the PDF's width.
	WidthAlreadyMatching
	// WidthUnsupportedProgram: TrueType, OpenType and Type 1 programs are
	// examined but not rewritten.
	WidthUnsupportedProgram
	// WidthRefused: the program cannot be rewritten safely (a glyph reaches
	// its width through a subroutine call, or the result did not read back
	// the same); the font is as it was.
	WidthRefused
)

The outcomes for a font.

func (WidthMatchOutcome) String

func (o WidthMatchOutcome) String() string

String returns "Matched", "AlreadyMatching", "UnsupportedProgram" or "Refused".

type WidthMatchReport

type WidthMatchReport struct {
	Entries []WidthMatchEntry
	// FontsRewritten counts the entries that are WidthMatched.
	FontsRewritten int
}

WidthMatchReport says what MatchEmbeddedFontWidths did.

type WidthPolicy

type WidthPolicy int

WidthPolicy says what to do when a program's advance differs from the PDF's /Widths or /W.

const (
	// WidthsAdjustProgram sets the program's advances to the PDF's widths, so
	// ISO 14289-1 7.21.5 holds and no glyph moves. Where one glyph serves
	// codes of different widths, the first code's width wins.
	WidthsAdjustProgram WidthPolicy = iota
	// WidthsKeepProgram leaves the program's own advances and reports the
	// differences.
	WidthsKeepProgram
	// WidthsRefuse refuses the program with [EmbedWidthMismatch] when an
	// advance differs by more than the tolerance.
	WidthsRefuse
)

func (WidthPolicy) String

func (p WidthPolicy) String() string

String returns the policy's name.

type WriterOption

type WriterOption interface {
	// contains filtered or unexported methods
}

WriterOption configures a DocumentWriter.

func WithWriterCloseOutput

func WithWriterCloseOutput() WriterOption

WithWriterCloseOutput makes Finish close the output when it is an io.Closer. By default the output is the caller's and stays open.

func WithWriterCompression

func WithWriterCompression(on bool) WriterOption

WithWriterCompression says whether content streams are Flate-compressed (default true).

func WithWriterDisplayTitle

func WithWriterDisplayTitle() WriterOption

WithWriterDisplayTitle asks viewers to show the document title instead of the file name (/DisplayDocTitle).

func WithWriterLanguage

func WithWriterLanguage(tag string) WriterOption

WithWriterLanguage sets the document's natural language, a tag such as "en-US", written as the catalog's /Lang (ISO 32000-2 14.9.2).

func WithWriterViewerPreferences

func WithWriterViewerPreferences(p ViewerPreferences) WriterOption

WithWriterViewerPreferences sets the viewer preferences (ISO 32000-2 12.2).

func WithWriterXRef

func WithWriterXRef(f XRefFormat) WriterOption

WithWriterXRef chooses the cross-reference form: XRefStream, XRefTable, or XRefAuto, the default, which is a stream from version 1.5 on.

type XMP

type XMP struct {
	// Raw is the decoded stream bytes exactly as stored, padding included.
	Raw []byte
	// WellFormed is true when Raw parses as XML.
	WellFormed bool

	// Title is dc:title; the x-default language alternative when there is one, otherwise the first.
	Title string
	// Creators is dc:creator in order.
	Creators []string
	// Subjects is dc:subject in order.
	Subjects []string
	// Description is dc:description, chosen like Title.
	Description string
	// Keywords is pdf:Keywords.
	Keywords string
	// Producer is pdf:Producer.
	Producer string
	// CreatorTool is xmp:CreatorTool.
	CreatorTool string
	// CreateDate, ModifyDate and MetadataDate are xmp:CreateDate, xmp:ModifyDate
	// and xmp:MetadataDate in UTC; the zero time when absent or unreadable.
	// A date without a zone is UTC.
	CreateDate, ModifyDate, MetadataDate time.Time
	// PDFAPart and PDFAConformance are pdfaid:part and pdfaid:conformance, the PDF/A
	// identification; 0 and "" when absent.
	PDFAPart        int
	PDFAConformance string
	// PDFUAPart and PDFUARevision are pdfuaid:part and pdfuaid:rev, the PDF/UA
	// identification; 0 when absent.
	PDFUAPart, PDFUARevision int
}

XMP is the document's XMP metadata packet (ISO 32000-2 14.3.2) read as data: the raw bytes and the properties every PDF reader wants. Fields hold the zero value when the packet lacks the property. A packet that is not well-formed XML keeps its Raw bytes and has WellFormed false; its other fields are empty.

The packet is never expanded beyond the five predefined XML entities and character references, and nothing external is fetched.

type XMPField

type XMPField struct {
	NS, Name string
	Value    XMPValue
}

XMPField is one field of a structure value: the property ns:Name with its value.

type XMPPacket

type XMPPacket struct {
	// contains filtered or unexported fields
}

XMPPacket is an XMP packet (ISO 16684-1) held as an ordered list of properties, to be built from nothing or read from an existing packet, changed and written again. Properties the packet had and the caller does not touch are kept as read, whatever their namespace and shape; a value set by the caller replaces the old one in place, and a new property goes at the end.

The zero value is an empty packet. An XMPPacket is not safe for concurrent use.

Example

An XMPPacket is built, or read from a document's metadata, changed and written again.

package main

import (
	"fmt"
	"log"

	"recursiveai.org/go/onepdf"
)

func main() {
	p := onepdf.NewXMPPacket()
	p.Set(onepdf.XMPNSDublinCore, "title", onepdf.XMPLangAlt("x-default", "Annual report"))
	p.Set(onepdf.XMPNSPDFUA, "part", onepdf.XMPText("1"))
	back, err := onepdf.ParseXMPPacket(p.Bytes())
	if err != nil {
		log.Fatal(err)
	}
	back.Set(onepdf.XMPNSPDFUA, "part", onepdf.XMPText("2"))
	title, _ := back.Text(onepdf.XMPNSDublinCore, "title")
	part, _ := back.Text(onepdf.XMPNSPDFUA, "part")
	fmt.Println(title, part)
}
Output:
Annual report 2

func NewXMPPacket

func NewXMPPacket() *XMPPacket

NewXMPPacket returns an empty packet.

func ParseXMPPacket

func ParseXMPPacket(raw []byte) (*XMPPacket, error)

ParseXMPPacket reads a packet as stored in a metadata stream, in UTF-8 or UTF-16. Properties given as attributes of rdf:Description are read as simple properties. It fails with an error that matches ErrFormat when the text is not well-formed XML or holds no rdf:Description.

func (*XMPPacket) Bytes

func (p *XMPPacket) Bytes() []byte

Bytes serialises the packet as UTF-8 with the xpacket wrapper (ISO 16684-1 7.3), marked writable (end="w"). The output depends only on the packet's content: the same properties in the same order give the same bytes.

func (*XMPPacket) Has

func (p *XMPPacket) Has(ns, name string) bool

Has reports whether the packet has the property ns:name.

func (*XMPPacket) RegisterPrefix

func (p *XMPPacket) RegisterPrefix(prefix, ns string)

RegisterPrefix chooses the prefix written for a namespace. The common schemas have their usual prefixes (dc, xmp, pdf, pdfaid, pdfuaid, xmpMM, pdfaExtension, pdfaSchema, pdfaProperty); a prefix read from a packet is kept. A namespace with no prefix gets ns1, ns2 and so on. A prefix already used for another namespace is left alone.

func (*XMPPacket) Remove

func (p *XMPPacket) Remove(ns, name string) bool

Remove deletes the property ns:name and reports whether it was there.

func (*XMPPacket) Set

func (p *XMPPacket) Set(ns, name string, v XMPValue)

Set gives the property ns:name the value v, replacing an existing one in place. The name is the local name without a prefix.

func (*XMPPacket) Text

func (p *XMPPacket) Text(ns, name string) (string, bool)

Text returns the text of a simple property, or of the first item (the default language when there is one) of an array or language alternative.

type XMPValue

type XMPValue struct {
	// contains filtered or unexported fields
}

XMPValue is the value of an XMP property: simple text, an ordered or unordered array of text, or a language alternative.

func XMPBag

func XMPBag(items ...string) XMPValue

XMPBag is an unordered array (rdf:Bag), such as dc:subject.

func XMPBagOfStructs

func XMPBagOfStructs(items ...[]XMPField) XMPValue

XMPBagOfStructs is an unordered array whose items are structures (rdf:parseType="Resource"), each an ordered list of fields, as the PDF/A extension schema container pdfaExtension:schemas is.

func XMPLangAlt

func XMPLangAlt(lang, text string) XMPValue

XMPLangAlt is a language alternative (rdf:Alt) with one item, in the language lang. The default language is "x-default", which dc:title and dc:description should always carry (ISO 16684-1 8.2.2.4).

func XMPSeq

func XMPSeq(items ...string) XMPValue

XMPSeq is an ordered array (rdf:Seq), such as dc:creator.

func XMPSeqOfStructs

func XMPSeqOfStructs(items ...[]XMPField) XMPValue

XMPSeqOfStructs is XMPBagOfStructs as an ordered array (rdf:Seq), as pdfaSchema:property is.

func XMPText

func XMPText(s string) XMPValue

XMPText is a simple property: <dc:format>application/pdf</dc:format>.

func (XMPValue) With

func (v XMPValue) With(lang, text string) XMPValue

With returns the alternative with one more item, in the language lang. It applies to a language alternative.

type XRefEntry

type XRefEntry struct {
	Kind EntryKind
	// Generation is the generation number from the cross-reference data.
	Generation int
	// Offset is, for EntryInUse, the byte offset in the source of the object's "n g obj" line.
	Offset int64
	// Container is, for EntryCompressed, the number of the object stream that holds the object.
	Container int
	// Index is, for EntryCompressed, the object's position in that object stream.
	Index int
}

XRefEntry is where the file says an object lives.

type XRefFormat

type XRefFormat int

XRefFormat selects how a saved file records where its objects are.

const (
	// XRefAuto follows the document's newest revision: a table for a table, a stream for a stream.
	XRefAuto XRefFormat = iota
	// XRefTable writes a classic table and no object streams (ISO 32000-2 7.5.4).
	XRefTable
	// XRefStream writes a cross-reference stream and, unless WithObjectStreams(false) says otherwise,
	// object streams (7.5.8, 7.5.7). It needs PDF 1.5.
	XRefStream
)

Cross-reference formats.

func (XRefFormat) String

func (f XRefFormat) String() string

String returns "Auto", "Table" or "Stream".

Source Files

Directories

Path Synopsis
Package device defines the drawing device that the content-stream interpreter drives, and the plain data types it passes: geometry, paths, graphics state, colours in a final space, glyph runs, finished images, decoded shadings, patterns, soft masks and transparency groups.
Package device defines the drawing device that the content-stream interpreter drives, and the plain data types it passes: geometry, paths, graphics state, colours in a final space, glyph runs, finished images, decoded shadings, patterns, soft masks and transparency groups.
displaylist
Package displaylist records the calls a device.Device receives, replays them (optionally culled to a clip box), and reads and writes the display-list text format.
Package displaylist records the calls a device.Device receives, replays them (optionally culled to a clip box), and reads and writes the display-list text format.
fonts module
internal
ccitt
Package ccitt decodes CCITTFaxDecode data: ITU-T T.4 Group 3 (one- and two-dimensional) and T.6 Group 4, with the options of ISO 32000-2 7.4.6.
Package ccitt decodes CCITTFaxDecode data: ITU-T T.4 Group 3 (one- and two-dimensional) and T.6 Group 4, with the options of ISO 32000-2 7.4.6.
cff
Package cff reads Compact Font Format programs (Adobe Technical Note 5176), bare or inside an OpenType wrapper, and interprets their Type 2 charstrings (Technical Note 5177).
Package cff reads Compact Font Format programs (Adobe Technical Note 5176), bare or inside an OpenType wrapper, and interprets their Type 2 charstrings (Technical Note 5177).
cmap
Package cmap reads CMaps (Adobe Technical Notes 5014 and 5099; ISO 32000-2 9.7.5 and 9.10.3): the embedded streams of Type 0 fonts and /ToUnicode, and the predefined CMaps of the Adobe character collections.
Package cmap reads CMaps (Adobe Technical Notes 5014 and 5099; ISO 32000-2 9.7.5 and 9.10.3): the embedded streams of Type 0 fonts and /ToUnicode, and the predefined CMaps of the Adobe character collections.
cms
Package cms reads CMS SignedData (RFC 5652) and RFC 3161 time-stamp tokens and checks their signatures.
Package cms reads CMS SignedData (RFC 5652) and RFC 3161 time-stamp tokens and checks their signatures.
conform
Package conform is the seam between the onepdf engine and the pdfa and pdfua packages.
Package conform is the seam between the onepdf engine and the pdfa and pdfua packages.
ctxcheck
Package ctxcheck backs the tests that every exported function taking a context.Context accepts a nil one.
Package ctxcheck backs the tests that every exported function taking a context.Context accepts a nil one.
deflate
Package deflate compresses data as DEFLATE (RFC 1951) inside the zlib wrapper (RFC 1950) that PDF's FlateDecode filter expects.
Package deflate compresses data as DEFLATE (RFC 1951) inside the zlib wrapper (RFC 1950) that PDF's FlateDecode filter expects.
der
Package der reads and writes the ASN.1 encodings that signatures use: DER, and the BER forms real files contain (indefinite lengths, constructed strings).
Package der reads and writes the ASN.1 encodings that signatures use: DER, and the BER forms real files contain (indefinite lengths, constructed strings).
filter
Package filter decodes PDF stream filters (ISO 32000-2 7.4).
Package filter decodes PDF stream filters (ISO 32000-2 7.4).
fontdata
Package fontdata holds the data tables PDF fonts need: the predefined encodings (ISO 32000-1 Annex D), the Adobe glyph list, the Core 14 font metrics, the predefined CMaps and the CID to Unicode tables for the Adobe character collections.
Package fontdata holds the data tables PDF fonts need: the predefined encodings (ISO 32000-1 Annex D), the Adobe glyph list, the Core 14 font metrics, the predefined CMaps and the CID to Unicode tables for the Adobe character collections.
hook
Package hook carries the few calls that the packages built on the root package (redact, tag) need into the root's engine, which they cannot import directly because the root must not import them.
Package hook carries the few calls that the packages built on the root package (redact, tag) need into the root's engine, which they cannot import directly because the root must not import them.
inflate
Package inflate decompresses DEFLATE (RFC 1951) and zlib (RFC 1950) data.
Package inflate decompresses DEFLATE (RFC 1951) and zlib (RFC 1950) data.
lex
Package lex splits PDF syntax (ISO 32000-2 7.2) into tokens.
Package lex splits PDF syntax (ISO 32000-2 7.2) into tokens.
pdfstr
Package pdfstr holds the small string rules the root package and the text extraction engine share.
Package pdfstr holds the small string rules the root package and the text extraction engine share.
predictor
Package predictor undoes the PNG and TIFF predictors that Flate and LZW streams may apply before compression (ISO 32000-2 7.4.4.4).
Package predictor undoes the PNG and TIFF predictors that Flate and LZW streams may apply before compression (ISO 32000-2 7.4.4.4).
rc4
Package rc4 is the RC4 stream cipher as the PDF standard security handler uses it (ISO 32000-2 7.6.3.2, Algorithm 1).
Package rc4 is the RC4 stream cipher as the PDF standard security handler uses it (ISO 32000-2 7.6.3.2, Algorithm 1).
subset
Package subset writes TrueType font programs for embedding in a PDF: a subset that keeps only the glyphs a document shows, and a copy of a whole font whose horizontal advances were changed.
Package subset writes TrueType font programs for embedding in a PDF: a subset that keeps only the glyphs a document shows, and a copy of a whole font whose horizontal advances were changed.
textlayout
Package textlayout turns the glyphs a page shows into words, lines and blocks in reading order, and into the three plain-text forms.
Package textlayout turns the glyphs a page shows into words, lines and blocks in reading order, and into the three plain-text forms.
truetype
Package truetype reads TrueType and OpenType font programs: the sfnt table directory, character maps, metrics, glyf outlines (with composites) and, for OpenType-CFF, the CFF table through package cff.
Package truetype reads TrueType and OpenType font programs: the sfnt table directory, character maps, metrics, glyf outlines (with composites) and, for OpenType-CFF, the CFF table through package cff.
type1
Package type1 reads Adobe Type 1 font programs (PFA, PFB and the bare form embedded in PDF) and produces glyph outlines.
Package type1 reads Adobe Type 1 font programs (PFA, PFB and the bare form embedded in PDF) and produces glyph outlines.
writer
Package writer holds the byte-level pieces of writing a PDF file: tokens, cross-reference sections and the file's fixed text.
Package writer holds the byte-level pieces of writing a PDF file: tokens, cross-reference sections and the file's fixed text.
Package layout lays out documents: styled text shaped with onefont, boxes, columns, rows, layers, lists and tables, split over pages with keep rules, widow and orphan control, repeated headers and footers and page numbers.
Package layout lays out documents: styled text shaped with onefont, boxes, columns, rows, layers, lists and tables, split over pages with keep rules, widow and orphan control, repeated headers and footers and page numbers.
hyphen
Package hyphen finds hyphenation points with Liang's algorithm, the method of TeX. It bundles the public hyph-utf8 pattern and exception files of 26 languages (see data/NOTICES.txt for each file's copyright and licence) and builds hyphenators from the caller's own patterns.
Package hyphen finds hyphenation points with Liang's algorithm, the method of TeX. It bundles the public hyph-utf8 pattern and exception files of 26 languages (see data/NOTICES.txt for each file's copyright and licence) and builds hyphenators from the caller's own patterns.
Package pdfa checks, prepares, writes and converts to PDF/A (ISO 19005-2 and -3).
Package pdfa checks, prepares, writes and converts to PDF/A (ISO 19005-2 and -3).
Package pdfua checks, prepares and writes PDF/UA (ISO 14289-1 and -2), the accessibility profile of PDF.
Package pdfua checks, prepares and writes PDF/UA (ISO 14289-1 and -2), the accessibility profile of PDF.
Package redact removes content from a PDF document for good.
Package redact removes content from a PDF document for good.
Package sign lists, verifies and writes the digital signatures in a PDF document.
Package sign lists, verifies and writes the digital signatures in a PDF document.
Package tag adds, reads, edits and removes the logical structure of a PDF document (ISO 32000-2 14.7 and 14.8): the structure tree, the marked content that ties it to the pages, and the artifact marks for what is not content.
Package tag adds, reads, edits and removes the logical structure of a PDF document (ISO 32000-2 14.7 and 14.8): the structure tree, the marked content that ties it to the pages, and the artifact marks for what is not content.
Package text extracts the text of PDF pages: glyphs with their geometry, words, lines and blocks in reading order, and the plain text in three forms.
Package text extracts the text of PDF pages: glyphs with their geometry, words, lines and blocks in reading order, and the plain text in three forms.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL