core

package
v0.11.0 Latest Latest
Warning

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

Go to latest
Published: Oct 23, 2026 License: Apache-2.0 Imports: 20 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.

Documentation

Overview

Package core implements the fundamental PDF object types defined in ISO 32000 §7.3 — Boolean, Number, String, Name, Array, Dictionary, Stream, and Null — plus indirect references (§7.3.10) and standard security handler encryption (§7.6).

Every object type satisfies the PdfObject interface, which provides WriteTo for serialization and Type for runtime type discrimination. Composite types (Array, Dictionary, Stream) preserve insertion order to produce deterministic output.

Encryption covers three standard security handler revisions:

  • RC4-128 (V=2, R=3): legacy, widely compatible
  • AES-128 (V=4, R=4): recommended minimum
  • AES-256 (V=5, R=6): strongest, PDF 2.0

Index

Constants

This section is empty.

Variables

View Source
var ErrInvalidPassword = errors.New("core: invalid password")

ErrInvalidPassword is returned when a candidate password matches neither the user nor the owner password recorded in /Encrypt.

View Source
var ErrUnsupportedEncryption = errors.New("core: unsupported encryption")

ErrUnsupportedEncryption is returned for security-handler configurations the Standard-handler decoder does not implement: non-Standard /Filter, unsupported /V or /R, or a crypt filter other than the standard AESV2/AESV3 configuration.

Functions

func DecodeTextString added in v0.11.0

func DecodeTextString(raw string) string

DecodeTextString decodes the raw bytes of a PDF text string (ISO 32000-1 §7.9.2.2) to Go UTF-8 text.

A value starting with the byte-order mark FE FF is UTF-16BE and is decoded (an odd trailing byte is dropped, unpaired surrogates become U+FFFD, and language escape sequences ESC … ESC are removed). A value starting with the UTF-8 BOM EF BB BF (allowed by ISO 32000-2) has the BOM stripped. Anything else is PDFDocEncoding and is mapped through Annex D.2, except that a value which is valid UTF-8 and contains a non-ASCII byte is returned unchanged: older folio releases wrote text strings as raw UTF-8, and those files stay readable.

func DeflateStreamData added in v0.7.0

func DeflateStreamData(data []byte) ([]byte, error)

DeflateStreamData compresses data using zlib (RFC 1950) at zlib.BestCompression — the encoding PDF's FlateDecode filter (ISO 32000-1 §7.4.4) expects. Exposed as a writer-side primitive for passes that need to produce FlateDecode payloads independently of PdfStream.WriteTo.

func DeflateStreamDataLevel added in v0.11.0

func DeflateStreamDataLevel(data []byte, level int) ([]byte, error)

DeflateStreamDataLevel compresses data using zlib (RFC 1950) at the given level (see compress/zlib level constants). It is the level-aware primitive behind DeflateStreamData and PdfStream.SetCompressLevel.

func EncodeTextStringUTF16BE added in v0.11.0

func EncodeTextStringUTF16BE(s string) string

EncodeTextStringUTF16BE returns the UTF-16BE byte representation of s prefixed with the UTF-16 byte-order mark (\xFE\xFF). The result is suitable as the value of a PDF text string per ISO 32000-1 §7.9.2.2. Code points outside the Basic Multilingual Plane are emitted as a UTF-16 surrogate pair (high surrogate + low surrogate). U+001B is dropped: inside a UTF-16 text string it marks a language escape, so a reader would hide the text that follows it.

func EncodeXRefStreamEntry added in v0.7.0

func EncodeXRefStreamEntry(dst []byte, e XRefStreamEntry, widths [3]int) error

EncodeXRefStreamEntry writes one entry into dst using the given field widths. dst must have length widths[0]+widths[1]+widths[2]. Each field is written big-endian and zero-padded to its assigned width. Returns an error if any field value does not fit in its assigned width.

func EscapeLiteralString

func EscapeLiteralString(s string) string

EscapeLiteralString escapes special characters inside a PDF literal string. Per ISO 32000 §7.3.4.2, the characters \, (, and ) must be escaped. Control characters (0x00–0x1F except \n, \r, \t) are escaped as octal.

func InflateStreamData added in v0.7.0

func InflateStreamData(data []byte) ([]byte, error)

