PDFium Delphi Component Docs

TPdfStreamInspector class

Unit: FPdfStreamInspect
Read-only bounded inventory and extraction of arbitrary physical PDF stream objects

Syntax

type TPdfStreamInspector = class ... end;

Constructors

ConstructorDescription
Create(Source: TStream)Reads a seekable PDF source under default budgets and restores its original position
Create(Source: TStream; const Options: TPdfStreamInspectOptions)Reads a seekable PDF source under caller-selected budgets
Create(const Data: TBytes)Inspects an existing PDF byte array under default budgets
Create(const Data: TBytes; const Options: TPdfStreamInspectOptions)Inspects an existing PDF byte array under caller-selected budgets

Methods

MethodDescription
CopyRawData(Index, Destination, out Report)Copies the complete encoded payload of one stream object
CopyRawData(Index, Destination, Offset, Count, out Report)Copies a validated byte window without decoding the filter chain
DecodeData(Index, Destination, Level, out Report)Returns raw data or applies supported general filters in declaration order
PdfStreamFilterKindFromName(Name)Maps a full or abbreviated PDF filter name to TPdfStreamFilterKind
ValidatePdfStreamDictionarySyntax(Dictionary)Checks one complete stream dictionary and nested values for bounded syntax, byte-canonical unique keys and forbidden decoded null names without resolving references
ParsePdfStreamFilterChain(Dictionary, out Filters, out Status)Parses one complete AnsiString stream dictionary into ordered filter records; returns an empty array on failure
DecodePdfStreamFilter(Source, Filter, Options, InitialInputBytes, out Dest, out Status, out EncodedByteCount, RequireTerminator = False)Decodes one general filter into bounded bytes, returns its available EOD byte count and clears the output on failure

Filter helper contracts

Version 3.336.2 makes the common PdfReadAndDecodeStream pure-Flate helper honor direct null Predictor/Colors/BitsPerComponent/Columns entries with the same defaults as checked inspection. Dictionary and single-item array parameters, TIFF/PNG data and malformed null suffixes are covered by the focused helper qualification; physical inspection and source-indexed reference resolution retain their existing contracts

Version 3.336.1 rejects zero and negative Predictor values in checked LZW/Flate decoding, returning psrsUnsupportedDecodeParameters with no decoded output. Only Predictor 1 selects no prediction; the supported predictor values are 1, 2 and 10 through 15 under ISO 32000-1 Table 10

Version 3.336.0 reconstructs TIFF Predictor 2 with 1, 2, 4, 8 or 16 bits per component for LZW and Flate. Differences use the same component in the preceding pixel, wrap at the component bit depth and restart on each row; 16-bit samples are big-endian and unused low row-padding bits are preserved. Complete byte-aligned rows, supported geometry and decoded-size budgets are checked before reconstruction; failed checked decoding returns no partial output

Version 3.335.0 validates the complete stream dictionary before metadata normalization and every referenced parameter dictionary before interpreting its fields. Repeated keys are rejected even when their values match or are null. Name equality expands PDF hex escapes and compares the original 8-bit bytes case-sensitively; it does not apply text encoding or Unicode normalization. Identical keys in separate dictionaries remain independent, hash collisions are compared by bytes, and decoded null bytes in names are rejected

ValidatePdfStreamDictionarySyntax performs these checks without resolving indirect references. Its hash tables store source spans, with retained ancestor tables and both old/new tables during growth charged against MaxAllocationBytes. Hashing, probing and byte comparison consume validation work under MaxTokens and the deadline; lexical depth retains the 64-level implementation ceiling and lower caller limits. This remains a syntax/unique-key check, without schema or private-name registry validation

Version 3.334.0 interprets Predictor, Colors, BitsPerComponent and Columns only for LZW/Flate, and EarlyChange only for LZW. Other parameter values remain opaque compatibility data and unused record fields retain their defaults. Active parameter dictionaries require Type to be a direct name or null; the source-indexed pipeline separately resolves Type references. This name-shape check does not verify private-name registration or complete schema conformance

