Render caches with byte budgets (issue #103, spec #33 viewer capability 13 and story 8).
public sealed class PdfDocument : IDisposable
ISO 32000-2 §7.5 (file structure) and §7.7.2 (document catalog). Opening reads the header, the cross-reference information, the trailer and the catalog; every other object, the page tree included, loads on first use. The document is a live view over its COS objects (Catalog, Trailer, Resolve(CosObject?)), so a change made through the COS layer is visible through the document model.
Reading is lenient by default: deviations are repaired and recorded in Diagnostics. In strict mode the first deviation throws a DiagnosticException; deviations in objects loaded after open (the page tree, for instance) throw from the member that loads them, so strict validation at open is not exhaustive.
Repairs (ISO 32000-2 §7.5 describes the structure but not its repair): a wrong startxref or Prev offset
reads the nearest cross-reference section; an entry whose offset does not hold its object is looked up near that offset, then
anywhere in the file; a missing or unusable cross-reference table or trailer is rebuilt by scanning the file for object headers,
object streams and trailers, and the catalog is found by its type when no trailer leads to it; a wrong stream Length is
recovered from endstream (or endobj), without changing the Length entry; a missing endobj ends the
object at the next keyword.
Objects load lazily through the cross-reference table (§7.5.4: it "permits random access to indirect objects ... so that the entire PDF file need not be read"), are parsed once, and are kept: every reference to an object resolves to the same instance. A file opened from a path is memory-mapped and a seekable stream is read in place, so memory grows with the objects used, not with the file: stream data stays in the file and is read each time it is asked for (EncodedData). A 2 GiB file opens and reads its last page in a few megabytes of managed memory. A non-seekable stream is copied when opened.
Concurrency contract. While nobody mutates the document, any number of threads may read it at the same time: resolve objects, walk pages, decode streams, read diagnostics, render. Each object is still parsed once, and every thread sees the same instance. Mutation (changing a COS object reachable from the document) is single-threaded and the caller's responsibility to synchronize: no read may run while a mutation runs, and reading concurrently with a mutation is undefined. Disposing the document while another thread reads it is a caller error too; reads after Dispose() throw .
kind:method, kind:property, kind:ctor. Press Esc to clear.AcroFormGets the document's interactive form, or null when the catalog has no AcroForm dictionary.AdditionalActionsGets the document's additional actions (AA, PDF 1.4): scripts run before and after closing, saving and printing; null when absent.AssociatedFilesGets the files associated with the whole document (the catalog's AF).CachedBytesGets the bytes the document's render caches hold right now, all four together, without allocating.CacheStatisticsGets the counters of the document's render caches as they are now: decoded content, decoded images and masks, glyph outlines and display lists, each with its budget, the bytes and entries it holds, the most bytes it has held, and its hits, misses and evictions.CatalogGets the document catalog dictionary, the root of the document's object hierarchy.CatalogVersionGets the catalog's Version entry, or null when it has none (or none that is a version).CollectionGets the document's portable collection (Collection), or null when it is not a portfolio.DeclarationsGets the PDF Declarations of the whole document, from the XMP of the catalog's Metadata.DiagnosticsGets the deviations found so far, in the order they were found. Empty for a well-formed file.EmbeddedFilesGets the document's embedded files: the entries of the name dictionary's EmbeddedFiles tree, in tree order.ExtensionsGets the developer extensions the document declares (Extensions), in the order written; empty when none.FileIdentifierGets the file identifier (the trailer's ID), or null when the trailer has none or it is not two strings.HeaderVersionGets the version the file header states, or null when the header has no valid version.InformationGets the document information dictionary (the trailer's Info), or null when the document has none.IsEncryptedGets a value indicating whether the document is encrypted (its trailer's Encrypt entry is an encryption dictionary).IsLinearizedGets a value indicating whether the file is linearized: it starts with a linearization parameter dictionary whose file length (L) is the length of the file.LanguageGets the natural language of the document's text (Lang), such as en-US, or null when unknown.LinearizationGets the linearization information when the file starts with a valid linearization parameter dictionary, whether or not the file is still linearized (IsLinearized); otherwise null.MarkInfoGets the document's mark information: whether it is a tagged PDF (Marked) and which conventions it uses.MetadataGets the document's metadata stream (the catalog's Metadata), or null when the document has none.NamesGets the document's name dictionary, or null when the catalog has none.OpenActionGets the action performed when the document is opened (OpenAction as an action dictionary), or null when the entry is absent or is a destination (see OpenDestination).OpenDestinationGets the destination shown when the document is opened (OpenAction as a destination array), or null when the entry is absent or is an action (see OpenAction): the top of the first page.OptionalContentGets the document's optional content (layers), or null when the catalog has no OCProperties.OutlineGets the document outline (bookmarks), or null when the catalog has none.OutputIntentsGets the document's output intents (OutputIntents, PDF 1.4), in the order written; empty when it has none.PageLabelsGets the page labels (PageLabels, PDF 1.3), or null when the catalog has none: pages are then numbered from 1.PageLayoutGets how a viewer lays the pages out when the document opens (PageLayout). Default SinglePage.PagesGets the pages, in page order. The page tree is read on first use.PermissionsGets the operations the document permits: All when it is not encrypted or was opened with the owner password, otherwise those its security handler grants.PropertiesGets the common document properties, each from the XMP metadata when it has it and from the Info dictionary otherwise.RequirementsGets the requirements the document places on an interactive processor (Requirements, PDF 1.7); empty when none.RevisionsGets the revisions of the file, oldest first: the original file, then one per incremental update.SecurityGets how the document is encrypted and what the credential that opened it allows, or null when it is not encrypted.StructureTreeGets the root of the document's structure tree, or null when the document has none.TrailerGets the trailer dictionary: the newest trailer, with entries only older trailers hold filled in.UriBaseGets the base URI relative URI actions are resolved against (the catalog's URI dictionary's Base, PDF 1.1), or null when there is none or it is not an absolute URI (with a diagnostic).VersionGets the version of the specification the document conforms to: the header's version, or the catalog's Version entry when that is later.ViewerPreferencesGets the viewer preferences (ViewerPreferences), or null when the catalog has none: the viewer's own preferences then apply.AddAssociatedFile(CosDictionary, PdfFileSpecification)Associates file with owner by adding it to the owner's AF array.AddEmbeddedFile(String, PdfFileSpecification)Lists file in the document's EmbeddedFiles name tree under name.AddEmbeddedFile(String, ReadOnlySpan<Byte>, PdfEmbeddedFileOptions?)Embeds contents (see CreateEmbeddedFile(String, ReadOnlySpan<Byte>, PdfEmbeddedFileOptions?)) and lists the new file in the document's EmbeddedFiles name tree under fileName.AddObject(CosObject)Makes value a new indirect object of the document and returns the reference to it: the next object number the file does not use and no reference in it names, generation 0.AddValidationData(Stream, PdfSignatureValidationOptions?)Adds the validation data of every signature and document timestamp (their certificate chains, OCSP responses and CRLs) to the document security store and writes the document, with an incremental update holding it, to stream.AddValidationDataAsync(Stream, PdfSignatureValidationOptions?, CancellationToken)Adds the validation data of every signature to the document security store and writes the document to stream, as AddValidationData(Stream, PdfSignatureValidationOptions?) does, fetching and writing asynchronously.AppendPages(PdfDocument, Range)Appends the pages of source that pages selects to this document, with the outline items, named destinations, form fields and page labels that belong to them.AppendPages(PdfDocument)Appends every page of source to this document, with its outline, named destinations, form fields and page labels.AutoTag()Tags an untagged document from its detected layout tree.AutoTag(AutoTaggingOptions)Tags a document from its detected layout tree, with options.ConvertToPdfA(PdfAConformance)Converts the document to a PDF/A level (issue #229): changes what the level forbids that can be fixed, embeds the fonts it does not embed, and reports what it cannot fix. Save with CreateSaveOptions() to write the result; the save adds the output intent and the XMP identification, and identifies the file only when it conforms.Create()Creates a new document with one empty US Letter page (612 by 792 points), with default options.Create(PdfOptions)Creates a new document with one empty US Letter page (612 by 792 points).CreateAcroForm()Gives the document an interactive form with no fields and default resources, and returns it.CreateAxialShading(PathPoint, PathPoint, IReadOnlyList<PdfGradientStop>, PdfShadingOptions?)Creates an axial shading (Type 2) that blends between gradient stops along the line from start to end.CreateAxialShading(PathPoint, PathPoint, IReadOnlyList<PdfGradientStop>)Creates an axial shading (Type 2) that blends between gradient stops along the line from start to end.CreateAxialShading(PdfColorSpace, PathPoint, PathPoint, PdfFunction, PdfShadingOptions?)Creates an axial shading (Type 2) coloured by a function of the caller's along the line from start to end.CreateAxialShading(PdfColorSpace, PathPoint, PathPoint, PdfFunction)Creates an axial shading (Type 2) coloured by a function of the caller's along the line from start to end.CreateDestination(PdfPage, PdfDestinationView, Nullable<Double>, Nullable<Double>, Nullable<Double>, Nullable<Double>, Nullable<Double>)Creates an explicit destination showing page as view says.CreateDeviceNColorSpace(IReadOnlyList<String>, PdfColorSpace, PdfFunction)Creates a DeviceN colour space with a tint transform of the caller's, or returns the one this document already has for the same values.CreateDeviceNColorSpace(IReadOnlyList<String>, IReadOnlyList<PdfColor>)Creates a DeviceN colour space whose colourants look like alternateColors at full tint, or returns the one this document already has for the same values.CreateEmbeddedFile(String, ReadOnlySpan<Byte>, PdfEmbeddedFileOptions?)Embeds contents as a new embedded file stream and returns a new file specification for it, attached to nothing yet.CreateExponentialFunction(ReadOnlySpan<Double>, ReadOnlySpan<Double>, Double)Creates an exponential interpolation function of one input over the domain 0 to 1.CreateFormXObject(PdfRectangle)Creates an empty form XObject that a PdfCanvas can draw on and draw.CreateFunctionShading(PdfColorSpace, PdfFunction, PdfRectangle, Matrix, PdfShadingOptions?)Creates a function-based shading (Type 1): the colour of every point (x, y) of domain is the function's value there.CreateFunctionShading(PdfColorSpace, PdfFunction, PdfRectangle, Matrix)Creates a function-based shading (Type 1): the colour of every point (x, y) of domain is the function's value there.CreateGradientFunction(IReadOnlyList<PdfGradientStop>)Creates a function of one input over 0 to 1 that blends between gradient stops.CreateIccBasedColorSpace(ReadOnlySpan<Byte>)Creates an ICCBased colour space from an ICC profile, or returns the one this document already has for the same profile.CreateImage(ReadOnlySpan<Byte>, PdfImageLayout, PdfImageCompression)Creates an image XObject from a buffer of samples, or returns the one this document already has for the same samples.CreateImage(ReadOnlySpan<Byte>, ReadOnlySpan<Byte>, PdfImageLayout, PdfImageCompression)Creates an image XObject with a soft mask from buffers of samples and alpha, or returns the one this document already has for the same buffers.CreateImageFromJpeg(ReadOnlySpan<Byte>)Creates an image XObject from a JPEG file, passed through unchanged, or returns the one this document already has for the same file.CreateImageFromPng(ReadOnlySpan<Byte>)Creates an image XObject from a PNG file, or returns the one this document already has for the same file.CreateIndexedColorSpace(PdfColorSpace, ReadOnlySpan<Byte>)Creates an Indexed colour space over baseSpace, or returns the one this document already has for the same table.CreateMeshShading(PdfFreeFormMeshBuilder, PdfShadingOptions?)Creates a free-form triangle mesh shading (Type 4) from a builder's triangles.CreateMeshShading(PdfFreeFormMeshBuilder)Creates a free-form triangle mesh shading (Type 4) from a builder's triangles.CreateMeshShading(PdfLatticeMeshBuilder, PdfShadingOptions?)Creates a lattice-form triangle mesh shading (Type 5) from a builder's rows.CreateMeshShading(PdfLatticeMeshBuilder)Creates a lattice-form triangle mesh shading (Type 5) from a builder's rows.CreateMeshShading(PdfPatchMeshBuilder, PdfShadingOptions?)Creates a Coons (Type 6) or tensor-product (Type 7) patch mesh shading from a builder's patches.CreateMeshShading(PdfPatchMeshBuilder)Creates a Coons (Type 6) or tensor-product (Type 7) patch mesh shading from a builder's patches.CreateNameTree(IEnumerable<KeyValuePair<CosString, CosObject>>)Builds a new name tree holding entries, balanced, with every node a new indirect object.CreateNumberTree(IEnumerable<KeyValuePair<Int32, CosObject>>)Builds a new number tree holding entries, balanced, with every node a new indirect object.CreateOptionalContentGroup(String, Boolean)Creates an optional content group (a layer) named name.CreateOptionalContentMembership(PdfVisibilityExpression)Creates an optional content membership dictionary whose visibility expression decides.CreateOptionalContentMembership(IEnumerable<PdfOptionalContentGroup>, PdfVisibilityPolicy)Creates an optional content membership dictionary: content visible according to policy over groups.CreateOutline()Creates a new, empty outline and makes it the document's, replacing any outline the catalog has.CreatePageLabels()Creates new page labels that number every page in decimal from 1, replacing any the catalog has.CreatePostScriptFunction(ReadOnlySpan<Double>, ReadOnlySpan<Double>, String)Creates a PostScript calculator function.CreateRadialShading(PathPoint, Double, PathPoint, Double, IReadOnlyList<PdfGradientStop>, PdfShadingOptions?)Creates a radial shading (Type 3) that blends between gradient stops from one circle to another.CreateRadialShading(PathPoint, Double, PathPoint, Double, IReadOnlyList<PdfGradientStop>)Creates a radial shading (Type 3) that blends between gradient stops from one circle to another.CreateRadialShading(PdfColorSpace, PathPoint, Double, PathPoint, Double, PdfFunction, PdfShadingOptions?)Creates a radial shading (Type 3) coloured by a function of the caller's from one circle to another.CreateRadialShading(PdfColorSpace, PathPoint, Double, PathPoint, Double, PdfFunction)Creates a radial shading (Type 3) coloured by a function of the caller's from one circle to another.CreateSeparationColorSpace(String, PdfColor)Creates a Separation colour space whose full tint looks like alternateColor, or returns the one this document already has for the same values.CreateSeparationColorSpace(String, PdfColorSpace, PdfFunction)Creates a Separation colour space with a tint transform of the caller's, or returns the one this document already has for the same values.CreateShadingPattern(PdfShading, Nullable<Matrix>)Creates a shading pattern (PatternType 2): a shading used as a colour, filling or stroking with it.CreateSoftMask(PdfSoftMaskType, PdfFormXObject, IReadOnlyList<Double>?, PdfFunction?)Creates a soft-mask dictionary whose mask values come from a transparency group XObject, or returns the one this document already has for the same values.CreateStructureTree()Gives the document an empty structure tree and marks it as a tagged PDF.CreateTilingPattern(PdfRectangle, Double, Double, PdfTilingPaintType, Nullable<Matrix>, PdfTilingType)Creates a tiling pattern (PatternType 1) with an empty cell; draw the cell with CreateCanvas().DecodeStream(CosStream, IBufferWriter<Byte>)Decodes the data of stream through the filters its Filter entry names into output.DecodeStream(CosStream)Returns the data of stream decoded through the filters its Filter entry names.EmbedFont(FontQuery)Embeds the program the document's font resolvers find for query, as EmbedFont(ReadOnlyMemory<Byte>, Int32) does.EmbedFont(ReadOnlyMemory<Byte>, Int32)Embeds a TrueType, OpenType, CFF or Type 1 program a PdfCanvas of this document can show any text its glyphs cover with, subset to the glyphs shown.EmbedTrueTypeFont(FontQuery)Embeds the TrueType program the document's font resolvers find for query, as EmbedTrueTypeFont(ReadOnlyMemory<Byte>, Int32) does.EmbedTrueTypeFont(ReadOnlyMemory<Byte>, Int32)Embeds a TrueType program a PdfCanvas of this document can show any text its glyphs cover with, subset to the glyphs shown.EncodeStream(CosStream, ReadOnlySpan<Byte>, CompressionLevel)Replaces the data of stream with data encoded through the filters its Filter entry names, so that DecodeStream(CosStream) gives data back.EnumerateAssociatedFiles(Boolean)Enumerates every associated file of the document with the object it is associated with.EnumerateObjectMetadata(Boolean)Enumerates every object-level metadata stream of the document with the object it describes.ExtractLayout()Builds the document's layout tree: its logical content over every page, from the structure tree when the document is tagged.ExtractLayout(LayoutOptions)Builds the document's layout tree with options.ExtractPages(Range)Creates a new document holding the pages of this document that pages selects.Flatten()Flattens the form's fields into the page content and removes the form, as Flatten(PdfFlattenOptions) does with default options.Flatten(PdfFlattenOptions)Flattens the form's fields, and optionally every annotation, into the page content: each one's normal appearance becomes part of its page, and the widgets, the annotations and the interactive form are removed.GetAction(CosObject?, CosReference?)Reads an action dictionary through the typed view of its type.GetAnnotationAdditionalActions(CosObject?, CosReference?)Reads an annotation's additional-actions dictionary (its AA entry).GetColorConverter(PdfColorSpace, ColorConversion, PdfDefaultColorSpaces?)Returns the converter from source under conversion.GetColorConverter(PdfColorSpace, PdfDefaultColorSpaces?)Returns the converter from source to RGB with the relative colorimetric intent.GetColorConverter(PdfColorSpace)Returns the converter from source to RGB with the relative colorimetric intent and no default spaces.GetColorSpace(CosObject)Returns the colour space a colour space value describes.GetDefaultColorSpaces(CosDictionary?)Returns the default colour spaces of a resource dictionary.GetFieldAdditionalActions(CosObject?, CosReference?)Reads a form field's additional-actions dictionary (its AA entry, PDF 1.3).GetFileSpecification(CosObject?)Returns a view over a file specification held by value, resolving it first.GetFont(CosObject?)Returns the font view over a font dictionary of this document.GetFunction(CosObject)Returns the view of a function object of this document.GetImage(CosObject?)Returns the image view over an image XObject of this document.GetNamedDestination(CosName)Looks up the destination a name object names (PDF 1.1).GetNamedDestination(CosString)Looks up the destination a byte string names (PDF 1.2).GetNamedDestination(String)Looks up the destination a name (PDF 1.1) or string (PDF 1.2) names, as text.GetNameTree(CosObject?)Returns a view of the name tree whose root node is root.GetNumberTree(CosObject?)Returns a view of the number tree whose root node is root.GetPattern(CosObject)Returns the resolved model of a pattern of this document.GetShading(CosObject)Returns the resolved model of a shading of this document.GetStandard14Font(Standard14Font)Returns a non-embedded Standard 14 font a PdfCanvas of this document can show text with, adding its font dictionary the first time.Merge(IEnumerable<PdfDocument>)Creates a new document holding the pages of sources, in order, with their outlines, named destinations, form fields and page labels.Open(Stream, PdfOptions)Opens the PDF file held by stream, from its current position.Open(Stream)Opens the PDF file held by stream, from its current position, with default options.Open(ReadOnlyMemory<Byte>, PdfOptions)Opens the PDF file held in bytes.Open(ReadOnlyMemory<Byte>)Opens the PDF file held in bytes with default options.Open(String, PdfOptions)Opens the PDF file at path.Open(String)Opens the PDF file at path with default options.OpenAsync(Stream, PdfOptions, CancellationToken)Opens the PDF file held by stream, from its current position; a non-seekable stream is read asynchronously.OpenAsync(Stream, PdfOptions)Opens the PDF file held by stream, from its current position; a non-seekable stream is read asynchronously.OpenAsync(Stream, CancellationToken)Opens the PDF file held by stream, from its current position, with default options; a non-seekable stream is read asynchronously.OpenAsync(Stream)Opens the PDF file held by stream, from its current position, with default options; a non-seekable stream is read asynchronously.OpenAsync(HttpClient, Uri, PdfOptions, CancellationToken)Opens the remote PDF file at uri through HTTP range requests.OpenAsync(HttpClient, Uri, PdfOptions)Opens the remote PDF file at uri through HTTP range requests.OpenAsync(HttpClient, Uri, CancellationToken)Opens the remote PDF file at uri through HTTP range requests.OpenAsync(HttpClient, Uri)Opens the remote PDF file at uri through HTTP range requests.ReadAssociatedFiles(CosDictionary, CosReference?)Returns the associated files listed in the AF entry of owner.ReadMarkedContentAssociatedFiles(CosObject?)Returns the associated files of a marked-content sequence, from the property list of its /AF tag.RemoveAssociatedFile(CosDictionary, PdfFileSpecification)Removes file from owner's AF array.RemoveEmbeddedFile(String)Removes the entries of the document's EmbeddedFiles name tree whose key decodes to name.RemoveNamedDestination(CosString)Removes the named destination name, compared byte by byte.RemoveNamedDestination(String)Removes the named destination name.RemoveObject(CosReference)Removes the indirect object reference names from the document.Resolve(CosObject?)Returns value, or the indirect object it refers to when it is a CosReference.Save(Stream, PdfSaveOptions)Writes the document to stream as a complete file.Save(Stream)Writes the document to stream as a complete file with a classic cross-reference table.Save(String, PdfSaveOptions)Writes the document to the file at path, replacing it.Save(String)Writes the document to the file at path, replacing it, with a classic cross-reference table.SaveAsync(Stream, PdfSaveOptions?, CancellationToken)Writes the document to stream as a complete file, writing asynchronously.SetNamedDestination(CosString, PdfExplicitDestination)Gives destination the byte-string name name in the name dictionary's Dests tree.SetNamedDestination(String, PdfExplicitDestination)Gives destination the name name in the name dictionary's Dests tree.Sign(Stream, IPdfSigner, PdfSignatureOptions?)Signs the document and writes the signed file to stream: the document's file followed by an incremental update holding the signature, whose byte ranges cover the whole file except the signature value.SignAsync(Stream, IPdfSigner, PdfSignatureOptions?, CancellationToken)Signs the document and writes the signed file to stream, signing and writing asynchronously.Split(IEnumerable<Range>)Splits the document into one new document per range of pages.Timestamp(Stream, PdfTimestampClient, String?)Time-stamps the whole document and writes the time-stamped file to stream: the document's file followed by an incremental update holding a document timestamp, whose byte ranges cover the whole file except the token.TimestampAsync(Stream, PdfTimestampClient, String?, CancellationToken)Time-stamps the whole document and writes the time-stamped file to stream, asynchronously.TrimCaches(Int64)Drops the least recently used entries of the render caches until they hold at most maxBytes together: decoded content first (only builds read it), then images, glyph outlines and, last, display lists. Nothing is disposed; a dropped entry is rebuilt at its next use and renders the same.ValidateSignatures(PdfSignatureValidationOptions?)Validates every signature of the document: for each signed signature field, the byte range, the digest of the bytes it covers, the CMS signature value, its time-stamp token, and the signer's certificate path to the trust anchors options gives, with the revocation of each certificate.ValidateSignaturesAsync(PdfSignatureValidationOptions?, CancellationToken)Validates every signature of the document as ValidateSignatures(PdfSignatureValidationOptions?) does, fetching revocation data (when OnlineRevocationClient is set) asynchronously.