InflateStreamData is the inverse of DeflateStreamData: it decompresses zlib-framed bytes (PDF FlateDecode payload). It is the writer-side counterpart used by the recompression pass; the reader has its own size-bounded inflate that defends against zip bombs at parse time. Streams reaching the writer are already in memory, so this helper does not impose a size cap — callers control input size.

func IsPDFDocASCII added in v0.11.0

func IsPDFDocASCII(s string) bool

IsPDFDocASCII reports whether s can be written as a text string unchanged: every byte is 7-bit ASCII that means the same character in PDFDocEncoding. Bytes 0x18–0x1F (which PDFDocEncoding assigns to spacing accents such as ˘ and ˜) and 0x7F (undefined) are excluded, so text containing them is encoded as UTF-16BE instead.

func XRefStreamWidths added in v0.7.0

func XRefStreamWidths(maxOffset, maxGen, maxObjStmNum, maxIndex int) [3]int

XRefStreamWidths returns the byte widths of the three fields of a cross-reference stream entry, sized to fit the largest value each field must hold (ISO 32000-1 §7.5.8.2).

  • field 1 is the entry type: 0 (free), 1 (in-use uncompressed), or 2 (in-use compressed in an object stream). Always 1 byte.
  • field 2 holds either a byte offset (type 1) or the object number of the containing object stream (type 2). It must be wide enough for the larger of maxOffset and maxObjStmNum.
  • field 3 holds either the generation number (type 1) or the index of the object within its containing object stream (type 2). It must be wide enough for the larger of maxGen and maxIndex.

Per §7.5.8.2 a width of zero is permitted and means "the field is not present and a default value is used", but the default for field 2 is 0 and for field 3 is 0 — both meaningless for any non-trivial document — so this function returns a minimum width of 1 byte for fields 2 and 3 even when the maximum value is 0. The spec allows this; it costs at most two bytes per entry and keeps the encoder simple.

All inputs must be non-negative.

Types

type AccessLevel added in v0.10.0

type AccessLevel int

AccessLevel reports which password unlocked an encrypted document, per ISO 32000-1 §7.6.3-7.6.4.

const (
	AccessNone  AccessLevel = iota // document is not encrypted
	AccessUser                     // opened with the user (open) password
	AccessOwner                    // opened with the owner (permissions) password
)

type Decryptor added in v0.10.0

type Decryptor struct {
	Revision        EncryptionRevision
	FileKey         []byte // 16 bytes (RC4/AES-128) or 32 bytes (AES-256)
	Access          AccessLevel
	P               int32 // permission flags from /P — authenticated against /Perms for R=6, informational only (never enforced)
	EncryptMetadata bool  // /EncryptMetadata; false means /Metadata streams are stored in the clear
	// contains filtered or unexported fields
}

Decryptor decrypts strings and stream payloads for a document encrypted with the Standard security handler. It mirrors Encryptor: key derivation is identical for encryption and decryption, and RC4 is symmetric, so decryption reuses most of the same unexported helpers.

func NewDecryptor added in v0.10.0

func NewDecryptor(dict *PdfDictionary, fileID []byte, password string) (*Decryptor, error)

NewDecryptor reads a resolved /Encrypt dictionary and authenticates password, trying it first as the user password (Algorithm 6 / 2.A), then as the owner password (Algorithm 7 / 2.A). fileID is the first element of the trailer /ID array and may be nil.

A wrong password returns ErrInvalidPassword. A configuration this decoder does not implement — a non-Standard or public-key handler, an unsupported /V or /R, or a crypt filter other than AESV2/AESV3 — returns ErrUnsupportedEncryption naming the value seen. Malformed /O, /U, /OE, or /UE entries (wrong type or too short) also return ErrUnsupportedEncryption rather than reading out of bounds.

func (*Decryptor) DecryptBytes added in v0.10.0

func (d *Decryptor) DecryptBytes(objNum, genNum int, data []byte) ([]byte, error)

DecryptBytes decrypts a string or stream payload belonging to the given indirect object (Algorithm 1). Objects nested inside an object stream must NOT be passed through this a second time — the containing /ObjStm was already decrypted as a whole.

func (*Decryptor) DecryptObject added in v0.10.0