Parameter values must use complete PDF object syntax: dictionary keys are names, values have balanced containers/strings, valid hex strings and numeric/reference tokens, and no unknown bare keywords or extra values. Lexical nesting is limited to 64, matching the shared object-skipping implementation limit, and also honors lower parser depth, token, allocation and deadline limits. Decoder acceptance of opaque extension fields is a compatibility behavior and does not establish Annex E registration or ISO conformance

Version 3.334.1 requires a token boundary after an indirect reference generation number, rejecting malformed adjacency such as 1 0R and 1 +0R while retaining whitespace/comment-separated references

Version 3.332.0 classifies a leading Crypt filter with a direct Identity Name, an omitted Name or a null Name as psfkCryptIdentity and passes its bytes through under the same allocation, decoded-byte and cumulative chain budgets. Optional Type must be CryptFilterDecodeParms or null; direct names accept PDF name escapes. Other crypt-filter names remain psfkCrypt and return psrsEncrypted, and a Crypt filter after another filter is rejected. Cross-reference streams reject every Crypt filter, including Identity, while raw reads remain available. Indirect Name/Type values inside Crypt parameters remain unsupported by this profile

Since v3.328.0, ParsePdfStreamFilterChain accepts a complete dictionary with direct Filter names or arrays and null or direct DecodeParms dictionaries, including comments and escaped names. Recognized integer parameters must be complete direct integers or null; indirect, fractional or trailing values return psrsUnsupportedDecodeParameters. Dictionary bytes and filter counts remain bounded by the parser policy. Unknown filter names remain classified for the decoder to report

Version 3.330.1 treats a null Filter as an omitted Filter and applies the documented defaults for null Predictor, Columns, Colors, BitsPerComponent and EarlyChange values: 1, 1, 1, 8 and 1 respectively. A null element inside a Filter name array remains invalid. Physical inspection does not resolve parameter references; source-indexed rewrite helpers additionally support revision-scoped null or undefined optional parameter references

Since v3.331.0, a direct null F entry is equivalent to omitting the external-file specification, so HasExternalFile is false and supported inline data may be decoded. Non-null or indirect F entries retain the physical inspector's external-data boundary; the source-indexed FPdfCompress pipeline can resolve permitted metadata references, including a reference that resolves to null, without opening external files

DecodePdfStreamFilter applies one filter and its predictor. Pass the original encoded stream length as InitialInputBytes at every chain stage so expansion limits retain the same anchor. Input allocation and output ceilings are separate; zero decoded allowance permits no nonempty output. Caller limits are capped by the global parser allocation, decoded-byte and expansion policies

EncodedByteCount is positive through an ASCIIHex, ASCII85, RunLength or LZW EOD marker, zero for an incomplete marker-based input, -2 for a detected invalid encoded prefix, and -1 when no endpoint is reported. A positive result can precede unused source bytes, so exact-span callers must also compare it with their expected encoded length. RequireTerminator requires EOD for those four families and additionally validates LZW initial clear codes, final zero padding and full-table resets; it does not provide exact Flate consumption or checksum qualification

Identity Crypt reports the supplied source length as EncodedByteCount, including zero for empty input; it has no intrinsic EOD marker and callers must independently validate the enclosing declared stream extent

Since v3.333.0, the source-indexed FPdfCompress pipeline can resolve optional Crypt Name/Type references against the requesting revision, including ordinary aliases and independent compressed metadata. The physical inspector and direct filter helpers keep their direct-metadata contract and do not resolve those references

DecodeData validates filter metadata before decoded reads and reports malformed or unsupported parameters instead of silently treating the payload as unfiltered or substituting integer defaults. Raw reads and CopyRawData remain available. Established ASCIIHex decoded reads still accept EOF without a closing marker; strict bootstrap callers use the helper's explicit terminator requirement

Default limits

ConstantValuePurpose
PdfStreamInspectDefaultSourceLimit512 MiBMaximum retained source size
PdfStreamInspectDefaultRawLimit256 MiBMaximum raw payload copied by one operation
PdfStreamInspectDefaultDecodedLimit256 MiBMaximum decoded payload produced by one operation
PdfStreamInspectDefaultExpansionRatio100Maximum decoded-to-encoded expansion ratio
PdfStreamInspectDefaultMaxStreams1,000,000Maximum stream objects inventoried
PdfStreamInspectDefaultDictionaryLimit1 MiBMaximum dictionary bytes inspected for one stream

