pdf

package
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Jul 5, 2026 License: AGPL-3.0 Imports: 20 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	PDFAPartRe = regexp.MustCompile(`pdfaid:part\s*=\s*"([^"]*)"|<pdfaid:part>\s*([^<\s]+)\s*</pdfaid:part>`)
	PDFAConfRe = regexp.MustCompile(`pdfaid:conformance\s*=\s*"([^"]*)"|<pdfaid:conformance>\s*([^<\s]+)\s*</pdfaid:conformance>`)
)

PDFAPartRe and PDFAConfRe extract the PDF/A part and conformance level a document's XMP metadata claims (6.7.11 pdfaid namespace), shared by ClaimedConformance and the 6.7.11 verifier.

View Source
var (
	ErrNoXMPMetadata        = errors.New("document catalog lacks a Metadata entry")
	ErrXMPMetadataNotStream = errors.New("document Metadata is not a metadata stream")
)

ErrNoXMPMetadata and ErrXMPMetadataNotStream are returned by RawXMP when the document catalog has no usable Metadata stream at all (as opposed to one that exists but fails to decode).

View Source
var Checks checksRegistry

Functions

func AbsInt

func AbsInt(x int) int

AbsInt returns the absolute value of x.

func CMYKToRGB

func CMYKToRGB(comps []float64) (r, g, b float64)

cmykToRGB applies the PDF specification's default (non-ICC) CMYK -> RGB approximation: R = 1-min(1,C+K), and likewise for G/B.

func ClampInt

func ClampInt(v, lo, hi int) int

ClampInt clamps v to the inclusive range [lo, hi].

func ClauseLess

func ClauseLess(a, b string) bool

ClauseLess compares two dotted clause numbers ("6.2.9", "6.2.10") segment by segment so they sort numerically rather than lexicographically.

func ColorSpaceComponents

func ColorSpaceComponents(cs PDFValue) int

colorSpaceComponents returns the number of colour components a (non- Indexed) base colour space takes.

func DecodeASCII85

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

DecodeASCII85 decodes an ASCII85Decode stream.

func DecodeASCIIHex

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

decodeASCIIHex decodes an ASCIIHexDecode stream: pairs of hex digits, terminated by '>'. Whitespace between pairs is ignored.

func DecodeCCITT

func DecodeCCITT(data []byte, p CCITTParams) ([]byte, error)

decodeCCITT decodes a CCITT-encoded bitstream into packed 1-bit-per-pixel Rows (row-padded to a byte boundary), with each pixel's bit set per the BlackIs1 convention. K<0 is pure 2D (Group 4), K==0 pure 1D (Group 3 1D), K>0 mixed (Group 3 2D).

func DecodeInfoTextString added in v0.4.0

func DecodeInfoTextString(v PDFValue) string

DecodeInfoTextString decodes a PDFString or PDFHexString Info-dictionary value to Unicode: the bytes are interpreted as a PDF text string (UTF-16BE with BOM, otherwise PDFDocEncoding). Returns "" for any other value type.

func DecodeLZW

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

decodeLZW decodes a PDF LZWDecode stream into its uncompressed bytes.

func DecodePDFHexStringBytes

func DecodePDFHexStringBytes(s string) []byte

DecodePDFHexStringBytes decodes a hex string's digit characters into bytes, ignoring whitespace and padding a trailing odd nibble with 0.

func DecodePDFName

func DecodePDFName(s string) []byte

DecodePDFName decodes PDF name #XX escape sequences and returns the resulting byte slice. Unescaped bytes are returned as-is.

func DecodePDFTextString

func DecodePDFTextString(raw []byte) string

DecodePDFTextString decodes a PDF text string's bytes per 7.9.2.2: a leading 0xFE 0xFF BOM means the rest is UTF-16BE; otherwise bytes are PDFDocEncoding.

func DecodeStream

func DecodeStream(dict PDFDict) ([]byte, error)

decodeStream returns the decoded bytes of a stream dictionary, applying FlateDecode, ASCIIHexDecode, and ASCII85Decode filters as needed.

func DictInt

func DictInt(dict PDFDict, key string, def int) int