func (d *Decryptor) DecryptObject(obj PdfObject, objNum, genNum int) error

DecryptObject walks obj in place, decrypting every string it contains. Streams are decrypted separately via Decryptor.DecryptBytes on their raw payload before decompression, so this walk descends into dictionaries, arrays, and strings only — mirroring [Encryptor.walkEncrypt] in reverse. Indirect references are left untouched; the object they point to is decrypted under its own object number when resolved.

type DictEntry

type DictEntry struct {
	Key   *PdfName
	Value PdfObject
}

DictEntry is a key-value pair in a PdfDictionary. We use a slice of entries rather than a map to preserve insertion order, which produces deterministic PDF output (important for testing and byte-level reproducibility).

type EncryptionRevision

type EncryptionRevision int

EncryptionRevision identifies the encryption algorithm.

const (
	// RevisionRC4128 selects the RC4-128 Standard Security Handler (V=2, R=3).
	// RC4 is cryptographically broken; prefer [RevisionAES256] for new
	// documents. The constant remains supported for reading and writing
	// legacy RC4-encrypted PDFs and is not scheduled for removal.
	RevisionRC4128 EncryptionRevision = 3
	RevisionAES128 EncryptionRevision = 4 // AES-128-CBC (V=4, R=4)
	RevisionAES256 EncryptionRevision = 6 // AES-256-CBC (V=5, R=6)
)

type Encryptor

type Encryptor struct {
	Revision EncryptionRevision
	FileKey  []byte // 16 bytes (RC4/AES-128) or 32 bytes (AES-256)
	O, U     []byte // owner/user hash (32 bytes for R3/R4, 48 bytes for R6)
	OE, UE   []byte // owner/user key encryption (32 bytes, R6 only)
	Perms    []byte // encrypted permissions (16 bytes, R6 only)
	P        int32  // permission flags
	FileID   []byte // 16-byte file identifier
	// contains filtered or unexported fields
}

Encryptor handles PDF object encryption for a single document.

func NewEncryptor

func NewEncryptor(rev EncryptionRevision, userPassword, ownerPassword string, perms Permission) (*Encryptor, error)

NewEncryptor creates an Encryptor for the given revision and passwords. If ownerPassword is empty, it defaults to userPassword.

func (*Encryptor) BuildEncryptDict

func (e *Encryptor) BuildEncryptDict() *PdfDictionary

BuildEncryptDict returns the /Encrypt dictionary for the trailer.

func (*Encryptor) EncryptBytes

func (e *Encryptor) EncryptBytes(objNum, genNum int, data []byte) ([]byte, error)

EncryptBytes encrypts data for the given indirect object.

func (*Encryptor) EncryptObject

func (e *Encryptor) EncryptObject(obj PdfObject, objNum, genNum int) error

EncryptObject walks a PdfObject tree and encrypts all strings and stream data in place. The /Encrypt dictionary object is skipped.

func (*Encryptor) SetEncryptDictObjNum

func (e *Encryptor) SetEncryptDictObjNum(n int)

SetEncryptDictObjNum records the object number of the /Encrypt dictionary so it can be skipped during the encryption walk.

type ObjStmEntry added in v0.7.0

type ObjStmEntry struct {
	ObjectNumber int
	Object       PdfObject
}

ObjStmEntry is a single object packed into an object stream. Object streams (ISO 32000-1 §7.5.7) carry only direct objects belonging to generation zero, so this struct intentionally records no generation number — the value is implicitly zero. Stream objects are not eligible for inclusion and the builder rejects them.

type ObjStmPlacement added in v0.7.0

type ObjStmPlacement struct {
	ObjectNumber  int // the original object number (gen 0 implied)
	ObjStmObjNum  int // the object number that will be assigned to the containing /ObjStm
	IndexInObjStm int
}

ObjStmPlacement reports where an entry ended up after BuildObjStm: the object number of the containing object stream and the entry's index within that stream. The writer uses this mapping to emit a type-2 cross-reference entry per ISO 32000-1 §7.5.8.3 Table 18.

Index is the index within the object stream's header table (0-based), not a byte offset.

type ObjectType

type ObjectType int

ObjectType enumerates the PDF object types.

