Documentation
¶
Index ¶
- Variables
- func AbsInt(x int) int
- func CMYKToRGB(comps []float64) (r, g, b float64)
- func ClampInt(v, lo, hi int) int
- func ClauseLess(a, b string) bool
- func ColorSpaceComponents(cs PDFValue) int
- func DecodeASCII85(data []byte) ([]byte, error)
- func DecodeASCIIHex(data []byte) ([]byte, error)
- func DecodeCCITT(data []byte, p CCITTParams) ([]byte, error)
- func DecodeInfoTextString(v PDFValue) string
- func DecodeLZW(data []byte) ([]byte, error)
- func DecodePDFHexStringBytes(s string) []byte
- func DecodePDFName(s string) []byte
- func DecodePDFTextString(raw []byte) string
- func DecodeStream(dict PDFDict) ([]byte, error)
- func DictInt(dict PDFDict, key string, def int) int
- func EncodePDFLiteralString(s string) string
- func EqualPDFValue(a, b PDFValue) bool
- func FilterNames(filter PDFValue) []string
- func FirstRegexpGroup(re *regexp.Regexp, s string) (string, bool)
- func FloatArray(v PDFValue) ([]float64, error)
- func InflateZlib(data []byte) ([]byte, error)
- func IsHexDigit(ch byte) bool
- func IsWhitespace(ch byte) bool
- func PDFNumberToFloat(v PDFValue) (float64, bool)
- func PDFNumberToInt(v PDFValue) (int, bool)
- func ReadBits(data []byte, bitOffset, n int) uint64
- func ReplayOps(ops []ScannedOp, fn func(op string, operands []PDFValue))
- func ResolveColor(cs PDFValue, comps []float64, resources PDFDict) (r, g, b float64)
- func UndoPNGPredictor(data []byte, columns, colors, bpc int) ([]byte, error)
- func UndoTIFFPredictor(data []byte, columns, colors, bpc int) ([]byte, error)
- func ValuePointer(v PDFValue) uintptr
- type CCITTParams
- type Check
- type ContentScanner
- type Cursor
- type FileResult
- type Function
- type InlineImageRaw
- type LevelType
- type Lexer
- type PDFArray
- type PDFBoolean
- type PDFDict
- type PDFError
- type PDFHexString
- type PDFInteger
- type PDFName
- type PDFReal
- type PDFRef
- type PDFString
- type PDFValue
- type Profile
- func (p *Profile) AddCheck(checks ...Check) *Profile
- func (p *Profile) Allows(clause string, subclause int) bool
- func (p *Profile) Checks() []Check
- func (p *Profile) Clear() *Profile
- func (p *Profile) Clone() *Profile
- func (p *Profile) Has(c Check) bool
- func (p *Profile) RemoveCheck(checks ...Check) *Profile
- func (p *Profile) String() string
- type Reader
- func (d *Reader) AdoptStreamCaches(src *Reader)
- func (d *Reader) BuildPageIndex(graph PDFValue) (map[int]int, error)
- func (d *Reader) ClaimedConformance() (part, conformance string, err error)
- func (d *Reader) Close() error
- func (d *Reader) DecodeStreamCached(dict PDFDict) ([]byte, error)
- func (d *Reader) DecodeStreamCachedConcurrent(dict PDFDict) ([]byte, error)
- func (d *Reader) EffectiveTrailer() PDFDict
- func (d *Reader) GetMetadata() (map[string]string, error)
- func (d *Reader) GetPageCount() (int, error)
- func (d *Reader) GetVersion() (string, error)
- func (d *Reader) PDFStart() int64
- func (d *Reader) ParseXRefSectionAt(offset int64, fillIn bool) (PDFDict, error)
- func (d *Reader) RawXMP() (data []byte, meta PDFDict, err error)
- func (d *Reader) ReadAt(p []byte, off int64) (int, error)
- func (d *Reader) ResolveGraph() (PDFValue, error)
- func (d *Reader) ResolveGraphByPath(path []string) (PDFValue, error)
- func (d *Reader) ResolveObject(obj PDFValue) (PDFValue, error)
- func (d *Reader) ResolveReference(ref PDFRef) (PDFValue, error)
- func (d *Reader) ScanStreamCached(dict PDFDict) ([]ScannedOp, error)
- func (d *Reader) SeedResolvedGraph(graph PDFDict, objs map[int]PDFValue)
- func (d *Reader) Size() int64
- func (d *Reader) StructErrors() []PDFError
- func (d *Reader) Trailer() PDFDict
- func (d *Reader) XMPMetadata() ([]byte, error)
- func (d *Reader) XRefOffset() int64
- func (d *Reader) XRefTable() map[int]int64
- type Result
- type ScannedOp
- type StreamKey
- type Token
- type TokenType
Constants ¶
This section is empty.
Variables ¶
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.
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).
var Checks checksRegistry
Functions ¶
func CMYKToRGB ¶
cmykToRGB applies the PDF specification's default (non-ICC) CMYK -> RGB approximation: R = 1-min(1,C+K), and likewise for G/B.
func ClauseLess ¶
ClauseLess compares two dotted clause numbers ("6.2.9", "6.2.10") segment by segment so they sort numerically rather than lexicographically.
func ColorSpaceComponents ¶
colorSpaceComponents returns the number of colour components a (non- Indexed) base colour space takes.
func DecodeASCII85 ¶
DecodeASCII85 decodes an ASCII85Decode stream.
func DecodeASCIIHex ¶
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
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 DecodePDFHexStringBytes ¶
DecodePDFHexStringBytes decodes a hex string's digit characters into bytes, ignoring whitespace and padding a trailing odd nibble with 0.
func DecodePDFName ¶
DecodePDFName decodes PDF name #XX escape sequences and returns the resulting byte slice. Unescaped bytes are returned as-is.
func DecodePDFTextString ¶
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 ¶
decodeStream returns the decoded bytes of a stream dictionary, applying FlateDecode, ASCIIHexDecode, and ASCII85Decode filters as needed.
func DictInt ¶
dictInt reads an integer-valued entry from dict, returning def if absent or not an integer.
func EncodePDFLiteralString ¶ added in v0.5.0
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 FilterNames ¶
filterNames returns the list of filter names applied to a stream.
func FirstRegexpGroup ¶
FirstRegexpGroup returns the first non-empty capture group re matches in s.
func FloatArray ¶
floatArray converts a PDFArray of PDFInteger/PDFReal values to []float64.
func InflateZlib ¶
inflateZlib decodes a zlib (FlateDecode/Fl) stream using a pooled decoder.
func IsHexDigit ¶
func IsWhitespace ¶
func PDFNumberToFloat ¶
pdfNumberToFloat extracts a float64 from a PDFInteger/PDFReal value, the float counterpart of pdfNumberToInt.
func PDFNumberToInt ¶
PDFNumberToInt extracts an int from a PDFInteger/PDFReal value, the repeated PDF-number-operand pattern used throughout font and image checks.
func ReadBits ¶
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
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 ¶
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 ¶
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 ¶
undoTIFFPredictor reverses TIFF predictor 2 (horizontal differencing), applied per sample within each row.
func ValuePointer ¶
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 ¶
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 ¶
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 ¶
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 ¶
ChecksForClause returns every registered check under the given clause (e.g. "6.3.4"), in catalog order.
func (Check) Description ¶
Description returns a human-readable summary of what this check enforces.
func (Check) ID ¶
ID returns this check's unique sequential registration ID, used by Profile as a compact key for its enabled-check set.
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 FileResult ¶ added in v0.3.0
FileResult is one path's outcome from a batch operation.
type Function ¶
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 ¶
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 ¶
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 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 NewLexerBytes ¶ added in v0.5.0
NewLexerBytes creates a fast lexer that indexes data starting at startPos.
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 ¶
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 ¶
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 ¶
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) IsDocumentLevel ¶
IsDocumentLevel reports whether this violation applies to the document as a whole rather than to a specific page.
func (PDFError) ObjectRef ¶
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.
type PDFHexString ¶
type PDFHexString struct{ Value string }
type PDFInteger ¶
type PDFInteger int
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 NewProfile ¶
NewProfile returns an empty profile for the given conformance level.
func (*Profile) AddCheck ¶
AddCheck returns a new profile with the given checks added to the enabled set.
func (*Profile) Clear ¶
Clear returns a new profile with the same conformance level but no checks enabled. Behavioral flags (SkipUnreachableXObjects, SkipUnusedSimpleFonts) are preserved.
func (*Profile) RemoveCheck ¶
RemoveCheck returns a new profile with the given checks removed from the enabled set.
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 OpenBytes ¶
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
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 (*Reader) ClaimedConformance ¶
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) DecodeStreamCached ¶ added in v0.5.0
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
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 ¶
EffectiveTrailer returns d.trailer, or d.firstPageTrailer for linearized PDFs whose overflow trailer lacks /Root.
func (*Reader) GetMetadata ¶
GetMetadata extracts info from the Info dictionary.
func (*Reader) GetPageCount ¶
GetPageCount retrieves the page count.
func (*Reader) GetVersion ¶
GetVersion extracts the PDF version from the Reader header
func (*Reader) PDFStart ¶
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 ¶
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 ¶
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 ¶
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 ¶
ResolveGraph resolves the PDF object graph, starting from the effective trailer (firstPageTrailer if set, else trailer).
func (*Reader) ResolveGraphByPath ¶
ResolveGraphByPath resolves the PDF object graph by path, starting from the effective trailer (firstPageTrailer if set, else trailer).
func (*Reader) ResolveReference ¶
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
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
SeedResolvedGraph pre-populates the Reader with an already-resolved graph and object cache.
func (*Reader) StructErrors ¶
StructErrors returns the structural parse diagnostics recorded so far.
func (*Reader) Trailer ¶
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 ¶
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 ¶
XRefOffset returns the byte offset of the main cross-reference section, as recorded by the trailer's startxref.
type Result ¶
func (Result) Checks ¶
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) IssuesByCheck ¶
IssuesByCheck groups r.Issues by their violated
func (Result) IssuesForCheck ¶
IssuesForCheck returns the issues that correspond to the given registered
func (Result) IssuesOnPage ¶
IssuesOnPage returns the issues found on the given 1-based page number. Pass 0 to get document-level issues (see PDFError.IsDocumentLevel).
type ScannedOp ¶ added in v0.5.0
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
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
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 ¶
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).