dictInt reads an integer-valued entry from dict, returning def if absent or not an integer.

func EncodePDFLiteralString added in v0.5.0

func EncodePDFLiteralString(s string) string

EncodePDFLiteralString escapes a decoded string's bytes for serialization between "(" and ")": backslash, parentheses, and EOL bytes are escaped so a conforming reader recovers the exact original bytes.

func EqualPDFValue

func EqualPDFValue(a, b PDFValue) bool

func FilterNames

func FilterNames(filter PDFValue) []string

filterNames returns the list of filter names applied to a stream.

func FirstRegexpGroup

func FirstRegexpGroup(re *regexp.Regexp, s string) (string, bool)

FirstRegexpGroup returns the first non-empty capture group re matches in s.

func FloatArray

func FloatArray(v PDFValue) ([]float64, error)

floatArray converts a PDFArray of PDFInteger/PDFReal values to []float64.

func InflateZlib

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

inflateZlib decodes a zlib (FlateDecode/Fl) stream using a pooled decoder.

func IsHexDigit

func IsHexDigit(ch byte) bool

func IsWhitespace

func IsWhitespace(ch byte) bool

func PDFNumberToFloat

func PDFNumberToFloat(v PDFValue) (float64, bool)

pdfNumberToFloat extracts a float64 from a PDFInteger/PDFReal value, the float counterpart of pdfNumberToInt.

func PDFNumberToInt

func PDFNumberToInt(v PDFValue) (int, bool)

PDFNumberToInt extracts an int from a PDFInteger/PDFReal value, the repeated PDF-number-operand pattern used throughout font and image checks.

func ReadBits

func ReadBits(data []byte, bitOffset, n int) uint64

readBits reads an n-bit (n<=32) big-endian unsigned field starting at the given bit offset, the sample-unpacking primitive shared by Type 0 functions and image sample decoding.

func ReplayOps added in v0.5.0

func ReplayOps(ops []ScannedOp, fn func(op string, operands []PDFValue))

ReplayOps invokes fn for each entry in ops in order, the same callback shape as ContentScanner.Scan, so a cached token list (see Reader.ScanStreamCached) can stand in for re-lexing an unchanged stream.

func ResolveColor

func ResolveColor(cs PDFValue, comps []float64, resources PDFDict) (r, g, b float64)

ResolveColor converts comps (component values in the colour space cs) to an RGB triple in [0,1]. resources supplies the /ColorSpace dictionary used to look up named (non-device) colour spaces referenced by name.

This mirrors the same component-count device-model approximation deviceColourModel (checks_colour.go) already uses elsewhere in this codebase: no ICC profile is actually applied, CalGray/CalRGB are treated as their device equivalents, and an unrecognized or unsupported space (e.g. Pattern) falls back to mid-gray rather than failing.

func UndoPNGPredictor

func UndoPNGPredictor(data []byte, columns, colors, bpc int) ([]byte, error)

undoPNGPredictor reverses the PNG-style per-row predictor (ISO 32000-1 7.4.4.4 / RFC 2083 §6): each output row is prefixed by a one-byte filter type (None/Sub/Up/Average/Paeth) describing how it was encoded relative to the previous row and to already-decoded bytes within the same row.

func UndoTIFFPredictor

func UndoTIFFPredictor(data []byte, columns, colors, bpc int) ([]byte, error)

undoTIFFPredictor reverses TIFF predictor 2 (horizontal differencing), applied per sample within each row.

func ValuePointer

func ValuePointer(v PDFValue) uintptr

ValuePointer returns the identity pointer of a PDFDict's Entries map or a PDFArray's backing slice, used to detect cycles and dedupe visits when walking the object graph.

Types

type CCITTParams

type CCITTParams struct {
	Columns   int
	Rows      int
	K         int
	ByteAlign bool
	BlackIs1  bool
}

CCITTParams holds the CCITTFaxDecode parameters that drive decoding.

type Check

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

Check is a named, selectable PDF/A validation rule, identified by a (clause, subclause) pair and grouped into categories under Checks.

func AllChecks

func AllChecks() []Check

AllChecks returns every registered check in catalog order.