const (
	ObjectTypeBoolean    ObjectType = iota
	ObjectTypeNumber                // integer or real
	ObjectTypeString                // literal or hexadecimal
	ObjectTypeName                  // /Name
	ObjectTypeArray                 // [...]
	ObjectTypeDictionary            // << ... >>
	ObjectTypeStream                // dictionary + byte sequence
	ObjectTypeNull                  // null
	ObjectTypeReference             // indirect reference (e.g. 1 0 R)
)

type PdfArray

type PdfArray struct {
	// Elements is the underlying slice of array elements.
	//
	// Deprecated: since v0.7.0, scheduled for removal at v1.0. Use
	// [PdfArray.All], [PdfArray.At], [PdfArray.Len], [PdfArray.Add],
	// [PdfArray.Set], [PdfArray.RemoveAt], and [PdfArray.Replace] so
	// internal representation changes remain invisible to callers.
	Elements []PdfObject
}

PdfArray represents a PDF array object (ISO 32000 §7.3.6). An array is a one-dimensional collection of objects.

func NewPdfArray

func NewPdfArray(elements ...PdfObject) *PdfArray

NewPdfArray creates a new PdfArray containing the given elements. It panics if any element is nil, matching the contract of PdfArray.Add.

func (*PdfArray) Add

func (a *PdfArray) Add(obj PdfObject)

Add appends an object to the array. Panics if obj is nil.

func (*PdfArray) All added in v0.7.0

func (a *PdfArray) All() iter.Seq2[int, PdfObject]

All returns an iterator over (index, element) pairs in insertion order. Using this iterator insulates callers from the underlying representation of PdfArray.Elements.

func (*PdfArray) At added in v0.7.0

func (a *PdfArray) At(i int) PdfObject

At returns the element at index i. It panics if i is out of range.

func (*PdfArray) Len

func (a *PdfArray) Len() int

Len returns the number of elements.

func (*PdfArray) RemoveAt added in v0.7.0

func (a *PdfArray) RemoveAt(i int) PdfObject

RemoveAt removes and returns the element at index i, shifting later elements down. It panics if i is out of range.

func (*PdfArray) Replace added in v0.7.0

func (a *PdfArray) Replace(elements ...PdfObject)

Replace discards all current elements and sets the array content to the given sequence. It panics if any element is nil.

func (*PdfArray) Set added in v0.7.0

func (a *PdfArray) Set(i int, obj PdfObject)

Set replaces the element at index i with obj. It panics if i is out of range or if obj is nil, matching the contract of PdfArray.Add.

func (*PdfArray) Type

func (a *PdfArray) Type() ObjectType

Type returns ObjectTypeArray.

func (*PdfArray) WriteTo

func (a *PdfArray) WriteTo(w io.Writer) (int64, error)

WriteTo serializes the array in PDF syntax to w.

type PdfBoolean

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

PdfBoolean represents a PDF boolean value (ISO 32000 §7.3.2). The underlying value is immutable after construction; use NewPdfBoolean to create new instances and PdfBoolean.Bool to read them.

func NewPdfBoolean

func NewPdfBoolean(v bool) *PdfBoolean

NewPdfBoolean returns the shared PdfBoolean instance for the given value. Because PdfBoolean is immutable, singletons are safe and avoid allocation.

func (*PdfBoolean) Bool added in v0.7.0

func (b *PdfBoolean) Bool() bool

Bool returns the underlying boolean value.

func (*PdfBoolean) Type

func (b *PdfBoolean) Type() ObjectType

Type returns ObjectTypeBoolean.

func (*PdfBoolean) WriteTo

func (b *PdfBoolean) WriteTo(w io.Writer) (int64, error)

WriteTo serializes the boolean as "true" or "false" to w.

type PdfDictionary

type PdfDictionary struct {
	// Entries is the ordered list of key-value pairs.
	//
	// Deprecated: since v0.7.0, scheduled for removal at v1.0. Use
	// [PdfDictionary.All], [PdfDictionary.Get], [PdfDictionary.Set],
	// and [PdfDictionary.Remove] so the internal index stays consistent
	// with mutations.
	Entries []DictEntry
	// contains filtered or unexported fields
}

PdfDictionary represents a PDF dictionary object (ISO 32000 §7.3.7). Keys are PdfName objects; values can be any PdfObject.