Public types

TypeDescription
TPdfStreamFilterKindClassifies filters as psfkUnknown, psfkASCIIHex, psfkASCII85, psfkLZW, psfkFlate, psfkRunLength, psfkCCITTFax, psfkJBIG2, psfkDCT, psfkJPX, psfkCrypt, psfkBrotli, or the appended psfkCryptIdentity
TPdfStreamNativeAccessSelects no native path, image-object access, or embedded-file access
TPdfStreamDecodeLevelSelects raw, supported general-filter, or required full-chain decoding
TPdfStreamReadStatusReports psrsCompleted, psrsPartiallyDecoded, psrsInvalidIndex, psrsInvalidRange, psrsSourceLimitExceeded, psrsRawLimitExceeded, psrsDecodedLimitExceeded, psrsExpansionRatioExceeded, psrsUnsupportedFilter, psrsUnsupportedDecodeParameters, psrsEncrypted, psrsExternalData, psrsMalformed, or psrsWriteError
TPdfStreamFilterInfoFilter name, Kind, HasDecodeParameters DecodeParms presence, Predictor, Colors, BitsPerComponent, Columns, and the LZW EarlyChange value
TPdfStreamFilterInfosDynamic array of TPdfStreamFilterInfo records
TPdfStreamInfoObject identity (ObjectNumber, Generation, TypeName), offsets and lengths (ObjectOffset, DictionaryOffset, DictionaryLength, RawOffset, RawLength, DecodedLengthHint), layout flags (LengthIsIndirect, UsedEndStreamFallback), encryption and external-file flags (HasExternalFile, IsEncryptedDocument), type names (SubtypeName), native boundary (NativeAccess of psnaNone, psnaImageObject, or psnaEmbeddedFile), and the declared Filters chain
TPdfStreamInfosDynamic array of TPdfStreamInfo records
TPdfStreamInspectOptionsCaller-selected source, payload (MaxRawBytes, MaxDecodedBytes), expansion (MaxExpansionRatio), object-count (MaxStreams), dictionary (MaxDictionaryBytes), token (MaxTokens), allocation (MaxAllocationBytes), and DeadlineMilliseconds deadline budgets with a static Default initializer
TPdfStreamReadReportStatus, byte counts (InputByteCount, OutputByteCount), applied and remaining filter counts (AppliedFilterCount, RemainingFilterCount), failed filter index (FailedFilterIndex), and ErrorMessage text for one read

Properties

MemberTypeDescription
CountIntegerNumber of physical stream objects or revisions found in the source
Infos[Index]TPdfStreamInfoObject number, generation, offsets, lengths, filters, DecodeParms, and native access classification
EncryptedBooleanWhether the trailer declares document encryption
OptionsTPdfStreamInspectOptionsNormalised resource budgets used by the inspector
SourceByteCountInt64Number of input bytes retained for inspection

Decode levels and native boundaries

Budgets and reports

TPdfStreamInspectOptions.Default combines its source, payload, expansion, dictionary, and stream ceilings with the current TPdfParserResourceBudget token, object, decoded-byte, expansion-ratio, allocation, and deadline policy

A non-finite MaxExpansionRatio falls back to the parser policy instead of disabling the expansion check

ASCIIHex, ASCII85, LZW, and RunLength output buffers grow geometrically within MaxDecodedBytes, with budget checks before writes; raw input copies remain subject to the separate source and raw-byte limits

TPdfStreamReadReport records status, input and output byte counts, applied and remaining filters, the failed filter index, and destination write errors

The current implementation retains one bounded source copy to support reliable indirect-length resolution and repeatable random stream reads; use a lower MaxSourceBytes when processing untrusted uploads under a tighter memory budget

Example

var
  Inspector: TPdfStreamInspector;
  Output: TMemoryStream;
  Report: TPdfStreamReadReport;
begin
  Inspector := TPdfStreamInspector.Create(PdfBytes);
  Output := TMemoryStream.Create;
  try
    if Inspector.Count > 0 then
      Inspector.DecodeData(0, Output, psdlGeneral, Report);
  finally
    Output.Free;
    Inspector.Free;
  end;
end;