func CheckByClause

func CheckByClause(clause string, subclause int) (c Check, ok bool)

CheckByClause looks up the registered check for a specific (clause, subclause) pair, e.g. CheckByClause("6.3.4", 1). ok is false if no check is registered for that pair.

func CheckByName

func CheckByName(name string) (c Check, ok bool)

CheckByName looks up a registered check by its CamelCase identifier (e.g. "ObjectFraming"), used to map a pdf.Reader's parse-time StructError diagnostics -- which only carry that name, to avoid this package's check registry being a dependency of the pdf package -- back to a

func ChecksForClause

func ChecksForClause(clause string) []Check

ChecksForClause returns every registered check under the given clause (e.g. "6.3.4"), in catalog order.

func (Check) Clause

func (c Check) Clause() string

Clause returns the PDF/A-1 specification clause number (e.g. "6.1.2").

func (Check) Description

func (c Check) Description() string

Description returns a human-readable summary of what this check enforces.

func (Check) ID

func (c Check) ID() int

ID returns this check's unique sequential registration ID, used by Profile as a compact key for its enabled-check set.

func (Check) Name

func (c Check) Name() string

Name returns the CamelCase identifier of this check (e.g. "ImageWithSoftMask").

func (Check) Subclause

func (c Check) Subclause() int

Subclause returns the internal sub-rule index within the clause.

type ContentScanner

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

ContentScanner walks a decoded content stream, exposing each operator together with its operands. It reuses the object Lexer for tokenising; bare operators arrive as keyword tokens.

func NewContentScanner

func NewContentScanner(data []byte) *ContentScanner

func (*ContentScanner) Scan

func (cs *ContentScanner) Scan(fn func(op string, operands []PDFValue))

scan iterates the content stream, invoking fn for each operator with the operands collected since the previous operator.

type Cursor

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

func NewCursor

func NewCursor(data []byte) *Cursor

func (*Cursor) ReadLine

func (c *Cursor) ReadLine() (string, bool)

type FileResult added in v0.3.0

type FileResult[T any] struct {
	Path   string
	Result T
	Err    error
}

FileResult is one path's outcome from a batch operation.

type Function

type Function interface {
	Eval(in []float64) []float64
}

Function evaluates a PDF Function (Types 0, 2, 3, 4; ISO 32000-1 §7.10) mapping m input values to n output values.

func ParseFunction

func ParseFunction(v PDFValue) (Function, error)