Insertion order is preserved to produce deterministic PDF output. A lazily-built map index accelerates key lookups from O(n) to O(1).

func NewPdfDictionary

func NewPdfDictionary() *PdfDictionary

NewPdfDictionary creates a new empty PdfDictionary.

func (*PdfDictionary) All added in v0.7.0

func (d *PdfDictionary) All() iter.Seq2[string, PdfObject]

All returns an iterator over (key, value) pairs in insertion order. Using this iterator insulates callers from the underlying representation of PdfDictionary.Entries.

func (*PdfDictionary) Get

func (d *PdfDictionary) Get(key string) PdfObject

Get retrieves a value by key name. Returns nil if not found.

func (*PdfDictionary) Len added in v0.7.0

func (d *PdfDictionary) Len() int

Len returns the number of entries.

func (*PdfDictionary) Remove

func (d *PdfDictionary) Remove(key string)

Remove deletes an entry by key name. Does nothing if the key does not exist.

func (*PdfDictionary) Set

func (d *PdfDictionary) Set(key string, value PdfObject)

Set adds or updates an entry. If the key already exists, its value is replaced. Panics if value is nil.

func (*PdfDictionary) Type

func (d *PdfDictionary) Type() ObjectType

Type returns ObjectTypeDictionary.

func (*PdfDictionary) WriteTo

func (d *PdfDictionary) WriteTo(w io.Writer) (int64, error)

WriteTo serializes the dictionary in PDF syntax to w.

type PdfIndirectReference

type PdfIndirectReference struct {
	// ObjectNumber is the object number of the referenced indirect object.
	//
	// Deprecated: since v0.7.0, scheduled for removal at v1.0. Use
	// [PdfIndirectReference.Num] for reads and [PdfIndirectReference.SetNum]
	// for writes.
	ObjectNumber int

	// GenerationNumber is the generation number of the referenced object.
	//
	// Deprecated: since v0.7.0, scheduled for removal at v1.0. Use
	// [PdfIndirectReference.Gen] in new code.
	GenerationNumber int
}

PdfIndirectReference represents a PDF indirect reference (ISO 32000 §7.3.10). Written as "objNum genNum R" (e.g., "1 0 R"). Generation numbers are almost always 0 in modern PDFs.

func NewPdfIndirectReference

func NewPdfIndirectReference(objNum, genNum int) *PdfIndirectReference

NewPdfIndirectReference creates a new indirect reference with the given object and generation numbers.

func (*PdfIndirectReference) Gen added in v0.7.0

func (r *PdfIndirectReference) Gen() int

Gen returns the generation number of the referenced object.

func (*PdfIndirectReference) Num added in v0.7.0

func (r *PdfIndirectReference) Num() int

Num returns the object number of the referenced indirect object.

func (*PdfIndirectReference) SetNum added in v0.7.0

func (r *PdfIndirectReference) SetNum(objNum int)

SetNum updates the object number this reference points to. Writer-side passes that renumber objects (e.g., orphan sweep, deduplication) use this in place of mutating the deprecated ObjectNumber field directly.

func (*PdfIndirectReference) Type

func (r *PdfIndirectReference) Type() ObjectType

Type returns ObjectTypeReference.

func (*PdfIndirectReference) WriteTo

func (r *PdfIndirectReference) WriteTo(w io.Writer) (int64, error)

WriteTo serializes the indirect reference as "objNum genNum R" to w.

type PdfName

type PdfName struct {
	Value string // the name without the leading /
}

PdfName represents a PDF name object (ISO 32000 §7.3.5). Names are written with a leading solidus: /Type, /Pages, etc.

func NewPdfName

func NewPdfName(v string) *PdfName

NewPdfName creates a new PdfName with the given value (without the leading solidus).

func (*PdfName) Type

func (n *PdfName) Type() ObjectType

Type returns ObjectTypeName.

func (*PdfName) WriteTo

func (n *PdfName) WriteTo(w io.Writer) (int64, error)

WriteTo serializes the name with a leading solidus to w.

type PdfNull

type PdfNull struct{}

PdfNull represents the PDF null object (ISO 32000 §7.3.9). PdfNull is stateless; all instances are equivalent.

func NewPdfNull

func NewPdfNull() *PdfNull

