type TPdfStreamInspector = class ... end;
| Constructor | Description |
|---|---|
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 |
| Method | Description |
|---|---|
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 |
Version 3.336.2 makes the common PdfReadAndDecodeStream pure-Flate helper honour 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 normalisation 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 normalisation. 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 honours lower parser depth, token, allocation and deadline limits. Decoder acceptance of opaque extension fields is a compatibility behaviour 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 whilst 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, whilst 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. Recognised 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
| Constant | Value | Purpose |
|---|---|---|
PdfStreamInspectDefaultSourceLimit | 512 MiB | Maximum retained source size |
PdfStreamInspectDefaultRawLimit | 256 MiB | Maximum raw payload copied by one operation |
PdfStreamInspectDefaultDecodedLimit | 256 MiB | Maximum decoded payload produced by one operation |
PdfStreamInspectDefaultExpansionRatio | 100 | Maximum decoded-to-encoded expansion ratio |
PdfStreamInspectDefaultMaxStreams | 1,000,000 | Maximum stream objects inventoried |
PdfStreamInspectDefaultDictionaryLimit | 1 MiB | Maximum dictionary bytes inspected for one stream |
| Type | Description |
|---|---|
TPdfStreamFilterKind | Classifies filters as psfkUnknown, psfkASCIIHex, psfkASCII85, psfkLZW, psfkFlate, psfkRunLength, psfkCCITTFax, psfkJBIG2, psfkDCT, psfkJPX, psfkCrypt, psfkBrotli, or the appended psfkCryptIdentity |
TPdfStreamNativeAccess | Selects no native path, image-object access or embedded-file access |
TPdfStreamDecodeLevel | Selects raw, supported general-filter or required full-chain decoding |
TPdfStreamReadStatus | Reports psrsCompleted, psrsPartiallyDecoded, psrsInvalidIndex, psrsInvalidRange, psrsSourceLimitExceeded, psrsRawLimitExceeded, psrsDecodedLimitExceeded, psrsExpansionRatioExceeded, psrsUnsupportedFilter, psrsUnsupportedDecodeParameters, psrsEncrypted, psrsExternalData, psrsMalformed or psrsWriteError |
TPdfStreamFilterInfo | Filter name, Kind, HasDecodeParameters DecodeParms presence, Predictor, Colors, BitsPerComponent, Columns, and the LZW EarlyChange value |
TPdfStreamFilterInfos | Dynamic array of TPdfStreamFilterInfo records |
TPdfStreamInfo | Object 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 |
TPdfStreamInfos | Dynamic array of TPdfStreamInfo records |
TPdfStreamInspectOptions | Caller-selected source, payload (MaxRawBytes, MaxDecodedBytes), expansion (MaxExpansionRatio), object-count (MaxStreams), dictionary (MaxDictionaryBytes), token (MaxTokens), allocation (MaxAllocationBytes), and DeadlineMilliseconds deadline budgets with a static Default initialiser |
TPdfStreamReadReport | Status, byte counts (InputByteCount, OutputByteCount), applied and remaining filter counts (AppliedFilterCount, RemainingFilterCount), failed filter index (FailedFilterIndex), and ErrorMessage text for one read |
| Member | Type | Description |
|---|---|---|
Count | Integer | Number of physical stream objects or revisions found in the source |
Infos[Index] | TPdfStreamInfo | Object number, generation, offsets, lengths, filters, DecodeParms, and native access classification |
Encrypted | Boolean | Whether the trailer declares document encryption |
Options | TPdfStreamInspectOptions | Normalised resource budgets used by the inspector |
SourceByteCount | Int64 | Number of input bytes retained for inspection |
psdlRaw copies the encoded stream bytes without applying filterspsdlGeneral applies leading Identity Crypt, ASCIIHex, ASCII85, LZW, Flate, RunLength, TIFF predictors with 1/2/4/8/16-bit components, and PNG predictors, then returns psrsPartiallyDecoded when an image or unknown codec remainspsdlFull requires the complete chain to use supported general filters and returns psrsUnsupportedFilter otherwisepsnaImageObject directs document-level callers to the native FPDFImageObj_GetImageDataRaw, FPDFImageObj_GetImageDataDecoded and image filter APIspsnaEmbeddedFile directs attachment callers to the native FPDFAttachment_GetFile pathpsrsEncrypted, because the public native ABI does not decrypt an arbitrary indirect stream by object numberTPdfStreamInspectOptions.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 rather than switching the expansion check off
ASCIIHex, ASCII85, LZW and RunLength output buffers grow geometrically within MaxDecodedBytes, with budget checks before each write; raw input copies stay 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
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;