PDFiumPas Docs

Document Collection and RichMedia assets

FPdfDocumentAssets reads and writes document-level Collection data, catalog and page Associated Files (/AF), and discovers RichMedia file specifications without requiring PDFium, VCL or LCL

ReadPdfDocumentPortfolio returns the TPdfPortfolio model for a catalog Collection; a document without a Collection succeeds with FoundPortfolio False and an empty model

WritePdfDocumentPortfolio returns an independent PDF byte array containing the supplied schema, embedded-file index, item values, folder hierarchy (/Folders) and item-to-folder parent binding (FolderID / filespec /P), split presentation (/Split), collection color palette (/Colors), view, sort direction, initial document and item-level /AFRelationship associated-file links; source bytes and the seekable source stream position remain unchanged

ReadPdfDocumentAssociatedFiles and WritePdfDocumentAssociatedFiles read and write PDF 2.0 / PDF/A-3 Associated Files (/AF, ISO 32000-2 ยง14.13) attached to the document catalog (pafsCatalog), individual pages (pafsPage), structure elements (pafsStructureElement), page annotations (pafsAnnotation) or page XObject resources (pafsXObject) without requiring a catalog /Collection

For pafsXObject, reading and writing use the nearest effective page resource dictionary. A page-local dictionary, including an empty dictionary, replaces the inherited resources

DiscoverPdfDocumentRichMedia reads annotation asset name trees, configuration instance assets and activation script resources; it reports external file specifications without opening files, fetching URLs, playing media or executing scripts, while WritePdfDocumentRichMedia writes /Subtype /RichMedia annotations with /RichMediaContent and /RichMediaSettings dictionaries to target pages

Portfolio model and supported serialization

Collection fields retain Name, DisplayName, FieldType, Order, Visible and Editable; field subtypes cover text, number, date, filename, description, size, modification date and creation date

Each item carries a name-tree Key independently of FileName, plus Description, optional FolderID (written as /P on the filespec pointing to the matching folder object in /Collection /Folders), optional AFRelationship (written as /AFRelationship on the filespec and registered in catalog /AF when non-empty), EmbeddedData, MimeType, CreationDate, ModificationDate and IsExternal; an empty Key uses FileName during writing, while an external item must have empty EmbeddedData

Custom Values use schema field names and typed PDF numbers or text/date strings; Prefix preserves a Collection subitem display prefix; builtin file-related columns use the item's file specification or embedded-file parameters rather than custom CI values

Number strings use PDF decimal syntax and reject exponent notation; date strings are preserved literally without date normalization or standards certification

InitialDocument identifies an embedded-file Key, and View selects ppvDetails, ppvTiles or ppvHidden; when HasSplit is True, SplitDirection (ppsdNone, ppsdHorizontal, ppsdVertical) and SplitPosition (percentage 0..100) serialize and read back the /Collection /Split dictionary; when HasColors is True, BackgroundColor, CardBackgroundColor, CardBorderColor, PrimaryTextColor and SecondaryTextColor (24-bit RGB $RRGGBB) serialize and read back the /Collection /Colors dictionary; when Folders carries entries, the hierarchical /Collection /Folders tree (/ID, /Name, /Parent, /Child, /Next, optional /Desc, /CreationDate, /ModDate and /CI values) is emitted and read back with cycle detection; SortFields carries the ordered sort keys (each name must identify a schema field with its own direction) and readers accept both scalar and array /Sort forms in any count, while SortField and SortAscending stay as the mirror of the first key and are ignored on write while SortFields carries entries

The supported model has one sort field; a single-element sort array is accepted, while multiple sort keys, unknown field subtypes and missing schema/initial-document references are rejected rather than flattened into a partial model

Text decoding supports PDFDocEncoding and UTF-16 strings with validated surrogate pairs; output uses ASCII literals or UTF-16BE strings, and schema name tokens use escaped UTF-8 bytes

Replacement and document integrity

ReplaceExistingAssets defaults to False; replacing an existing Collection or EmbeddedFiles name-tree index requires setting it True

Replacement installs the supplied complete model, preserving other name-tree categories and catalog entries; it does not merge unknown Collection extensions or arbitrary filespec keys into the supplied model

Output appends a fresh active revision and raises an older effective PDF version to 1.7 without downgrading newer documents; previous revisions and any separately referenced associated files remain in the output, so replacement is not secure deletion

Encrypted inputs require a separately decrypted source; read-only discovery can inspect signed inputs, while writing rejects signature dictionaries and signature fields

RichMedia provenance

TPdfDocumentRichMediaAsset contains zero-based PageIndex and AnnotationIndex, filespec FileSpecObjectNumber and FileSpecGeneration, the embedded StreamObjectNumber and the existing TPdfRichMediaAsset in Asset; a direct filespec or external resource can have zero object numbers

Asset name-tree aliases are retained; configuration and script references already present in the annotation's inventory are deduplicated; content shared across annotations produces separate provenance records

ActivationCondition preserves the annotation condition with XA as its default; DefaultView uses the activation view or first content view and returns its external or internal name when available

Instance assets outside the Assets name tree are included, consistent with the ISO 32000-2 multimedia errata; resources are read as data only

Embedded files use the bounded general stream decoder and require every filter to be decoded successfully; unsupported codecs, cyclic trees and budget failures discard the complete asset array

Returned resources can be passed to ExtractPdfRichMediaAssets after selecting the desired names and annotation scope; that helper enforces its own safe output-name policy and does not overwrite existing files