NewPdfNull returns the shared PdfNull instance. Because PdfNull has no fields, a singleton is safe and avoids allocating on every call.

func (*PdfNull) Type

func (n *PdfNull) Type() ObjectType

Type returns ObjectTypeNull.

func (*PdfNull) WriteTo

func (n *PdfNull) WriteTo(w io.Writer) (int64, error)

WriteTo serializes the null object as "null" to w.

type PdfNumber

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

PdfNumber represents a PDF numeric object — either integer or real (ISO 32000 §7.3.3). It tracks whether the value is integral so that integers serialize without a decimal point.

func NewPdfInteger

func NewPdfInteger(v int) *PdfNumber

NewPdfInteger creates an integer PdfNumber.

func NewPdfReal

func NewPdfReal(v float64) *PdfNumber

NewPdfReal creates a real (floating-point) PdfNumber.

func (*PdfNumber) FloatValue

func (n *PdfNumber) FloatValue() float64

FloatValue returns the float64 value.

func (*PdfNumber) IntValue

func (n *PdfNumber) IntValue() int

IntValue returns the integer value, truncating reals toward zero. NaN and infinite values return 0 so malformed PDFs cannot propagate undefined conversions into the rest of the pipeline.

Note: this method silently truncates real values and can overflow on 32-bit platforms for very large reals. Use PdfNumber.IntValueChecked when you need to distinguish between an integer, a truncated real, and an out-of-range value.

func (*PdfNumber) IntValueChecked added in v0.7.0

func (n *PdfNumber) IntValueChecked() (value int, ok bool)

IntValueChecked returns the integer value and a boolean indicating whether the conversion was exact. ok is false if the underlying value is a real with a fractional part, is NaN or Inf, or overflows the platform int range.

func (*PdfNumber) IsInteger

func (n *PdfNumber) IsInteger() bool

IsInteger reports whether this number was created as an integer.

func (*PdfNumber) Type

func (n *PdfNumber) Type() ObjectType

Type returns ObjectTypeNumber.

func (*PdfNumber) WriteTo

func (n *PdfNumber) WriteTo(w io.Writer) (int64, error)

WriteTo serializes the number as an integer or real to w.

type PdfObject

type PdfObject interface {
	// WriteTo serializes the object in PDF syntax to w.
	WriteTo(w io.Writer) (int64, error)

	// Type returns the object's PDF type.
	Type() ObjectType
}

PdfObject is the interface satisfied by every PDF object type.

type PdfStream

type PdfStream struct {
	Dict *PdfDictionary
	Data []byte
	// contains filtered or unexported fields
}

PdfStream represents a PDF stream object (ISO 32000 §7.3.8). A stream consists of a dictionary followed by a sequence of bytes enclosed between "stream" and "endstream" keywords.

func BuildObjStm added in v0.7.0

func BuildObjStm(entries []ObjStmEntry) (*PdfStream, error)

BuildObjStm assembles an /ObjStm indirect object per ISO 32000-1 §7.5.7 from the supplied entries.

The decoded stream consists of a header — N pairs of "objNum offset" integers, where offset is the byte offset of the corresponding object body relative to /First — followed by the N object bodies in the same order, each rendered with the standard PdfObject.WriteTo. /First is set to the length of the header so the bodies begin at exactly that offset after decompression.

Entries are emitted in the order supplied. Callers that need a canonical layout must sort their entries before calling; the builder does not reorder so that callers retain control over the layout.

The builder rejects:

  • empty entry lists (a /ObjStm must compress at least one object);
  • entries whose object number is <= 0 (object number 0 is the free list head and cannot be assigned to a real object);
  • duplicate object numbers within a single object stream (the parser would resolve only one of them);
  • stream objects (§7.5.7: streams cannot be compressed inside another stream).

FlateDecode is applied via the existing compressed-stream path. /Length is set on serialization. The returned stream's dictionary has /Type, /N, and /First populated; the caller is free to add /Extends or other entries before serialization, but must not overwrite the builder-owned keys.

func BuildXRefStream added in v0.7.0

func BuildXRefStream(subsections []XRefStreamSubsection, size int, extras *PdfDictionary) (*PdfStream, error)

BuildXRefStream assembles a cross-reference stream object per ISO 32000-1 §7.5.8.

