Documentation
¶
Overview ¶
Package reader takes existing PDF bytes apart: the object syntax, the cross-reference machinery, stream filters, and the document structure built on top of them. It is the parsing counterpart of github.com/go-pdfkit/pdfkit, which writes PDF.
Nothing outside the Go standard library is used, so the package builds for js/wasm and for every architecture the fleet targets.
Index ¶
- Variables
- func AppendObject(dst []byte, o Object) []byte
- func FormatObject(o Object) []byte
- func ImageFilter(n Name) bool
- func ParseIndirectObject(b []byte, resolve Resolver) (Ref, Object, int, error)
- func TextString(o Object) (string, bool)
- func ToBool(o Object) (bool, bool)
- func ToFloat(o Object) (float64, bool)
- func ToInt(o Object) (int64, bool)
- func ToString(o Object) ([]byte, bool)
- type Array
- type Bool
- type ContentScanner
- type Decoded
- type Dict
- type Document
- func (d *Document) Catalog() (Dict, error)
- func (d *Document) DecodeStream(s *Stream) ([]byte, Name, error)
- func (d *Document) DecodeStreamRecovering(s *Stream) Decoded
- func (d *Document) DecodeStreamRecoveringLimit(s *Stream, limit int64) Decoded
- func (d *Document) Encrypted() bool
- func (d *Document) Get(ref Ref) (Object, error)
- func (d *Document) GetDict(from Dict, key Name) (Dict, bool)
- func (d *Document) Linearize() ([]byte, error)
- func (d *Document) Page(i int) (Dict, error)
- func (d *Document) PageContent(i int) ([]byte, error)
- func (d *Document) PageContentDecoded(i int) (Decoded, error)
- func (d *Document) PageContentDecodedLimit(i int, limit int64) (Decoded, error)
- func (d *Document) PageCount() int
- func (d *Document) PageOperations(i int) ([]Operation, error)
- func (d *Document) PageRef(i int) (Ref, bool)
- func (d *Document) Partition() (*Partition, error)
- func (d *Document) Protection() (Protection, bool)
- func (d *Document) Repaired() bool
- func (d *Document) Resolve(o Object) (Object, error)
- func (d *Document) Resolver() Resolver
- func (d *Document) Signatures() ([]Signature, error)
- func (d *Document) SignedBytes(s Signature) ([]byte, error)
- func (d *Document) Trailer() Dict
- func (d *Document) Version() string
- type Encryption
- type InlineImage
- type Integer
- type Kind
- type Linearization
- type Name
- type Null
- type Object
- type Operation
- type Part
- type Partition
- type Permissions
- type Protection
- type Real
- type Ref
- type Resolver
- type Signature
- type Stream
- type String
- type SyntaxError
- type Writer
Constants ¶
This section is empty.
Variables ¶
var ( // ErrNotLinearized says the file carries no linearization parameter // dictionary where Annex F requires one. ErrNotLinearized = errors.New("reader: the file has no linearization parameter dictionary") // ErrLinearizationStale says the dictionary is there and well formed but // disagrees with the file around it — which Table F.1 says shall be // treated as ordinary PDF. Appending an incremental update does this, and // F.3.6 says any such change invalidates the hint tables. ErrLinearizationStale = errors.New("reader: the linearization parameters do not describe this file") // ErrLinearizationMalformed says the dictionary is present but breaks a // rule of Table F.1 — a missing required entry, a wrong type, or a value // that is an indirect reference where "all values in this dictionary // shall be direct objects". ErrLinearizationMalformed = errors.New("reader: the linearization parameter dictionary is malformed") // ErrHintTablesInvalid says the parameter dictionary agrees with the file // and the hint tables /H names do not read as Annex F's F.4 describes // them. // // ⛔⛔ IT IS A SEPARATE ERROR BECAUSE THE HINT TABLES ARE AN OPTIMISATION // AND THE PARAMETERS ARE NOT. F.3.6: the tables let a reader fetch and // display page one before the rest arrives. A file whose tables are wrong // is still a correct PDF that any reader can open by the ordinary route — // what it has lost is the fast path. A caller that cannot tell this from // ErrLinearizationStale must either reject readable files or accept // parameters that lie, and neither is what Table F.1 asks for. // // ⭐ testdata/linearized-gs.pdf is exactly this case and is committed for // it: Ghostscript 10.08.0 writes sound parameters and hint tables that // qpdf reports five problems in. Before this error existed the fixture had // to be described in prose as "a positive for the parameters and a // negative for the tables"; now the distinction is in the type. ErrHintTablesInvalid = errors.New("reader: the hint tables do not describe this file") )
Errors from Linearized. They are distinguishable because the difference matters to a caller: a file with no parameter dictionary was never linearized, while one whose dictionary disagrees with the file was linearized and then changed.
var ErrByteRange = errors.New("reader: invalid signature /ByteRange")
ErrByteRange is wrapped by every refusal of a signature's /ByteRange or of the gap it leaves.
var ErrCannotLayOut = errors.New("reader: this partition cannot be laid out for linearization")
ErrCannotLayOut reports a partition this package declines to put in order.
var ErrCannotLinearize = errors.New("reader: this document cannot be linearized")
ErrCannotLinearize reports a document this package declines to linearize.
var ErrCannotPartition = errors.New("reader: this document cannot be partitioned for linearization")
ErrCannotPartition reports a document this package declines to place.
⛔⛔ IT IS A REFUSAL AND NOT A BEST EFFORT, which is the whole design of this function. Annex F.3.5, F.3.7 and F.3.10 place objects by what REFERS to them — an outline hierarchy belongs to part 6 or part 9 depending on /PageMode, thread dictionaries split from their information dictionaries across parts 4 and 9, an interactive form's top level separates from its field hierarchy — and a partition that guessed any of those would produce a file whose hint tables point a reader at the wrong offsets. That is worse than no file: the reader does not fail, it reads the wrong bytes.
var ErrLinearizationTooWide = errors.New("reader: the linearization parameters do not fit their reserved span")
ErrLinearizationTooWide reports a parameter dictionary that will not fit the span reserved for it.
var ErrTooManyFields = errors.New("reader: the interactive form has too many fields")
ErrTooManyFields is returned when the interactive form is larger than this package will walk.
var ErrUnsupportedEncryption = errors.New("reader: unsupported security handler")
ErrUnsupportedEncryption is returned for a security handler this package does not implement — anything other than the standard one.
var ErrWrongPassword = errors.New("reader: the password does not open this file")
ErrWrongPassword is returned when a file is encrypted and neither the password given nor the empty one opens it.
Functions ¶
func AppendObject ¶
AppendObject writes an object in PDF syntax, appending to dst. Dictionary keys are written in order, so the same object always produces the same bytes — which is what makes a rewritten file comparable with the one it came from.
func FormatObject ¶
FormatObject renders an object in PDF syntax.
func ImageFilter ¶
ImageFilter reports whether a filter yields an encoded image rather than a byte stream. Decode stops at one of these and hands the caller the still encoded bytes, because decoding them is an image decoder's job.
/CCITTFaxDecode was on this list and is not any more. It does not carry an image with its own idea of how many components it has and how deep they are, the way DCT and JPX do: it produces bilevel samples, one bit a pixel, and the stream dictionary says what they mean. That is a byte stream, so it is a filter — and decoding it here means every caller gets it rather than each writing its own. See ccitt.go.
func ParseIndirectObject ¶
ParseIndirectObject parses "N G obj … endobj" from the start of b, returning the reference it defines, the object itself, and how many bytes it consumed. A stream's /Length may be an indirect reference; resolve supplies it, and a nil or unhelpful resolve falls back to scanning for the endstream keyword.
func TextString ¶ added in v0.9.0
TextString decodes a PDF text string: what a document says in a human language, as opposed to the bytes of a name, a date or a content stream. A title, an author, a bookmark's label, a form field's value.
⛔ ToString is NOT this. It hands back the bytes, and the bytes of a text string are not text: `pdfops info` printed a document's creator as "\xfe\xffL\x00a\x00T\x00e\x00X" — a UTF-16 string read a byte at a time — and that output had been shipping for as long as the verb had.
A text string is one of three things (ISO 32000-1 §7.9.2.2 and §7.9.2.2.1 of ISO 32000-2):
FE FF … UTF-16BE, which is how a document says anything outside
Latin 1 and most of what any modern producer writes
EF BB BF … UTF-8, which PDF 2.0 added
anything else PDFDocEncoding
⛔ Only those two byte orders of mark, and no guessing beyond them. A string that merely looks like UTF-16LE is PDFDocEncoding that happens to contain a zero byte, and decoding it as UTF-16 turns a readable title into mojibake — which is the opposite failure to the one above and just as silent.
Types ¶
type Array ¶
type Array []Object
Array is a PDF array.
type ContentScanner ¶
type ContentScanner struct {
// contains filtered or unexported fields
}
A ContentScanner walks a content stream one operation at a time. A stream with rubbish in it yields the operations around the rubbish rather than nothing at all, which is what a renderer needs; ContentScanner.Err reports the first thing that did not parse.
func NewContentScanner ¶
func NewContentScanner(data []byte) *ContentScanner
NewContentScanner reads operations from a decoded content stream.
func (*ContentScanner) Err ¶
func (s *ContentScanner) Err() error
Err reports the first malformed token the scan stepped over, if any.
func (*ContentScanner) Next ¶
func (s *ContentScanner) Next() (Operation, bool)
Next returns the next operation, and false once the stream is exhausted.
type Decoded ¶ added in v0.6.0
type Decoded struct {
// Data is what the chain decoded. A recovered decode leaves fewer bytes
// here than the stream meant to carry, but they are bytes of the kind it
// meant to carry: Data never holds bytes that no filter has decoded.
//
// The one case where Data is still encoded is the deliberate one: a chain
// that stopped at an image filter, which Image names and Recovered does
// not flag, because stopping there is the contract.
Data []byte
// Undecoded holds the bytes the chain could not get past, still in the
// encoding Filter names. It is set instead of Data — never beside it —
// when the filter that failed produced nothing at all.
//
// This is where a compressed content stream, a truncated fax, or a filter
// nobody implements ends up. A caller that wants the stream as it lies has
// to ask for it by a name that says what it is; a caller that reads Data
// cannot be handed it by accident. Painting undecoded bytes as a one-bit
// image looks like a page with something on it, which is why nothing about
// this is left to a flag.
Undecoded []byte
// Image names the image filter the chain stopped at, when it stopped at
// one; Data is then the bytes still encoded in it.
Image Name
// Recovered says the chain could not be run to the end. A caller that must
// not act on damaged data stops here — or calls [Decode], which refuses
// outright.
Recovered bool
// Cause says why the chain stopped, and is set exactly when Recovered is.
Cause error
// Filter names the filter that could not be applied, when one is to blame:
// a chain whose /Filter entry itself is unreadable blames nothing.
Filter Name
}
A Decoded is the outcome of applying a stream's filter chain, including the outcome of a chain that could not be finished.
The point of the type is that a caller can tell the three outcomes apart without having to be careful. Bytes a filter decoded and bytes no filter decoded arrive in different fields, so the second kind cannot be painted as samples or tokenised as content by a caller that forgot to check a flag.
func DecodeRecovering ¶ added in v0.6.0
DecodeRecovering applies a stream dictionary's filter chain to raw and never fails. A filter that cannot be applied — corrupt Flate data, a stream that stops in the middle, a filter name nobody implements — ends the chain, and what the filters before it produced is returned with Decoded.Recovered set. That is deliberately what every other reader does: refusing the stream loses a page the file can still show.
The salvage is always as far down the chain as the filters got, never the bytes as they arrived: a damaged Flate stream yields the prefix it did inflate, in Decoded.Data. A filter that produced nothing at all leaves the bytes in Decoded.Undecoded instead, still in its encoding, because that is what they are.
func DecodeRecoveringLimit ¶ added in v0.21.0
DecodeRecoveringLimit is DecodeRecovering with the caller's own ceiling on what any one filter of the chain may produce. A caller that holds a budget (a renderer that has already charged part of its memory) passes what is left, so that a stream is refused while it inflates and not after it has been materialised in full. A limit below 1 or above the package's own cap of 1 GiB means that cap. A filter that would pass the limit fails like any other filter that cannot be finished: Recovered is set, Cause says what was exceeded, and Data holds the prefix inflated before it was stopped (Flate) or nothing (the other filters, whose output is judged once it is made).
func DecodeStreamRecovering ¶ added in v0.6.0
DecodeStreamRecovering is DecodeRecovering for a parsed stream.
type Dict ¶
Dict is a PDF dictionary.
func ToDict ¶
ToDict reports the dictionary of a dictionary object, or a stream's own dictionary — a stream is a dictionary everywhere a dictionary is expected.
type Document ¶
type Document struct {
// contains filtered or unexported fields
}
A Document is a parsed PDF file: its cross-reference information, its trailer, and lazy access to every object in it.
func Open ¶
Open parses the cross-reference information of a PDF file held in memory, using the empty password. A file whose tables are damaged is rebuilt by scanning it, so Open fails only when there is no usable document structure at all, or when the file is encrypted and the empty password does not open it — OpenWithPassword then does.
func OpenWithPassword ¶
OpenWithPassword is Open with a password to try. The password is tried both as the user password and as the owner password, the empty one as well.
func (*Document) DecodeStream ¶
DecodeStream applies a stream's filter chain, resolving any indirect decode parameters against this document. A chain that cannot be run to the end is an error; Document.DecodeStreamRecovering salvages instead.
func (*Document) DecodeStreamRecovering ¶ added in v0.6.0
DecodeStreamRecovering applies a stream's filter chain, salvaging what it can from a chain that cannot be run to the end and saying that it did so.
func (*Document) DecodeStreamRecoveringLimit ¶ added in v0.21.0
DecodeStreamRecoveringLimit is Document.DecodeStreamRecovering refusing to produce more than limit bytes from any one filter; see DecodeRecoveringLimit.
func (*Document) Get ¶
Get returns the object an indirect reference names, or Null when the file does not define it.
func (*Document) Linearize ¶ added in v0.16.0
Linearize writes a linearized copy of the document: ISO 32000-1 Annex F's eleven parts, with the parameter dictionary at the front and the first-page cross-reference section before the objects a reader needs first.
The file carries the parameter dictionary, both cross-reference sections, and a primary hint stream holding Table F.3's page offset table and Table F.5's shared object hint table. `qpdf --check` reports no problem with it.
⛔⛔ IT WRITES DOCUMENTS WHOSE PAGES SHARE OBJECTS, which until #68 it refused. F.4.2's shared object hint table is how a page after the first says which of part 6's and part 8's objects it depends on; the writer used to emit a required but EMPTY one, true for a document whose pages are independent and a contradiction for one whose pages are not — two pages sharing a content stream gave `qpdf --check`:
WARNING: page 1: shared object 3: in computed list but not hint table
so it returned an error instead of a file that lied. The table is now filled, and that warning is gone on every shape the suite and the probe exercise.
⛔⛔⛔ THE REFUSAL IS GONE AND SO IS ITS RULE. What stood here was
refused iff an object a page after the first reaches is ALSO reached by the first page or by another page — other than the CATALOGUE
and it is kept only to say that it no longer holds: every one of those shapes is written. The sentence was corrected three times before it was right, and the shapes that corrected it are now the rows of TestWhatEachInheritanceShapePutsInTheSharedTable, where each one asserts what goes IN the table instead of whether the file exists.
⛔ THE CATALOGUE IS STILL THE EXCEPTION, and it survived the change for the reason it was always right: `of[catNum] = PartCatalog` is assigned AFTER the readers loop, so part 4 holds it, part 4 precedes part 6, and it reaches the reader ahead of the first page. planShared plans parts 6 and 8 only, so a later page that depends on the catalogue still gets no F.4.2 identifier — measured, not assumed: that row of the table asserts ZERO identifiers.
⛔⛔ INHERITANCE IS A ROUTE BY WHICH A PAGE REACHES AN OBJECT, not a separate case. Table 30 lets a page omit /Resources, /MediaBox, /CropBox and /Rotate and take an ancestor's, and the writer pushes those down because F.3.7 needs part 6 self-contained — so an inherited reference makes the page reach that object exactly as naming it would. That is why the partition had to learn inheritance (#66) before this table could be right: an object the partition cannot see a page reaching is an object the table cannot describe, and the same fix that made the refusal correct is what makes the table correct.
⚠ WHAT THIS WRITER STILL DOES NOT SAY is WHERE in a page a shared object is first used: F.4.1 items 5 and 13 are a fraction, and refsFor writes 0/1 for every reference. A reader may fetch a shared object earlier than it needs it, never later. See refsFor.
⚠ AND ITEMS 6 AND 7 ARE 0 FOR TWO DIFFERENT PAGES. They are an offset from the page's first byte and a length, both unsigned, so a page that BORROWS a shared content stream — which then lies in part 6, BEFORE the page — has no representable value and gets zeros, exactly like a page with no content stream at all. The format cannot tell those apart and neither can a reader; the suite can, and asserts each case separately. A reader that treats 0 as "nothing to prefetch" is right in both, which is why this is a loss of precision rather than a falsehood.
⭐ EVERY STEP WAS JUDGED BEFORE THE NEXT ONE STARTED, which is why the defects were separable: the partition before the layout, the layout before the fixpoint, the encoder's bytes before any file existed, and the layout before the tables. A writer that emitted everything at once could only be asked "is this file right", and qpdf's answer would have named a hint-table problem while a wrong /T sat underneath it.
func (*Document) Page ¶
Page returns the i'th page's dictionary, counting from one, with the attributes it inherits from its ancestors filled in.
func (*Document) PageContent ¶
PageContent returns the decoded content stream of the i'th page, counting from one. A page whose /Contents is an array has its streams joined, as the specification requires, with a newline between them.
A content stream whose filters cannot be applied contributes what could be salvaged from it rather than failing the page, which is what a renderer needs; the error is for a page that is not there at all. Document.PageContentDecoded says whether any salvaging happened.
func (*Document) PageContentDecoded ¶ added in v0.6.0
PageContentDecoded is Document.PageContent with the outcome of the decode attached: Decoded.Recovered reports that at least one of the page's content streams could not be decoded cleanly, and Decoded.Cause says why.
func (*Document) PageContentDecodedLimit ¶ added in v0.21.0
PageContentDecodedLimit is Document.PageContentDecoded with a ceiling on the whole page: the decoded streams of its /Contents together never hold more than limit bytes, and a stream that would pass what is left is cut short while it inflates, with Decoded.Recovered set. A limit below 1 means the package's own cap on a single stream.
func (*Document) PageOperations ¶
PageOperations tokenises the i'th page's content stream, counting from one.
func (*Document) Partition ¶ added in v0.13.0
Partition computes which part of a linearized layout each object belongs to, following ISO 32000-1 Annex F.3.5, F.3.7, F.3.9 and F.3.10.
It is the first step of writing a linearized file (go-pdfkit/reader#40) and it is deliberately separable from the writing: the partition is a pure function of the document, it has a foreign judge that can check it — `qpdf --show-linearization` prints its own computed part assignments — and getting it wrong is the failure that would be hardest to see in a finished file.
⛔ WHAT IT DECLINES, BY NAME. Every construct below changes which part an object belongs to, and none is exercised by any file in this package's corpus, so placing them would be writing untested rules into a format where a wrong placement is silent:
- /OpenAction, because F.3.7 says the page it opens at becomes the first page, and part 6 is defined in terms of that page rather than page one.
- /PageMode UseOutlines together with /Outlines, because F.3.7 then puts the ENTIRE outline hierarchy in part 6, where F.3.10 otherwise puts it in part 9.
- /Threads, because F.3.5 places the thread dictionaries in part 4 while F.3.10 places their /I information dictionaries in part 9 and the bead dictionaries go with the individual pages: one key, three parts.
- /AcroForm, because F.3.5 takes only the TOP-LEVEL form dictionary into part 4 and F.3.10 takes the field hierarchy into part 9.
- /Encrypt, because F.3.5 requires the encryption dictionary AND all its values in part 4, and because the first-page cross-reference table indexes them.
- /Thumb on any page, because F.3.10 gives thumbnails and their shared objects two ordered categories of their own.
A document using any of them is refused with ErrCannotPartition naming which, so that the next person to need one knows exactly which rule to implement and which part of the annex states it.
func (*Document) Protection ¶ added in v0.4.0
func (d *Document) Protection() (Protection, bool)
Protection reports how the file is protected, and false when it is not protected at all. A document that opened has already been decrypted; this says what it said about itself on the way.
func (*Document) Repaired ¶
Repaired reports whether the document's structure was rebuilt by scanning the file rather than read from its cross-reference tables.
func (*Document) Resolver ¶
Resolver returns the function that turns this document's indirect references into objects, for Resolve and Decode.
func (*Document) Signatures ¶ added in v0.20.0
Signatures lists the document's signature fields that hold a signature, walking /AcroForm /Fields and /Kids (ISO 32000-1 §12.7.4.5): a field is a signature field when its /FT, which it may inherit from an ancestor, is /Sig, and it holds one when its /V, likewise inheritable, is a dictionary. The walk is bounded in depth and in the number of fields, and cycle-safe.
A document without an interactive form has no signatures and no error. A signature whose /ByteRange or gap is refused is still listed, with Err set and no Contents.
func (*Document) SignedBytes ¶ added in v0.20.0
SignedBytes returns the bytes the signature covers: the file's two ranges, concatenated, exactly what a detached CMS signature (adbe.pkcs7.detached, ETSI.CAdES.detached) was computed over (ISO 32000-1 §12.8.3.3).
The /ByteRange is validated first, against this document, whatever s says, and s.Contents must be the string the file holds in the gap: a Signature built or altered by hand cannot name bytes the file's own ranges do not.
type Encryption ¶ added in v0.3.0
type Encryption struct {
UserPassword string
OwnerPassword string
Permissions Permissions
// AES128 asks for the older method, which readers before 2008 understand.
// The default is AES-256, which is what a file should use today.
AES128 bool
}
An Encryption says how a file is to be protected.
Two people can open it: whoever knows the user password, subject to the permissions, and whoever knows the owner password, subject to nothing. An empty user password means the file opens without one and the permissions are all it says.
type InlineImage ¶
An InlineImage is the dictionary and the still-encoded bytes of a BI … ID … EI sequence. Its dictionary uses the abbreviated keys inline images are written with; InlineImage.Expanded gives the ordinary spelling.
func (*InlineImage) Expanded ¶
func (im *InlineImage) Expanded() Dict
Expanded returns the image's dictionary with the abbreviated keys and colour space names written out, so it can be read like any image XObject.
A dictionary may say the same thing twice and disagree with itself: /W 20 beside /Width 10, /CS /RGB beside /ColorSpace /3chanRGB. The specification permits both spellings in an inline image and says nothing about which wins, and the public implementations disagree — pdf.js asks for the abbreviation and falls back to the written-out name, MuPDF asks the other way round.
The abbreviation wins here. Two reasons: it is the spelling Table 93 gives for an inline image, the written-out name being the tolerated alias; and safedocs' own fixture for this case marks the abbreviation as the line to remove "to see the effect", which is a statement about what the reference viewer does.
What is not defensible is the answer changing between runs. Expanding in one pass over the map made the winner depend on Go's map iteration order, which is deliberately random: the same file drew differently each time it was opened, with no way for a caller to notice. Two passes settle it — the written-out names first, then the abbreviations over them — and no order within either pass can matter, because the names in each are distinct.
type Integer ¶
type Integer int64
Integer is a PDF integer. Numbers too large for an int64 are parsed as Real, which is what every other reader does.
type Kind ¶
type Kind uint8
Kind names the eight basic PDF object types plus the two the file format adds on top of them: streams and indirect references.
const ( KindNull Kind = iota KindBool KindInteger KindReal KindString KindName KindArray KindDict KindStream KindRef )
The object kinds. Object.Kind reports one of these.
type Linearization ¶ added in v0.10.0
type Linearization struct {
// Version is /Linearized, "a version identification for the linearized
// format". Files in the wild carry 1 and 1.0; nothing is known to depend
// on it.
Version float64
// FileLength is /L, which "shall be exactly equal to the actual length of
// the PDF file".
FileLength int
// HintOffset and HintLength are the first pair of /H: where the primary
// hint stream starts — "the beginning of the stream object, not the
// beginning of the stream data" — and how long it is including object
// overhead.
HintOffset, HintLength int
// OverflowHintOffset and OverflowHintLength are the optional second pair
// of /H, for the overflow hint stream (part 10). HasOverflowHint says
// whether they were given, because zero is a legitimate-looking value for
// an offset that was never written.
OverflowHintOffset, OverflowHintLength int
HasOverflowHint bool
// FirstPageObject is /O, "the object number of the first page's page
// object".
FirstPageObject int
// FirstPageEnd is /E, the offset of the end of the first page.
FirstPageEnd int
// PageCount is /N, the number of pages in the document.
PageCount int
// LengthsMeasured says whether the hint tables' lengths were looked at at
// all. [CheckLinearized] sets it; [Linearized] leaves it false.
//
// ⛔⛔ IT EXISTS FOR THE REASON HasOverflowHint DOES, and the first version
// of these fields had to learn that from this very struct. A count of zero
// is a legitimate-looking value for a measurement that never ran: a
// Linearization from [Linearized] reports 0 checked because nothing checked
// it, and one from [CheckLinearized] can report 0 because every span was
// inside an object stream. Documenting the difference is not the same as
// making it unrepresentable.
LengthsMeasured bool
// LengthsChecked and LengthsSkipped count the hint-table lengths
// [CheckLinearized] held against the file, and those it could not measure.
// They mean nothing unless LengthsMeasured is true.
//
// ⛔ A span is not measured when it contains an object inside an object
// stream: such an object has no offset of its own, and qpdf substitutes its
// CONTAINER's, so several objects would measure from one byte. That is its
// accounting rather than a fact about the file, so the span is skipped.
//
// ⚠ A non-zero LengthsSkipped is NOT a defect in the file. Object streams
// are legal in a linearized document and F.4 says nothing against them; it
// is the measurement declining to claim what it cannot see.
LengthsChecked, LengthsSkipped int
// MainXrefOffset is /T. For a file with a traditional cross-reference
// table this is "the offset of the white-space character preceding the
// first entry of the main cross-reference table (the entry for object
// number 0)"; for a file using cross-reference streams exclusively (PDF
// 1.5) it is "the offset of the main cross-reference stream object".
MainXrefOffset int
// FirstPageNumber is /P, optional, default 0.
FirstPageNumber int
}
A Linearization is the parameter dictionary at the front of a linearized file (ISO 32000-1 Table F.1). Offsets and lengths are in bytes from the beginning of the file.
func CheckLinearized ¶ added in v0.11.0
func CheckLinearized(b []byte) (*Linearization, error)
CheckLinearized reads the parameter dictionary and then checks what it says against the document it describes.
⛔⛔ Linearized ON ITS OWN IS A WEAKER TEST THAN IT LOOKS, AND A WRITER DEVELOPED AGAINST IT WOULD PASS WITHOUT LINEARIZING ANYTHING. Of Table F.1's claims it checks exactly one against the file — /L against the byte count — because it is deliberately cheap: a reader deciding whether to stream a file has fetched 1024 bytes and has no cross-reference table to resolve anything with. /O, /E, /N and /T are read for type and never consulted. So a file carrying a correct /L and four invented integers is accepted, which is precisely what a first linearizer would emit.
This is the other question, for the other caller: not "may a reader trust the front of this file" but "is this file actually what the front says". It opens the document AND decodes the primary hint stream, so it costs what opening costs plus one stream expansion — bounded by maxDecodedSize — and the page entries it allocates. It is the judgement a writer needs on bytes it has just produced, not something to call on untrusted input to decide cheaply whether to proceed; Linearized is that.
What it establishes is that every parameter POINTS AT WHAT IT CLAIMS TO: the page count is the real one, /O is the real first page, /H begins at a real stream object of the length it declares, /T reaches the main cross-reference.
⛔ AND THAT THE HINT TABLES READ AS F.4 DESCRIBES THEM, which is new and is narrower than it sounds. Both tables must decode: every bit width in 0..32, every entry inside the stream, the page offset table ending at or before /S, and the counts bounded by the document's objects. Failure is ErrHintTablesInvalid.
⛔⛔ IT DOES NOT CHECK THE TABLES' VALUES, and the difference decides what a pass here is worth. A table can decode perfectly and still give a page length that is not the page's length — nothing in F.4's LAYOUT is violated, so this cannot see it. On testdata/linearized-gs.pdf, `qpdf --check` reports five such mismatches (three group lengths of 65536, two page lengths); this package refuses that file for a SIXTH defect, its /S overrun, and detects none of the five. Comparing values against the document needs the partition. So: a pass means the tables are READABLE, not that they are RIGHT, and qpdf's `--check` remains the foreign judge the tests print by.
⛔⛔ AND /E IS NOT GATED, SAID OUT LOUD BECAUSE A WRITER WILL BE TEMPTED TO TRUST IT. Table F.1 calls /E the offset of the end of the first page, and qpdf COMPUTES it: on the committed fixture it reports "computed = 901..902" and refuses a wrong value. This only bounds /E between 1 and the file length, so a writer that miscomputes /E passes here and fails qpdf. Review measured the gap. Computing it needs the first-page object set — the same partition the hint tables describe — which is why it waits for that work rather than being approximated now. Until then: do not read a pass from this as evidence about /E.
The error wraps Linearized's sentinels and one of its own. A dictionary that disagrees with the document around it is ErrLinearizationStale, which is what Table F.1 says such a file is — ordinary PDF. Tables that do not read are ErrHintTablesInvalid, which Linearized never returns: the parameters are sound and only the optimisation is lost, so a caller may reasonably open the file anyway.
func Linearized ¶ added in v0.10.0
func Linearized(b []byte) (*Linearization, error)
Linearized reads the linearization parameter dictionary of b and checks it against the file.
It returns the parameters on success. On failure the error wraps one of ErrNotLinearized, ErrLinearizationMalformed or ErrLinearizationStale, and names the claim that failed.
⛔ It does NOT validate the hint tables. Their format is F.4 and checking them is a separate, much larger job; a file can pass this and still have hint tables that send a reader to the wrong offset. What this establishes is that the front of the file says what Annex F requires and that what it says matches the file — which is the part a reader consults first, and the part that goes wrong when a file is edited after being linearized.
type Name ¶
type Name string
Name is a PDF name with its #xx escapes resolved and the leading slash dropped, so /Type is Name("Type").
func Decode ¶
Decode applies a stream dictionary's filter chain to raw. It returns the decoded bytes and, when the chain ends in an image filter, that filter's name together with the bytes still encoded in it.
Decode is the strict reading: a chain that cannot be run to the end is an error and yields no bytes. DecodeRecovering is the lenient one, and says which of the two it gave you.
func DecodeStream ¶
DecodeStream is Decode for a parsed stream.
type Null ¶
type Null struct{}
Null is the PDF null object. A missing dictionary entry resolves to Null rather than to a nil Object, so callers never have to nil-check.
type Object ¶
type Object interface {
Kind() Kind
}
An Object is any value the PDF object syntax can express. The concrete types are Null, Bool, Integer, Real, String, Name, Array, Dict, Ref and *Stream; Kind tells them apart without a type switch.
func ParseObject ¶
ParseObject parses a single direct object from the start of b and reports how many bytes it consumed.
type Operation ¶
type Operation struct {
Operator string
Operands []Object
Image *InlineImage
// Start and End are the operation's byte range in the stream it was
// scanned from: Start is the first byte of its first operand, or of the
// operator itself when it has none, and End is just past the operator.
//
// ⛔ They are here so that a content stream can be edited IN PLACE. A tool
// that wants to put something before every BT has only two honest ways to
// find one: re-serialise the whole stream, which risks changing what an
// inline image's bytes mean, or know where the operator was — and this
// scanner is the only thing that does know, because a "BT" inside a
// string or inside an inline image's data is not an operator and a byte
// search cannot tell.
Start, End int
}
An Operation is one step of a content stream: an operator and the operands that precede it. An inline image is reported as the operator "BI" with its dictionary and data attached, since the three keywords it spans are one thing.
func Operations ¶
Operations tokenises a whole content stream. The error it returns describes what did not parse; the operations it returns are still worth having.
type Part ¶ added in v0.13.0
type Part int
Part names a section of the eleven-part layout ISO 32000-1 Annex F.3.1 gives a linearized file. Only the parts that HOLD DOCUMENT OBJECTS are named: parts 1, 2, 3, 5, 10 and 11 are the header, the cross-reference tables, the hint streams and the trailer, which are produced by the layout rather than assigned to.
The numbers are F.3.1's own, not an enumeration of this package's making, so that a part can be compared with qpdf's `--show-linearization` output and with the annex without a translation table in between.
const ( // PartCatalog is part 4, the document catalogue and the document-level // objects a reader needs the moment the file opens (F.3.5). PartCatalog Part = 4 // PartFirstPage is part 6, every object needed to display the first page // (F.3.7). PartFirstPage Part = 6 // PartOtherPrivate is part 7, objects belonging to exactly one page that // is not the first. PartOtherPrivate Part = 7 // not from the first page (F.3.9). PartShared Part = 8 // PartOther is part 9, everything that is part of the document but not // needed to display a page (F.3.10). PartOther Part = 9 )
type Partition ¶ added in v0.13.0
type Partition struct {
// Of maps an object number to its part. An object the document never
// reaches is absent rather than placed: a linearized file is written from
// the objects a reader needs, and an unreachable object has no page to
// belong to.
Of map[int]Part
// FirstPage is the page that part 6 holds, counting from one.
FirstPage int
// FirstPageObject is the object number of that page's page object, which
// becomes /O in the linearization parameter dictionary.
FirstPageObject int
// Pages[i] is every object page i+1 needs, including its own page object,
// in ascending object number.
//
// ⛔⛔ THE HINT TABLES CANNOT BE BUILT WITHOUT THIS, and this function was
// computing it and throwing it away. Table F.4 item 1 is "the number of
// objects in a page" and item 2 is that page's length in bytes: both are
// PER PAGE, and Of answers only which PART an object is in. Part 7 says
// "belongs to exactly one page that is not the first" and never says which
// page, so a writer holding only Of knows the order to emit objects in and
// not what to say about them.
//
// ⛔ A page's own object is included, because item 1 counts it: qpdf
// reports 4 objects for a page whose reach is 3.
Pages [][]int
// PageObjects[i] is page i+1's own page object, in this document's
// numbering.
//
// ⛔⛔ Pages[i][0] IS NOT IT, which is why this field exists. Pages[i] is
// built with the page's own object first and then SORTED, so its index 0
// is the lowest object number — and on the fixtures here that usually IS
// the page, so code assuming it would measure correctly on every shape in
// the corpus and be wrong on a document whose content stream is numbered
// below its page.
//
// ⛔⛔ AND THE LAYOUT NEEDS IT, not just the hint tables. qpdf's checker
// computes a page's length by taking the page object's number and the next
// nobjects-1 CONSECUTIVE numbers and summing their lengths
// (QPDF_linearization.cc, Lin::lengthNextN) — so a page whose objects are
// not numbered consecutively from its page object is measured against
// objects belonging to something else. Order uses this to emit each page's
// own object first.
PageObjects []int
// page's part — part 6 or part 8 — and so is a shared object as far as
// F.4.2 is concerned. Shared[0] is always empty: Table F.4 item 3 requires
// 0 shared references for the first page.
//
// ⛔⛔ THIS IS NOT "WHAT IS IN PART 8". An object page 1 needs stays in
// part 6 even when page 3 needs it too, and part 8 holds only objects
// shared between pages that are NOT the first. Measured: for a two-page
// document whose pages share one content stream, our part 8 is empty and
// qpdf's is too — yet qpdf reports `nshared_total: 3`, because its shared
// table covers part 6's shared objects as well.
//
// ⛔ The writer needs this to know when it CANNOT describe a document:
// `qpdf --check` says "page 1: shared object 3: in computed list but not
// hint table" for exactly the pages whose Shared is non-empty.
Shared [][]int
}
Partition is where every object of a document would go in a linearized layout.
func (*Partition) Order ¶ added in v0.16.0
Order returns the object numbers of a partition in the order this package writes them: part 4, then 6, then 7, then 8, then 9.
It is step 2 of writing a linearized file (go-pdfkit/reader#40) and, like Document.Partition before it, it is deliberately separable from the writing: the order is a pure function of the partition, and it can be judged against another producer's file. A layout tangled into the emission could only be checked by writing a whole file and asking qpdf about all of it at once.
⛔⛔ THE PART ORDER IS MEASURED, AND THE ANNEX IT COMES FROM WAS NEVER READ. An earlier version of this comment opened "the order ISO 32000-1 Annex F.3.1 lays them out" as plain fact and admitted ten lines later that the annex was unavailable — the same contradiction this arc has now produced four times. What is true: ISO 32000-1 is not reachable from here, so the rule below was established by reading where qpdf 12.4.2 actually puts each part's objects.
1 page part 4 @500, 6 @667..861, 9 @892
2 pages part 4 @501, 6 @677..871, 7 @902..998, 9 @1096
5 pages part 4 @503, 6 @683..881, 7 @913..1595, 9 @1693
25 pages part 4 @503, 6 @695..894, 7 @926..5590, 9 @5689
10 pages, 4 shared fonts part 4 @604, 6 @808..1370, 7 @1402..3090, 9 @3189
25 pages, 8 shared fonts part 4 @684, 6 @896..1786, 7 @1818..6506, 9 @6605
testdata/linearized-shared part 4 @481, 6 @658..766, 7 @865..1175,
part 8 @1273, 9 @1874
Every part contiguous, no two overlapping, on all seven.
⚠ THE EVIDENCE IS NOT EVEN ACROSS THE PARTS, and the summary line that said "a measured property of real output rather than an inference" was true of most of it and not all. Parts 4, 6, 7 and 9 are attested by seven files; **part 8 by exactly one**, because the shared-font shapes have the first page reference the shared dictionary too and F.3.9 keeps such an object in part 6 — those documents grow part 6 from 3 objects to 12 and say nothing about part 8. testdata/linearized-shared.pdf was built for that question (pages 2..n share a dictionary page 1 never names). So part 8's position here is n=1: corroborated, not established.
⚠ AND QPDF'S OWN DOCUMENTATION CORROBORATES THE WEAKER HALF ONLY. Its linearization chapter never enumerates the parts, never gives their order and cites no clause, but it does say that deciding which part each object belongs to "tells us the exact order in which objects are written". That supports "part membership determines file order" — the half this function rests on — and says nothing about the order being ascending by part number.
⚠ WITHIN a part the order is the object number ascending, and that is THIS PACKAGE'S CHOICE rather than something the annex requires or qpdf agrees with. It is fixed so that writing the same document twice gives the same bytes. Nothing depends on it for CORRECTNESS, since a reader follows the hint tables' offsets — but inside part 6 it can still affect what a sequential viewer can paint first, which is a streaming property and not a correctness one. The tests assert the part boundaries and never the order inside a part.
type Permissions ¶ added in v0.3.0
type Permissions uint32
Permissions say what a reader may do with a file it can open with the user password. They are advisory — nothing enforces them but the reader's own good manners — and a file opened with the owner password ignores them entirely.
const ( PermPrint Permissions = 1 << 2 PermModify Permissions = 1 << 3 PermCopy Permissions = 1 << 4 PermAnnotate Permissions = 1 << 5 PermFillForms Permissions = 1 << 8 PermExtract Permissions = 1 << 9 // for accessibility PermAssemble Permissions = 1 << 10 PermPrintFaithful Permissions = 1 << 11 // at full resolution // AllPermissions grants every one of them. AllPermissions = PermPrint | PermModify | PermCopy | PermAnnotate | PermFillForms | PermExtract | PermAssemble | PermPrintFaithful )
The permissions a standard security handler can express. Anything not granted is refused; AllPermissions grants everything.
func (Permissions) Allows ¶ added in v0.4.0
func (p Permissions) Allows(want Permissions) bool
Allows reports whether every one of the given permissions is granted.
func (Permissions) String ¶ added in v0.4.0
func (p Permissions) String() string
String lists what is granted, in words.
type Protection ¶ added in v0.4.0
type Protection struct {
// Method names the algorithm the way a person would say it: "RC4-40",
// "RC4-128", "AES-128", "AES-256", or "none" for a file that declares an
// /Encrypt dictionary and then encrypts nothing with it.
Method string
// Revision is the standard security handler's revision: 2, 3, 4, 5 or 6.
Revision int
// Permissions is what the file grants whoever opened it with the user
// password.
Permissions Permissions
// Owner is true when the password the file was opened with was the
// owner's, in which case the permissions do not apply to this reader.
Owner bool
}
A Protection is what a file's security handler says about it: how it is encrypted, and what a reader that opened it with the user password may do.
type Ref ¶
Ref is an indirect reference: the "12 0 R" that stands in for an object stored elsewhere in the file.
type Resolver ¶
A Resolver fetches the object an indirect reference names. A document supplies one; a nil Resolver makes every reference resolve to Null, which is what a caller parsing an isolated fragment wants.
type Signature ¶ added in v0.20.0
type Signature struct {
// Field is the fully qualified field name: the /T of every ancestor and of
// the field, joined with ".".
Field string
// Filter and SubFilter are the dictionary's /Filter and /SubFilter names,
// e.g. "Adobe.PPKLite" and "adbe.pkcs7.detached" (Table 252, 12.8.3).
Filter, SubFilter string
// ByteRange is /ByteRange as written. It is the claim, and may be invalid:
// see Err.
ByteRange []int64
// Contents is the signature's DER, decoded from the hex string the
// /ByteRange leaves out of the signed bytes, with the zero padding a signer
// reserves after the DER removed. It is nil when Err is set.
Contents []byte
// Name, Reason, Location and M are the signer's claims — who, why, where and
// when (M is the date string as written). They are filled in ONLY when
// DictionarySigned is true, and empty otherwise: an incremental update could
// have supplied them (a new dictionary copying /ByteRange and /Contents), and
// a forged value must not be displayable by accident. Even then they are the
// signer's claims, not evidence. Field, the field's /T, is read from
// the field dictionaries, which this package never ties to the signed
// bytes: it is a label, not a signed claim, even when DictionarySigned.
Name, Reason, Location, M string
// DictionarySigned is true when the signature dictionary was read from an
// uncompressed indirect object that contains the gap, so its bytes outside
// /Contents lie inside the signed ranges. It is false when the dictionary is
// direct, sits in an object stream, its position cannot be established, or
// its end lies beyond the second range.
DictionarySigned bool
// CoversWholeFile is true when the ranges end at the end of the file, so no
// byte was added after signing. False for an earlier signature once an
// incremental update was appended (and that is legitimate: forms are filled
// and signatures stacked that way); judging what the update changed is the
// caller's.
CoversWholeFile bool
// Err is why this signature's ranges or gap were refused, or nil. A bad
// signature does not hide the others, so it is reported here rather than
// failing Signatures.
Err error
}
A Signature is one signature field that holds a value (/V) with a signature dictionary. Everything here is what the FILE claims; nothing is verified until reader/signature does it.
type Stream ¶
Stream is a PDF stream: a dictionary plus the raw, still-encoded bytes between the stream and endstream keywords. Decode applies the filter chain.
type String ¶
type String []byte
String is a PDF string, already unescaped: the bytes a literal or hex string denotes, with no interpretation of their text encoding.
type SyntaxError ¶
A SyntaxError reports malformed PDF syntax and where it was found, so a repair pass can restart from a known offset instead of giving up.
func (*SyntaxError) Error ¶
func (e *SyntaxError) Error() string
Error implements the error interface.
type Writer ¶
type Writer struct {
// contains filtered or unexported fields
}
A Writer builds a PDF file out of objects. Numbers are handed out by Writer.Reserve, objects are written with Writer.Put, and Writer.Finish adds the cross-reference table and the trailer.
func NewPackedWriter ¶ added in v0.3.0
NewPackedWriter starts a file that puts what it can into compressed object streams and ends in a cross-reference stream. That is smaller — usually by a lot, since a file is mostly small dictionaries — and has been readable since PDF 1.5, which is 2003; the version in the header is raised to 1.5 if it is lower.
func NewWriter ¶
NewWriter starts a file with the given version in its header, "1.7" when the version is empty. Objects are written one after another and the file ends in a cross-reference table, which every reader that has ever existed can read.
func (*Writer) Copy ¶
Copy writes an object from a document into this file, following every indirect reference it reaches and renumbering as it goes, so that objects from several documents can live side by side. An object already copied from the same document keeps the number it was given.
func (*Writer) Encrypt ¶ added in v0.3.0
func (w *Writer) Encrypt(e Encryption)
Encrypt protects everything written from here on. It must be called before anything is written, and the file it produces is not byte-for-byte reproducible: encryption needs randomness, by design.
func (*Writer) Finish ¶
Finish writes the cross-reference table and the trailer and returns the file. /Size is filled in; the caller supplies /Root and whatever else the trailer needs.