Limits and results

TPdfDocumentAssetOptions.Default initializes ReadOptions from TPdfActiveObjectReadOptions.Default, including its 256 MiB source and total-object limits, 64 MiB object/object-stream limits and 1,000,000 object-number limit

Additional defaults are MaxItems 10000, MaxFields 256, MaxPages 10000, MaxTreeNodes 10000, MaxDepth 64, MaxStringCharacters 1048576, MaxAssetBytes 64 MiB, MaxTotalAssetBytes 256 MiB, MaxOutputBytes 512 MiB and MaxWork 16777216

Valid maxima are 100000 items/pages, 4096 fields, 1000000 tree nodes, depth 128, 16777216 string characters, 512 MiB per asset, MaxInt total/output bytes and 268435456 work units; all limits must be positive and ReadOptions retains its own validation

MaxAssetBytes bounds both raw and decoded embedded-stream staging; MaxWork counts bounded traversal, lookup and model operations, and parser-wide allocation, expansion-ratio and deadline budgets still apply

CancellationToken is optional and is polled between parsing and staging operations; stream decompression is synchronous and does not promise interruption inside an individual decoder call

TPdfDocumentAssetReport returns Succeeded, Cancelled, FoundPortfolio, ItemCount, FieldCount, AssetCount, SourceByteCount, OutputByteCount and ErrorMessage; False clears every returned model, byte array and asset inventory, with the rejection reason in ErrorMessage

Example

Options := TPdfDocumentAssetOptions.Default;
if not ReadPdfDocumentPortfolio(Source, Options, Portfolio, Report) then
  raise Exception.Create(Report.ErrorMessage);

Options.ReplaceExistingAssets := True;
Portfolio.View := ppvDetails;
if not WritePdfDocumentPortfolio(Source, Portfolio, Options, OutputPdf, Report) then
  raise Exception.Create(Report.ErrorMessage);

Public declarations

type
  TPdfDocumentAssetOptions= record
    ReadOptions: TPdfActiveObjectReadOptions;
    MaxItems, MaxFields, MaxPages, MaxTreeNodes, MaxDepth: Integer;
    MaxStringCharacters, MaxAssetBytes: Integer;
    MaxTotalAssetBytes, MaxOutputBytes, MaxWork: Int64;
    ReplaceExistingAssets: Boolean;
    CancellationToken: IPdfCancellationToken;
    class function Default: TPdfDocumentAssetOptions; static;
  end;
  TPdfDocumentAssetReport= record
    Succeeded, Cancelled, FoundPortfolio: Boolean;
    ItemCount, FieldCount, AssetCount: Integer;
    SourceByteCount, OutputByteCount: Int64;
    ErrorMessage: string;
  end;
  TPdfDocumentRichMediaAsset= record
    PageIndex, AnnotationIndex: Integer;
    FileSpecObjectNumber, FileSpecGeneration, StreamObjectNumber: Integer;
    Asset: TPdfRichMediaAsset;
  end;
  TPdfDocumentRichMediaAssets= array of TPdfDocumentRichMediaAsset;
  TPdfAssociatedFileScope= (pafsCatalog, pafsPage, pafsStructureElement,
    pafsAnnotation, pafsXObject);
  TPdfDocumentAssociatedFile= record
    Scope: TPdfAssociatedFileScope;
    PageIndex, AnnotationIndex, TargetObjectNumber: Integer;
    ElementID, ResourceName: string;
    Key, FileName, Description, AFRelationship, MimeType: string;
    CreationDate, ModificationDate: string;
    EmbeddedData: TBytes;
    IsExternal: Boolean;
    FileSpecObjectNumber, FileSpecGeneration, StreamObjectNumber: Integer;
  end;
  TPdfDocumentAssociatedFiles= array of TPdfDocumentAssociatedFile;

function ReadPdfDocumentPortfolio(Source: TStream;
  const Options: TPdfDocumentAssetOptions; out Portfolio: TPdfPortfolio;
  out Report: TPdfDocumentAssetReport): Boolean;
function WritePdfDocumentPortfolio(Source: TStream; const Portfolio: TPdfPortfolio;
  const Options: TPdfDocumentAssetOptions; out OutputPdf: TBytes;
  out Report: TPdfDocumentAssetReport): Boolean;
function DiscoverPdfDocumentRichMedia(Source: TStream;
  const Options: TPdfDocumentAssetOptions; out Assets: TPdfDocumentRichMediaAssets;
  out Report: TPdfDocumentAssetReport): Boolean;
function WritePdfDocumentRichMedia(Source: TStream;
  const Assets: TPdfDocumentRichMediaAssets;
  const Options: TPdfDocumentAssetOptions; out OutputPdf: TBytes;
  out Report: TPdfDocumentAssetReport): Boolean;
function ReadPdfDocumentAssociatedFiles(Source: TStream;
  const Options: TPdfDocumentAssetOptions;
  out AssociatedFiles: TPdfDocumentAssociatedFiles;
  out Report: TPdfDocumentAssetReport): Boolean;
function WritePdfDocumentAssociatedFiles(Source: TStream;
  const AssociatedFiles: TPdfDocumentAssociatedFiles;
  const Options: TPdfDocumentAssetOptions; out OutputPdf: TBytes;
  out Report: TPdfDocumentAssetReport): Boolean;

Collection dictionaries follow ISO 32000-1, tables 155 through 159; the API exposes the supported model above without claiming preservation of every optional extension