subsections describes the entries in object-number order; size is the value of the /Size entry, which must equal one more than the highest object number ever written to the file (§7.5.8.2 Table 17). extras supplies the entries that would otherwise live in the file trailer (/Root, /Info, /Encrypt, /ID, /Prev). The builder owns /Type, /Size, /W, /Index, /Filter, and /Length.

The returned stream is configured with FlateDecode and writes its /Length on serialization. Phase 1 does not apply a PNG predictor (§7.5.8 Table 17 /DecodeParms): predictors save bytes on row-similar payloads but add a clean-room implementation burden, so the trade-off is deferred until the rest of the optimizer is in place.

func NewPdfStream

func NewPdfStream(data []byte) *PdfStream

NewPdfStream creates a stream with the given data (uncompressed). The /Length entry is managed automatically during serialization.

func NewPdfStreamCompressed

func NewPdfStreamCompressed(data []byte) *PdfStream

NewPdfStreamCompressed creates a stream that will be compressed with FlateDecode (zlib) when written. The Data field holds the uncompressed bytes; compression happens during WriteTo.

func (*PdfStream) SetCompress

func (s *PdfStream) SetCompress(enabled bool)

SetCompress enables or disables FlateDecode compression for this stream.

func (*PdfStream) SetCompressLevel added in v0.11.0

func (s *PdfStream) SetCompressLevel(level int)

SetCompressLevel selects the zlib level WriteTo uses when compressing this stream (see compress/zlib level constants, e.g. zlib.BestSpeed, zlib.DefaultCompression, zlib.NoCompression, zlib.HuffmanOnly). It has no effect unless the stream is also set to compress (SetCompress(true) or NewPdfStreamCompressed). Without a call to SetCompressLevel, WriteTo uses zlib.BestCompression, matching historical behavior.

func (*PdfStream) Type

func (s *PdfStream) Type() ObjectType

Type returns ObjectTypeStream.

func (*PdfStream) WillCompress added in v0.7.0

func (s *PdfStream) WillCompress() bool

WillCompress reports whether WriteTo will Flate-compress this stream's payload before serializing. Useful for writer-side passes that want to skip streams the writer is already going to compress at BestCompression.

func (*PdfStream) WriteTo

func (s *PdfStream) WriteTo(w io.Writer) (int64, error)

WriteTo serializes the stream dictionary and data bytes to w.

type PdfString

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

PdfString represents a PDF string object (ISO 32000 §7.3.4). PDF supports two notations: literal strings in parentheses and hexadecimal strings in angle brackets.

Use NewPdfLiteralString or NewPdfHexString to construct a byte string, NewPdfTextString for a human-readable *text string* (a title, author, bookmark label, annotation contents, ...), and PdfString.Text / PdfString.TextString / PdfString.IsHex to read. The underlying fields are unexported; encryption mutates them in-place from within the core package.

func NewPdfHexString

func NewPdfHexString(v string) *PdfString

NewPdfHexString creates a hexadecimal string: <hex>.

func NewPdfLiteralString

func NewPdfLiteralString(v string) *PdfString

NewPdfLiteralString creates a literal string: (value).

func NewPdfTextString added in v0.11.0

func NewPdfTextString(v string) *PdfString

NewPdfTextString creates a PDF *text string* (ISO 32000-1 §7.9.2.2) holding human-readable Unicode text: an outline title, an Info entry, annotation contents, alt text, a form field name, and so on.

A text string must be either PDFDocEncoding or UTF-16BE prefixed with the byte-order mark FE FF. Writing a Go string's UTF-8 bytes directly is wrong: a reader decodes them as PDFDocEncoding and "ó" (C3 B3) shows as "ó". This constructor keeps ASCII text as a plain literal string (see IsPDFDocASCII), which is valid PDFDocEncoding and stays readable in the file, and encodes anything else as UTF-16BE with the BOM, written in hexadecimal notation so the embedded NUL and delimiter bytes need no escaping.

Use NewPdfLiteralString for byte strings that are not text strings, such as /URI, dates, named destinations and file specifications (/F).

func (*PdfString) IsHex added in v0.7.0

func (s *PdfString) IsHex() bool

IsHex reports whether the string will be serialized in hexadecimal notation (<hex>) rather than literal notation ((text)).