ParseFunction builds a Function from a resolved Function Dictionary or Stream (v must already be dereferenced, as everything in this package's graph is after ResolveGraph).

type InlineImageRaw

type InlineImageRaw struct {
	Bytes []byte
	Data  []byte
}

InlineImageRaw carries an inline image's verbatim "BI...EI" byte span, appended as the last element of the "INLINEIMAGE" pseudo-operator's operands so writeContentStream can re-emit it unchanged. Existing consumers that scan operands in (key, value) pairs are unaffected: the trailing odd element falls outside every "i+1 < len(operands)" loop.

Data holds just the image bytes between ID's separator and EI's separator (excluding both), for a fixer that needs to inspect or replace them (e.g. re-encoding LZW to Flate) without textually searching Bytes for "ID"/"EI" -- which would be unsafe, since arbitrary binary image data can itself contain those bytes. buildInlineImageBytes (content_writer.go) is the inverse: it rebuilds a fresh Bytes span from edited params and Data.

type LevelType

type LevelType string
const (
	Undefined LevelType = "undefined"
	A_1B      LevelType = "A-1b"
)

type Lexer

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

Lexer holds the state of the current chunk being parsed. data is non-nil when lexing a []byte directly (fast path); reader is used for the io.Reader fallback (trailer parsing, object streams).

func NewLexer

func NewLexer(r io.Reader) *Lexer

NewLexer creates a lexer for a specific chunk of data.

func NewLexerAt

func NewLexerAt(r io.Reader, offset int64) *Lexer

func NewLexerBytes added in v0.5.0

func NewLexerBytes(data []byte, startPos int64) *Lexer

NewLexerBytes creates a fast lexer that indexes data starting at startPos.

func (*Lexer) NextToken

func (l *Lexer) NextToken() Token

NextToken returns the next distinct token from the stream.

func (*Lexer) Release

func (l *Lexer) Release()

Release returns l's underlying bufio.Reader to the pool for reuse by a later Lexer. Callers that construct a short-lived Lexer (the common case) should defer Release once the lexer is no longer needed.

func (*Lexer) UnreadToken

func (l *Lexer) UnreadToken(t Token)

type PDFArray

type PDFArray []PDFValue

type PDFBoolean

type PDFBoolean bool

type PDFDict

type PDFDict struct {
	Entries   map[string]PDFValue
	HasStream bool
	// RawStream holds the undecoded stream bytes. The slice may alias a
	// read-only memory-map; always assign a new slice, never mutate in place.
	RawStream []byte
}

func NewPDFDict

func NewPDFDict() PDFDict

func StreamDecodeParms

func StreamDecodeParms(dict PDFDict) PDFDict

streamDecodeParms returns the /DecodeParms (or abbreviated /DP) dictionary associated with dict's stream, or a zero-value dict if none is present. Handles both the common single-dict form and the per-filter array form, preferring the last array entry (the parameters for the last-applied filter), which covers the single-filter case used by cross-reference and object streams.

type PDFError

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

func NewError

func NewError(c Check, errs []error, page int, ref *PDFRef) PDFError

NewError constructs a PDFError reporting a violation of c, found on page (0 for document-level) and optionally tied to a specific indirect object.

func (PDFError) Check

func (e PDFError) Check() Check

Check returns the registered Check this violation corresponds to.

func (PDFError) Error

func (e PDFError) Error() string

func (PDFError) IsDocumentLevel

func (e PDFError) IsDocumentLevel() bool

IsDocumentLevel reports whether this violation applies to the document as a whole rather than to a specific page.

func (PDFError) Messages

func (e PDFError) Messages() []string

Messages returns the underlying error messages for this violation.

func (PDFError) ObjectRef

func (e PDFError) ObjectRef() (ref PDFRef, ok bool)

ObjectRef returns the indirect object this violation was reported against, and whether one was recorded. Not every violation is tied to a single object (e.g. file-header or trailer issues), in which case ok is false.

func (PDFError) Page

func (e PDFError) Page() int

Page returns the 1-based page number this violation was found on, or 0 if the violation is document-level (see IsDocumentLevel).

func (PDFError) String

func (e PDFError) String() string

type PDFHexString

type PDFHexString struct{ Value string }

type PDFInteger

type PDFInteger int

type PDFName

type PDFName struct{ Value string }

type PDFReal

type PDFReal float32

type PDFRef

type PDFRef struct {
	ObjNum int
	GenNum int
}

type PDFString

type PDFString struct{ Value string }

type PDFValue

type PDFValue any

func LookupNamedColorSpace

func LookupNamedColorSpace(name string, resources PDFDict) (PDFValue, bool)

type Profile

type Profile struct {
	Level LevelType

	// SkipUnreachableXObjects, when true, suppresses checks on Form XObjects
	// never invoked via Do from a reachable content stream. ISO 19005-1
	// (6.2.3.3, 6.2.10) applies to every Form XObject, so Legacy_1B keeps this
	// false; PDFA_1B sets it true to match veraPDF's lenient interpretation.
	SkipUnreachableXObjects bool

	// SkipUnusedSimpleFonts, when true, only reports 6.3.4 (SimpleNotEmbedded)
	// for simple fonts actually shown in content. Fonts in AcroForm /DR that
	// are never drawn are silently ignored, matching veraPDF's interpretation.
	// Legacy_1B keeps this false so every referenced non-embedded font is flagged.
	SkipUnusedSimpleFonts bool
	// contains filtered or unexported fields
}

Profile is a mutable set of enabled PDF/A checks for a conformance level, used by VerifyProfile. Mutators (Clear, AddCheck, RemoveCheck) return a new *Profile, leaving the receiver unchanged.

var Legacy_1B *Profile

Legacy_1B is the strict, fully spec-literal PDF/A-1b profile: every check enabled, every Form XObject checked regardless of reachability. Matches the Isartor suite's interpretation, which is stricter than veraPDF's in places.

var PDFA_1B *Profile

PDFA_1B is the default PDF/A-1b profile, tuned to match veraPDF's interpretation of the spec. Used by Verify(A_1B).

func NewFullProfile

func NewFullProfile(level LevelType) *Profile

func NewProfile

func NewProfile(level LevelType) *Profile

NewProfile returns an empty profile for the given conformance level.

func (*Profile) AddCheck

func (p *Profile) AddCheck(checks ...Check) *Profile

AddCheck returns a new profile with the given checks added to the enabled set.

func (*Profile) Allows

func (p *Profile) Allows(clause string, subclause int) bool

func (*Profile) Checks

func (p *Profile) Checks() []Check

Checks returns the list of currently enabled checks in catalog order.

func (*Profile) Clear

func (p *Profile) Clear() *Profile

Clear returns a new profile with the same conformance level but no checks enabled. Behavioral flags (SkipUnreachableXObjects, SkipUnusedSimpleFonts) are preserved.

func (*Profile) Clone

func (p *Profile) Clone() *Profile

func (*Profile) Has

func (p *Profile) Has(c Check) bool

Has reports whether check c is currently enabled in this profile.

func (*Profile) RemoveCheck

func (p *Profile) RemoveCheck(checks ...Check) *Profile

RemoveCheck returns a new profile with the given checks removed from the enabled set.

func (*Profile) String

func (p *Profile) String() string

String returns a human-readable summary of the profile.

type Reader

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

Reader parses a PDF file's structure (header, xref, trailer) and resolves its indirect object graph, caching decoded objects and object streams. Validation lives above this package; Reader only records the structural parse diagnostics (see PDFError) it discovers as a side effect of reading -- e.g. malformed stream framing -- for that layer to interpret.

func NewRawReader

func NewRawReader(file interface {
	io.Reader
	io.ReaderAt
	io.Seeker
	io.Closer
}, trailer PDFDict, size int64, xrefOffset int64) *Reader

NewRawReader builds a Reader directly from already-known structural state, bypassing Open/newReader's normal parse pipeline. It exists for white-box tests in other internal packages (verify) that drive Reader-derived behavior against a specific -- often deliberately malformed -- structure without a real file round-trip; production code should use Open/OpenBytes.

func Open

func Open(path string) (*Reader, error)

Open initializes the PDF document at path.

func OpenBytes

func OpenBytes(data []byte) (*Reader, error)

OpenBytes initializes a Reader from an in-memory PDF, parsing the same way Open does but without touching disk -- used to re-verify freshly-written bytes during conversion.

func (*Reader) AdoptStreamCaches added in v0.5.0

func (d *Reader) AdoptStreamCaches(src *Reader)

AdoptStreamCaches shares src's decoded-stream and token caches with d. Sound because StreamKey identifies RawStream bytes by pointer identity and both Readers are seeded with the same in-memory graph.

func (*Reader) BuildPageIndex

func (d *Reader) BuildPageIndex(graph PDFValue) (map[int]int, error)

func (*Reader) ClaimedConformance

func (d *Reader) ClaimedConformance() (part, conformance string, err error)

ClaimedConformance returns the PDF/A part and conformance level the document's XMP metadata claims (e.g. "1", "B"), read from the pdfaid namespace. This reflects what the file claims, not whether it actually validates — use Verify or IsPDFA to check actual compliance.

func (*Reader) Close

func (d *Reader) Close() error

Close releases all resources held by the Reader.

func (*Reader) DecodeStreamCached added in v0.5.0

func (d *Reader) DecodeStreamCached(dict PDFDict) ([]byte, error)

DecodeStreamCached decodes dict's stream, memoizing the result by content identity (StreamKeyOf) on the Reader so callers sharing one Reader across multiple verify passes never re-inflate an unchanged stream.

func (*Reader) DecodeStreamCachedConcurrent added in v0.5.0

func (d *Reader) DecodeStreamCachedConcurrent(dict PDFDict) ([]byte, error)

DecodeStreamCachedConcurrent is DecodeStreamCached for concurrent callers: map access is locked, inflation happens outside the lock (a racing miss may decode a stream twice; results are identical). Never mix with the unlocked DecodeStreamCached concurrently.

func (*Reader) EffectiveTrailer

func (d *Reader) EffectiveTrailer() PDFDict

EffectiveTrailer returns d.trailer, or d.firstPageTrailer for linearized PDFs whose overflow trailer lacks /Root.

func (*Reader) GetMetadata

func (d *Reader) GetMetadata() (map[string]string, error)

GetMetadata extracts info from the Info dictionary.

func (*Reader) GetPageCount

func (d *Reader) GetPageCount() (int, error)

GetPageCount retrieves the page count.

func (*Reader) GetVersion

func (d *Reader) GetVersion() (string, error)

GetVersion extracts the PDF version from the Reader header

func (*Reader) PDFStart

func (d *Reader) PDFStart() int64

PDFStart returns the byte offset of the "%PDF-" header, non-zero when the file begins with garbage bytes before it (6.1.2).

func (*Reader) ParseXRefSectionAt

func (d *Reader) ParseXRefSectionAt(offset int64, fillIn bool) (PDFDict, error)

ParseXRefSectionAt parses the xref table and trailer dict at offset. If fillIn is true, only entries not already in d.xrefTable are added, preserving newer revisions.

func (*Reader) RawXMP

func (d *Reader) RawXMP() (data []byte, meta PDFDict, err error)

RawXMP resolves the document's Metadata stream (Root/Metadata) and returns its decoded XMP packet bytes, normalised to UTF-8, along with the metadata stream's own dictionary (so callers can inspect entries like Filter). meta is returned even on a decode error, but is zero-valued if no Metadata stream exists at all (ErrNoXMPMetadata / ErrXMPMetadataNotStream).

func (*Reader) ReadAt

func (d *Reader) ReadAt(p []byte, off int64) (int, error)

ReadAt reads len(p) bytes from the underlying file source at offset off, for validation that inspects raw bytes directly (e.g. header/trailer framing).

func (*Reader) ResolveGraph

func (d *Reader) ResolveGraph() (PDFValue, error)

ResolveGraph resolves the PDF object graph, starting from the effective trailer (firstPageTrailer if set, else trailer).

func (*Reader) ResolveGraphByPath

func (d *Reader) ResolveGraphByPath(path []string) (PDFValue, error)

ResolveGraphByPath resolves the PDF object graph by path, starting from the effective trailer (firstPageTrailer if set, else trailer).

func (*Reader) ResolveObject

func (d *Reader) ResolveObject(obj PDFValue) (PDFValue, error)

func (*Reader) ResolveReference

func (d *Reader) ResolveReference(ref PDFRef) (PDFValue, error)

ResolveReference resolves an indirect reference to its object, parsing it from disk at most once per object number.

func (*Reader) ScanStreamCached added in v0.5.0

func (d *Reader) ScanStreamCached(dict PDFDict) ([]ScannedOp, error)

ScanStreamCached decodes and tokenizes dict's content stream, memoizing the token list by content identity (StreamKeyOf) alongside DecodeStreamCached's decoded-bytes cache, so callers sharing one Reader across multiple verify passes tokenize each unchanged stream at most once.

func (*Reader) SeedResolvedGraph added in v0.5.0

func (d *Reader) SeedResolvedGraph(graph PDFDict, objs map[int]PDFValue)

SeedResolvedGraph pre-populates the Reader with an already-resolved graph and object cache.

func (*Reader) Size

func (d *Reader) Size() int64

Size returns the total size of the underlying file source in bytes.

func (*Reader) StructErrors

func (d *Reader) StructErrors() []PDFError

StructErrors returns the structural parse diagnostics recorded so far.

func (*Reader) Trailer

func (d *Reader) Trailer() PDFDict

Trailer returns the document's main trailer dictionary, as parsed -- use EffectiveTrailer for the one that actually carries /Root on linearized PDFs.

func (*Reader) XMPMetadata

func (d *Reader) XMPMetadata() ([]byte, error)

XMPMetadata returns the document's raw XMP metadata packet (Root/Metadata), decoded and normalised to UTF-8. It returns an error if the document has no XMP metadata stream, regardless of whether the document otherwise validates as PDF/A.

func (*Reader) XRefOffset

func (d *Reader) XRefOffset() int64

XRefOffset returns the byte offset of the main cross-reference section, as recorded by the trailer's startxref.

func (*Reader) XRefTable

func (d *Reader) XRefTable() map[int]int64

XRefTable returns the object number -> byte offset map built while parsing the cross-reference table(s).

type Result

type Result struct {
	Type   LevelType
	Valid  bool
	Issues []PDFError
}

func (Result) Checks

func (r Result) Checks() []Check

Checks returns the distinct Checks violated in r.Issues, sorted by clause in numeric (dotted-segment) order, e.g. "6.2.9" before "6.2.10", then by subclause.

func (Result) Count

func (r Result) Count() int

Count returns the number of issues found.

func (Result) IssuesByCheck

func (r Result) IssuesByCheck() map[Check][]PDFError

IssuesByCheck groups r.Issues by their violated

func (Result) IssuesForCheck

func (r Result) IssuesForCheck(c Check) []PDFError

IssuesForCheck returns the issues that correspond to the given registered

func (Result) IssuesOnPage

func (r Result) IssuesOnPage(page int) []PDFError

IssuesOnPage returns the issues found on the given 1-based page number. Pass 0 to get document-level issues (see PDFError.IsDocumentLevel).

func (Result) Summary

func (r Result) Summary() string

Summary returns a human-readable multi-line report: a validity line followed by one line per violated Check with its issue count, in clause order.

type ScannedOp added in v0.5.0

type ScannedOp struct {
	Op       string
	Operands []PDFValue
}

ScannedOp is one content-stream operator paired with the operands collected before it, as an owned (non-aliasing) snapshot of what ContentScanner.Scan reports -- see TokenizeContent.

func TokenizeContent added in v0.5.0

func TokenizeContent(data []byte) []ScannedOp

TokenizeContent scans data once and returns every operator with its operands as an owned, replayable list. ContentScanner.Scan reuses one internal stack slice across operator callbacks, so operands are copied out here to remain valid after Scan returns (the PDFValues themselves, e.g. a TJ array, are still shared by reference -- consumers only read them).

type StreamKey added in v0.5.0

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

StreamKey identifies a stream's raw (undecoded) bytes by content identity: the RawStream slice's data pointer and length. A fixer that rewrites a stream always assigns a fresh RawStream slice (SetStreamFlate et al.), so keying a decode cache on StreamKey makes invalidation automatic -- an unchanged stream keeps hitting, a rewritten one always misses.

func StreamKeyOf added in v0.5.0

func StreamKeyOf(dict PDFDict) (StreamKey, bool)

StreamKeyOf returns dict's cache key and whether it is cacheable. Streams with no bytes (nil/empty RawStream) are not cacheable, since there is no address to key on and decoding them is trivial anyway.

type Token

type Token struct {
	Type  TokenType
	Value string
	Int   int64
	Num   float64
}

Token represents a distinct piece of syntax from the PDF. Number tokens carry their parsed payload in Int/Num with Value left ""; Value holds the raw text only for malformed numbers (see IntValue/RealValue).

func (Token) IntValue added in v0.5.0

func (t Token) IntValue() int

IntValue returns t's integer payload, re-parsing Value only for the rare malformed-number token (matching the legacy Atoi-error-to-zero behavior).

func (Token) RealValue added in v0.5.0

func (t Token) RealValue() (float64, error)

RealValue returns t's real payload, mirroring the legacy parse error for malformed reals.

type TokenType

type TokenType int
const (
	TokenError TokenType = iota
	TokenEOF
	TokenBoolean
	TokenInteger
	TokenReal
	TokenString
	TokenHexString
	TokenName
	TokenKeyword
	TokenArrayStart
	TokenArrayEnd
	TokenDictStart
	TokenDictEnd
	TokenObjectStart
	TokenObjectEnd
	TokenStreamStart
	TokenStreamEnd
)

Jump to

Keyboard shortcuts

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