func (*PdfString) Text added in v0.7.0

func (s *PdfString) Text() string

Text returns the raw string value, without PDF escaping. For literal strings this is the unescaped content; for hex strings it is the decoded bytes interpreted as a string. For a text string written by NewPdfTextString this may be UTF-16BE bytes; use PdfString.TextString to get the decoded Unicode text.

func (*PdfString) TextString added in v0.11.0

func (s *PdfString) TextString() string

TextString decodes the value as a PDF text string (ISO 32000-1 §7.9.2.2): a UTF-16BE string with the byte-order mark FE FF is decoded to UTF-8, a UTF-8 BOM (ISO 32000-2) is stripped, and anything else is decoded as PDFDocEncoding. See DecodeTextString.

func (*PdfString) Type

func (s *PdfString) Type() ObjectType

Type returns ObjectTypeString.

func (*PdfString) WriteTo

func (s *PdfString) WriteTo(w io.Writer) (int64, error)

WriteTo serializes the string in literal or hexadecimal notation to w.

type Permission

type Permission uint32

Permission flags for PDF document encryption (ISO 32000 Table 22). Combine with | to grant multiple permissions.

const (
	PermPrint         Permission = 1 << 2  // bit 3: print
	PermModify        Permission = 1 << 3  // bit 4: modify contents
	PermExtract       Permission = 1 << 4  // bit 5: copy/extract text and graphics
	PermAnnotate      Permission = 1 << 5  // bit 6: add/modify annotations, fill forms
	PermFillForms     Permission = 1 << 8  // bit 9: fill existing form fields
	PermExtractAccess Permission = 1 << 9  // bit 10: extract for accessibility
	PermAssemble      Permission = 1 << 10 // bit 11: assemble (insert, rotate, delete pages)
	PermPrintHigh     Permission = 1 << 11 // bit 12: high-quality print

	// PermAll grants all permissions.
	PermAll = PermPrint | PermModify | PermExtract | PermAnnotate |
		PermFillForms | PermExtractAccess | PermAssemble | PermPrintHigh
)

type StringEncoding

type StringEncoding int

StringEncoding controls how a PdfString is serialized.

const (
	StringLiteral     StringEncoding = iota // (Hello World)
	StringHexadecimal                       // <48656C6C6F>
)

type XRefEntryType added in v0.7.0

type XRefEntryType uint8

XRefEntryType is the value of the first field of a cross-reference stream entry (ISO 32000-1 §7.5.8.3 Table 18).

const (
	// XRefEntryFree marks an entry as a free object (linked-list head/body).
	// Field 2 is the object number of the next free object; field 3 is the
	// generation number to use if the slot is reused. The traditional xref
	// table uses 65535 as the head sentinel; xref streams use the same
	// convention (§7.5.8.3).
	XRefEntryFree XRefEntryType = 0

	// XRefEntryInUse marks an entry as an in-use object stored at a byte
	// offset from the start of the file. Field 2 is the offset; field 3 is
	// the generation number.
	XRefEntryInUse XRefEntryType = 1

	// XRefEntryCompressed marks an entry as an in-use object stored inside
	// an object stream (§7.5.7). Field 2 is the object number of the
	// containing object stream; field 3 is the index of the object within
	// that stream. The generation number is implicitly zero.
	XRefEntryCompressed XRefEntryType = 2
)

type XRefStreamEntry added in v0.7.0

type XRefStreamEntry struct {
	Type   XRefEntryType
	Field2 uint64
	Field3 uint64
}

XRefStreamEntry is one row of a cross-reference stream's binary payload. It is intentionally an unencoded value type — the byte layout is decided at encode time once all entries are known and the field widths are chosen.

type XRefStreamSubsection added in v0.7.0

type XRefStreamSubsection struct {
	First   int
	Entries []XRefStreamEntry
}

XRefStreamSubsection is one contiguous run of cross-reference stream entries describing object numbers First, First+1, ..., First+len(Entries)-1.

A complete xref stream is built from one or more subsections. The common case is a single subsection starting at 0 and covering every object in the file; that is what BuildXRefStream emits when given a single [0, N] subsection. Sparse subsections are supported because incremental updates need them, even though phase 1 of the optimizer does not.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL