PDFium Delphi Component Docs

Document ICC color conversion

Set TPdfDocumentColourOptions.ImageDecoder to the optional FPdfImageComponents provider for original-component DCT/JPX decoding; CodecImagesDecoded reports actual provider use, while default nil retains unsupported-codec rejection

ConvertPdfDocumentColours reads the active PDF revision, converts original component operands and image samples through an IPdfColourTransform, and appends a coherent revision to a separate output stream

It supports text and vector fill/stroke operators in DeviceGray, DeviceRGB, DeviceCMYK and ICCBased spaces, plus CalGray, CalRGB, Lab and Indexed sources decoded through the ICC PCS Lab connection, inherited page resources, named default color-space aliases, nested Form XObjects, 8-bit inline images (BI ... ID ... EI, raw or filtered via /AHx, /A85, /Fl, /LZW or /RL) and raw or general-filter image XObjects with 8-bit or 16-bit components

Pattern color spaces convert at the paint site: stock and underlying pattern spaces select tiling and shading patterns, uncoloured tiling pattern components convert through their underlying space while the resource base is rewritten to the target profile, and coloured tiling pattern content converts recursively like a form with its own resources

Axial and radial shading dictionaries convert by resampling their colour function through the target profile (including [/Indexed ...] shading palettes whose 1-output index function and /Background index expand through the palette lookup table into the base colour space): sampled, exponential-interpolation, stitching and bounded Type 4 calculator function trees evaluate with PDFium's clamp and stitch semantics, and the result publishes as a type 0 sampled function together with the rewritten /ColorSpace and a converted /Background array

CalGray gamma, CalRGB decode matrices and Lab white points are evaluated with Bradford adaptation into the D50 PCS; Lab /Range values beyond the encodable +-128 domain are rejected, and Indexed palettes resolve inline strings or their own decoded stream objects

Indexed images accept 1, 2, 4 or 8-bit samples with an optional two-entry /Decode remap; one palette conversion covers every pixel, over a device, ICCBased or calibrated base space, while Separation or DeviceN bases follow the spot preservation policy

Since v3.307.1, each Indexed image scanline begins at a byte boundary, including sub-byte rows whose final byte contains padding; Decode interpolation clamps to the palette range and rounds to the nearest index, and expanded image bytes and calibrated palette buffers are checked against MaxDecodedStreamBytes before decoding or provider work; these global allocation failures preserve the destination in strict and partial conversion modes

Since v3.308.0, explicit PDF Indexed images can use the optional IPdfImageIndexDecoder path for one-component raw JPX or JP2 input, including general filter chains, signed/unsigned source precisions 1-16 and sampled grids; unscaled source indices select the PDF palette and clamp to hival, while internal JP2 palette/channel interpretations and JPX Decode/BitsPerComponent entries are ignored

The source index buffer uses inspected 8/16-bit storage and is budgeted before decoding, independently of the target palette expansion; calibrated Indexed bases retain their 16-bit output path; older bridges without index exports report unsupported input, and any SMaskInData, multiple encoded components, higher precision and implicit color-space selection retain their separate gates

Parsed color spaces are cached per source expression and resource context, so repeated operator selections share one palette allocation

Content arrays share one operand parser and graphics state stack with a space between streams; q/Q, color-space defaults and component counts remain tied to their original source spaces throughout conversion

CMYK operands come from the PDF content and image streams, never rendered RGB getters; provide DeviceCMYKProfile for unprofiled DeviceCMYK sources

Source ICCBased profiles are resolved from their original resource scope; only an absent or default /Range [0 1 ...] is supported, while ordinary non-JPX image /Decode arrays are applied before conversion and removed from the converted image; calibrated images convert through their own CalGray, CalRGB or Lab decode ranges and are republished as 16-bit samples

Since v3.304.0, the optional JPX bridge accepts signed and mixed-signedness equal-resolution 8/16-bit channels by normalizing each signed range into unsigned samples; explicit PDF ColorSpace overrides embedded JP2 color labels and ICC metadata, and ordinary JPX image Decode entries are ignored before either calibrated or ICC conversion; nonzero SMaskInData, unsupported channel mappings, alpha definitions, precisions above 16 and unsupported implicit color families retain their explicit limits

Since v3.305.0, zero-origin JPX channels can use independent horizontal/vertical sampling intervals from 1 through 255 with common 8/16-bit precision; source-cell replication reconstructs the complete reference-grid image before ICC conversion, including odd or nondividing edges, without obtaining a rendered RGB bitmap or inferring a YCbCr interpretation

Since v3.306.0, optional IPdfImageComponentMetadata header inspection supports actual source precisions 1 through 16, including mixed channel precisions and sampled grids; source values scale to unsigned 8-bit buffers when all channels have at most eight bits and to 16-bit buffers otherwise, independently of a missing or ignored PDF BitsPerComponent entry; since v3.357.0 the accepted source range extends to 24 bits and still decodes into the 16-bit buffer, while larger declarations reject; the explicit PDF ColorSpace remains required

Image metadata must match the PDF Width, Height and component count, decoded buffers are budgeted before codec allocation, and actual target precision is checked again before ICC conversion; calibrated images count their 16-bit target components against MaxDecodedStreamBytes, including four-component CMYK output; older bridge DLLs without metadata retain the explicit supported 8/16-bit path

Since v3.307.0, JP2 PCLR/CMAP palettes and complete color-only CDEF associations produce the logical color channels described by the explicit PDF ColorSpace; supported mappings include permuted or repeated palette columns, selected raw components and mixed direct/palette channels with signed or mixed 1-16-bit color precision; palette indices must remain in range and padding bits must be zero

Implicit JPX color declarations

Since v3.310.0, absent or null PDF ColorSpace entries can use optional IPdfImageColourMetadata declarations; supported sources are provider-compatible RGB/Gray/CMYK ICC profiles in methods 2/3, standard sRGB 16, standard-gray 17 and device CMYK 12

Declarations are considered by descending signed Precedence, then ascending Approximation, with input order retained for ties; structurally invalid, mismatched or provider-unsupported ICC choices are skipped before pixel decoding, and a later supported declaration may be selected

sRGB uses the built-in standard profile independently of DeviceRGBProfile or DefaultRGB; standard-gray uses the piecewise sRGB transfer function through neutral PCS Lab and produces 16-bit converted samples; CMYK uses the configured device profile or resolved DefaultCMYK resource

Selection is cached within one conversion, with CMYK declarations and all device fallbacks retaining resource-dependent context checks; conflicting shared source interpretations still abort strict and partial conversion before destination publication

Explicit PDF ColorSpace bypasses implicit selection; the native codec receives neutral color metadata after original declarations are inspected, leaving source interpretation with the chosen PDF or JPX declaration

Since v3.311.0, unsigned sYCC 18 reconstructs each channel at its original 1-16-bit precision before applying the precision-specific chroma midpoint and the sYCC matrix; RGB values clip to the standard range and round to the decoded 8/16-bit precision before built-in sRGB ICC conversion; mixed precisions, supported sampled grids, nonzero origins and projected palette channels use this same interpretation

T.800 Table I.10 requires unsigned channels for sYCC; a signed channel makes that declaration unavailable, so selection continues to supported lower declarations or device fallback; explicit PDF ColorSpace continues to override sYCC

AllowJpxDeviceFallback defaults to True and applies DeviceGray, DeviceRGB or DeviceCMYK after successful JPX metadata inspection finds no usable declaration, including raw codestreams and missing declarations; configured profiles and DefaultGray/DefaultRGB/DefaultCMYK resources still determine these device spaces

JpxDeviceFallbackImages counts successfully converted fallback image objects once, including shared images; set AllowJpxDeviceFallback to False to require a usable declaration for implicit images, with normal strict/partial unsupported handling; unsupported embedded profiles or other enumerated families are not accurately interpreted by component-count fallback

Fallback selections retain every Default* resource context; conflicting shared interpretations abort strict and partial conversion before destination publication; malformed/unavailable metadata, invalid channel precision or sampling, allocation failures and cancellation never become device fallback

JPX CIELab and floating PCS Lab

Since v3.312.0, CIELab 14 declarations use the original per-channel integer precision and signedness to recover T.801 nominal samples, default ranges/offsets or all seven explicit EP fields; unsigned 1-16-bit and signed 2-16-bit channels can be mixed, including supported sampled grids, nonzero origins and signed palette columns

Default L/a/b ranges are 100/170/200; offsets depend on channel precision and signedness and differ from ordinary PDF Lab Decode ranges; an EP block is either absent or contains all RL/OL/RA/OA/RB/OB/IL fields, and a zero range, incomplete block, unknown illuminant or signed one-bit zero nominal maximum makes that declaration unavailable

The declared Bradford policy adapts D50, D65, D75, SA, SC, F2, F7 and F11 standard illuminants into D50 PCS, using rounded CIE 1931 2-degree white points; D50 retains the T.42 reference, and the declared values are independently compared with official CIE spectral datasets within 0.0001 in normalized XYZ

Since v3.348.0, T.801 Table M.29 colour-temperature illuminants are accepted: the IL field holds CT followed by a 16-bit big-endian kelvin value, and its white point is the Planckian radiator at that temperature, computed with Planck's law and integrated against the CIE 1931 2-degree observer at 5 nm before normalization to Y=1 and the same Bradford adaptation; a zero or visibly underflowing temperature leaves the declaration unavailable

Colour-temperature white points are qualified against the same official observer tabulated at 1 nm within 0.0005 in normalized XYZ and against published Planckian chromaticities within 0.0002

Optional IPdfColourFloatTransform receives three native-endian IEEE 754 Single PCS Lab components in physical Lab units, preserving wider chroma before ICC conversion rather than clipping it into encoded 16-bit Lab; document output remains 16-bit, and the 12-byte-per-pixel floating workspace is checked before pixel decoding, including partial conversion mode

Providers without the optional interface can select another supported declaration or use the separately reported optional device fallback; explicit PDF ColorSpace still takes priority, and ordinary integer color conversion retains its existing interface

Integer Pixel Format boxes require complete unique channel indices and integer format entries; malformed boxes and fixed/floating reinterpretations reject before native decoding and never trigger device fallback

JPX ROMM RGB and extended sRGB

Since v3.313.0, ROMM RGB 21 uses the published unflared ROMM encoding: reconstruct original unsigned 1-16-bit or signed 2-16-bit coordinates, clip to 0..1, apply the inverse linear toe below 1/32 or the 1.8 power curve, and invert the published XYZ-to-ROMM matrix into D50 PCS Lab

Extended sRGB 20 accepts 10-, 12- and 16-bit channels, including mixed precision; each unsigned channel subtracts 3*2^(p-3) and divides by 255*2^(p-9), while signed channels use the T.801 zero-radiance and signed nominal-maximum mapping into the same precision-dependent domain

The extended sRGB path clips coordinates to that encoding domain, applies the negative/positive piecewise transfer curve, retains extended linear RGB without early clipping, and uses the PIMA 7667:2001 matrix and the declared D65-to-D50 Bradford policy before floating PCS conversion

Both families require optional IPdfColourFloatTransform and produce 16-bit target samples; supported sampled grids, image/tile origins, palette projections, color-only channel permutations and shared-image context rules are retained; unavailable or rejected floating providers continue to a usable lower declaration or the explicit device fallback policy

ROMM encoding equations do not imply an ICC profile maker's measurement flare, black-point or characterization corrections; physical spectral-locus validity, source appearance certification and advanced rendering decisions remain separate from this finite mathematical conversion profile

Encoding sources: ICC registry ROMM RGB specification, PIMA 7667:2001 extended sRGB specification and ITU-T T.801 channel mapping

Encoded-stream and general-filter decoded-stream byte overflows abort strict and partial conversion, preserving source position and the destination; they cannot be downgraded to an unsupported object or published as a partial document

JPX extended sYCC and linear scRGB

Since v3.314.0, extended sYCC 24 reconstructs each original unsigned 1-16-bit or signed 2-16-bit channel, uses its luma nominal maximum and chroma midpoint, and applies the PIMA 7667:2001 B9 matrix, including the negative blue cross-term

The resulting continuous extended RGB values pass through the negative/positive extended sRGB transfer and explicit matrix into floating PCS Lab; there is no intermediate RGB integer requantization or ordinary 0..1 clipping; this path differs from the ordinary unsigned sYCC 18 conversion

scRGB 25 and scRGB Gray 26 accept 16-bit integer channels; unsigned samples decode as code/8192 - 0.5, retaining the linear -0.5..7.4998779296875 range; signed channels use the T.801 zero-radiance and nominal-maximum mapping, with coordinates clipped to that encoding range

scRGB uses the IEC 61966-2-2 RGB-to-XYZ matrix; scRGB Gray places its luminance on the D65 neutral axis; both retain negative and above-white values through the declared D65-to-D50 Bradford adaptation and optional floating PCS provider, producing 16-bit target output

Extended sYCC supports mixed channel precisions; all three paths retain supported signed/unsigned samples, sampled origins/tiles, palette projections, explicit PDF ColorSpace priority and declaration/provider fallback behavior; the complete floating workspace is checked before pixel decoding, including for single-channel Gray and partial conversion

scRGB-nl is a separate nonlinear encoding and is not inferred from a 12-bit scRGB declaration; encoded fixed/floating pixel formats and scene-to-output appearance or tone-mapping decisions remain separate from these integer mathematical conversions

scRGB sources: ICC registry scRGB encoding characteristics and IEC 61966-2-2:2003 preview, sections 4.2-4.3

JPX YPbPr(1125/60) and YPbPr(1250/50)

Since v3.350.0, enumerated colour spaces 22 and 23 accept three equal-precision unsigned channels of 8 or 10 bits; signature, mixed-precision, other-precision and non-three-channel declarations remain unavailable and continue to a lower declaration or the explicit device fallback policy

Codes recover the nominal studio levels from the declared precision, so Y uses the 16-to-235 black and peak codes while Pb/Pr use the 128 achromatic level with a 112 step; 10-bit declarations scale those levels by four

YPbPr(1125/60) applies the BT.709 luma coefficients (0.2126/0.0722) and YPbPr(1250/50) the 0.299/0.114 pair; the coded RGB values pass through the BT.709 inverse transfer into linear light before the declared D65 matrix and the same Bradford adaptation used by the other calibration spaces

Values outside the studio ranges are not rejected; after reconstruction each channel clips to the unit interval, matching the sYCC policy, and the result feeds the shared 16-bit PCS Lab path

Encoded fixed/floating pixel formats, CIEJab 19 and other enumerated families, component registration offsets, and alpha or premultiplied channels on these enumerated declarations remain separate gates; 17-24-bit sources and embedded opacity are qualified separately by the original JPX channel profiles, not by the enumerated conversions here; floating PCS transport does not imply floating JPX sample decoding, and header inspection does not establish full stream validity

Since v3.309.0, nonzero JPX image and tile origins use image-area Width/Height spans and retain absolute component sampling phase; first-source-sample extension covers leading unsampled positions, consistently across original colors, JP2 palettes and explicit Indexed conversion; output coordinates remain local to the PDF image and unused reference-grid prefixes are not allocated

Decoded image spans and sample buffers retain their existing budgets, absolute grid endpoints and tile dimensions are limited to 2147483647, empty component planes are unsupported, and native block/precinct validation still occurs during full decoding

Images retain PDF big-endian order for 16-bit samples; exact byte geometry and target expansion are checked before sample allocation, and no stride or padding bytes are invented

PreserveAllSpotColours defaults to true; otherwise populate PreservedSpotColours with decoded PDF colorant names, and a Separation or DeviceN space is preserved only when every listed colorant is selected

Preserved spot operators, tint functions and resources remain intact, including Indexed spaces over a preserved base; unselected spots require a dedicated conversion backend and are reported as unsupported

Image stencil masks and referenced mask data remain intact; color-key masks, explicit masks and soft-mask matte components require separate policies

PaintPolicies opts specific complex paint states out of the strict default rejection: pdcpAllowOverprint keeps overprint keys while target-space zeros may repaint differently, pdcpAllowBlendModes keeps non-normal blending in the converted space, pdcpAllowTransferFunctions keeps TR/TR2/BG/BG2/UCR/UCR2 entries applied to the final target components, and pdcpAllowRenderingIntents passes ri operators and ExtGState intents through unchanged

Since v3.218.0, ConvertIsolatedRgbGroups=True opts into a finite transparency profile; it defaults to False and requires an RGB target, empty PaintPolicies, explicit Form resources, /S /Transparency, /I true, absent or false /K, and an explicit RGB blending space whose ICC bytes exactly match the target profile. DeviceRGB uses DeviceRGBProfile; resource aliases and ICCBased RGB are resolved before comparison

The converter keeps the blending domain, isolation, alpha, geometry and paint order, rewrites the Form paint into the target ICC space, and replaces its Group CS with that same target profile without modifying a shared source Group dictionary. Nested and consistently shared Forms follow the existing depth/context rules

The same option accepts graphics /SMask dictionaries with /S /Alpha, a referenced Form in that isolated matching-RGB profile, no /BC, and absent or Identity /TR. It converts the mask Form while preserving the mask dictionary and binding; alpha extraction is independent of its paint color

Page groups, nonisolated/knockout groups, absent or different blending profiles, luminosity masks, custom mask transfer functions, mask backdrop arrays, inherited Form resources and combinations with the broader paint policies remain rejected. The option does not authorize changing a blending domain or make unsupported redaction profiles editable

TransparencyGroupsConverted counts converted group Forms once through the existing Form cache; AlphaSoftMaskSelections counts validated soft-mask selections in rewritten content. These are staged work counters; use Succeeded and Complete to determine publication

Matching Gray/CMYK blending domains since v3.252.0

ConvertIsolatedMatchingGroups is a separate opt-in policy for isolated DeviceGray, DeviceRGB or DeviceCMYK target domains with an exact matching blending ICC profile. It accepts Form groups and explicit page groups, including supported nested/shared Forms, images, axial/radial functions and Alpha soft masks. The original ConvertIsolatedRgbGroups option retains its narrower RGB Form-only behavior

Each group requires explicit resources, /S /Transparency, /I true, absent/false /K and an explicit blending space whose component count and profile bytes match the target. Device names resolve through the caller's configured device profile; resource aliases and direct/indirect ICCBased spaces are supported. Rewritten groups refer to the embedded target profile

The strict matching-group path retains its restrictions on non-normal blend modes, overprint, transfer state, rendering intents, inherited Form resources, luminosity masks, custom mask transfer functions and mask backdrop arrays. An Alpha mask's referenced Form must satisfy the same matching target-domain checks. This option does not authorize changing a blending space

Under this new policy, device/ICCBased buffers already encoded in the byte-identical target profile retain their original component samples instead of taking a PCS round trip. This applies across converted operators, images, inline images and supported shading samples; other profiles still use the configured conversion provider. Preserving encoded CMYK values avoids introducing CMY ink into pure K through an otherwise unnecessary same-profile transform

TransparencyGroupsConverted counts converted Form and page groups, PageTransparencyGroupsConverted identifies the page subset, and MatchingProfileBuffersPreserved counts buffers that retained their target encoding. These remain staged counters; inspect Succeeded and Complete before treating a result as published

Delphi/FPC Win64 evidence covers 20 successes and 28 rejections per compiler through two dirty native saves. Composition checks use nonblank Gray/CMYK sources and a maximum channel difference of 1; independent PDF and bitmap inspection verifies exact ICC bytes/component counts, group/mask relationships, retained image samples, pure K and shading resources. These finite results do not guarantee universal pixel equality or standards compliance

Annotation dictionary /C and /IC color arrays, widget/annotation /MK appearance-characteristics /BC (border) and /BG (background) color arrays (inline or indirect, covering transparent [], 1-component DeviceGray, 3-component DeviceRGB and 4-component DeviceCMYK), annotation /DS default-style and /RV rich-text CSS color literals (#RRGGBB, #RGB and rgb(r,g,b)), annotation /AP appearance streams (/N, /R, /D direct streams or state subdictionaries, with or without an explicit /Resources dictionary), outline item /C color arrays, and compliant AcroForm, field and widget /DA default-appearance strings carrying a Tf font selection and device color operators (g/G, rg/RG, k/K) convert through the target ICC profile

Bounded Type 4 calculator functions

Calculator functions with an increasing Domain and a numeric Range accept one input for axial/radial or mesh shading, or two inputs for function-based Type 1 shading, including compressed streams, one-input calculator children of stitching functions and direct/indirect arrays of one-output functions for individual color components

The interpreter implements the arithmetic, comparison, Boolean, bitwise, conditional and stack operators in ISO 32000-1 Table 42 and Annex B; braces express syntactic if/ifelse branches, without procedure objects, variables, strings, arrays, file access or general PostScript execution

Integers use signed 32-bit semantics, arithmetic overflow promotes add/sub/mul and unary neg/abs results to real values, integer division and conversion reject out-of-range results, right bit shifts fill with zeros, angles use degrees, and round resolves halfway values toward the greater integer rather than banker's rounding

Each calculator function has at most 64 KiB of decoded code, 4096 instructions, 32 nested conditional levels and exactly 100 operand slots; all calculator instructions and sampled-function bit reads in a conversion share a fixed 16777216-unit work budget and observe cancellation

Unknown operators are rejected during parsing even in unselected branches; execution rejects invalid types, underflow/overflow, undefined arithmetic, nonfinite numbers and a final stack whose numeric output count differs from Range; strict conversion preserves the existing destination on rejection

Component arrays can mix supported function types and evaluate each child with its own domain/range clipping; inputs and outputs retain domain/range clipping, and conversion still publishes a sampled target-profile function; MaxShadingFunctionSamples controls approximation density, so narrow features or discontinuities can require more samples and are not certified as exact analytic conversions

Function-based Type 1 shading

Direct or indirect Type 1 shading dictionaries accept two-input calculator or linear sampled functions, including arrays of one-output component functions; every function domain must cover the shading rectangle, and explicit four-number domains and finite nonsingular six-number matrices retain their original geometry

Direct shading and shading-pattern dictionaries are staged as indirect objects before converting page, inherited, Form and colored tiling-pattern resources; direct shading dictionaries inside Type 2 patterns use the same conversion path, resource names retain their escaped PDF spelling, and repeated shared shading patterns recheck the resolved source color context

Materialized dictionaries share the source-active object count and total-body-byte budgets from ReadOptions, obey its individual-object byte limit and MaxDecodedStreamBytes, and participate in the existing staged output-byte budget; exhaustion rejects the conversion before publishing output

Sampled functions accept 1, 2, 4, 8, 12, 16, 24 and 32 bits per sample, read continuously from the most significant bit with the first input dimension varying fastest; linear or cubic interpolation observes Encode, Decode, Range and single-sample dimensions

MaxShadingFunctionSamples bounds the total rectangular grid, rather than each dimension: width is the integer square root of the budget and height is the budget divided by width; Type 1 conversion needs at least four samples, and the default 256 produces a 16 by 16 grid

Type 1 color spaces must name an explicit family or use a color-space array; arbitrary resource aliases and Indexed spaces are rejected, while supported Device defaults resolve through the current resources; shared shading resources reject inconsistent resolved color contexts

Very small domains retain ordinary PDF decimal syntax without exponent notation; large integral matrix coefficients also require real syntax after native saving, so affected converted documents carry a private catalog flag that activates bounded post-processing in PostProcessSavedPdf; this repair preserves the original matrix and accepts only unencrypted output without signature ByteRange dictionaries

Type 1 acceptance covers 45 positive and 23 negative cases, three saved generations per positive case and independent sample-table/ICC checks; axial/radial acceptance additionally covers direct dictionaries; some packed sampled sources and different ICC profiles render differently in the native source decoder, so those cases retain the difference as a diagnostic and verify converted output against independent samples and interior pixels; MuPDF renders the tiny-domain large-matrix cohort blank, so that cohort instead requires nonblank native source/output comparisons and exact geometry checks

Cubic sampled functions since v3.301.0

One- and two-input sampled functions accept Order 3 across function-based, axial, radial and Type 4-7 mesh shadings, including stitching children and component-function arrays; absent or null Order selects linear interpolation, while other order values are rejected

Cubic segments use centered-tangent Hermite interpolation with repeated endpoint samples; two-input functions use a tensor product of the per-dimension kernels; an input dimension with fewer than four samples independently falls back to linear interpolation as required by ISO 32000-1 section 7.10.2

Inputs first clamp to Domain, map through Encode and clamp to sample-table coordinates; all interpolation completes before Decode and final Range clipping; cubic overshoot is retained until that final clipping, including when one dimension uses a linear fallback

Each uncached sample component charges its BitsPerSample to the conversion's shared 16777216-unit work budget; calculator instructions charge the same counter, including nested functions and arrays; adaptive function tessellation charges cache decoding by the source bit count and each cached component lookup by one unit; exhausted work rejects strict conversion before publication without resetting the counter for each function or sample

Converted output remains a bounded linear sampled approximation in the target profile, controlled by MaxShadingFunctionSamples; native source readers may ignore cubic Order, so source/output pixel equality is not proof of cubic semantics; acceptance uses independent polynomial values, ICC sample words, actual saved geometry and target-space interior colors

On the ordinary function-representation path, retained high-contrast Type 6/7 patches have correct converted function samples but interior channel errors of 16 against the required limit of 10, and an axial case with custom Decode reaches 13; those cases do not qualify that path's native composition, and increasing the function sample count alone does not prove the renderer's own lookup/subdivision precision; the bounded tessellation profile below addresses these retained counterexamples

Bounded function tessellation since v3.302.0

Set TessellateShadingFunctions=True to convert unary function meshes and bounded axial shadings into Type 4 triangles with 32-bit coordinates and 16-bit target components; the option defaults to False, retaining the function representation and exact original patch controls on the ordinary path

The adaptive path interpolates the source scalar parameter, evaluates its original sampled, exponential, stitching, calculator or component-array function, and only then converts the resulting source color through ICC; it avoids exchanging nonlinear functions or color transforms with interpolation

Type 4-7 function meshes and implicit Gray identities use MeshColourTolerance, MeshGeometryTolerance, MaxMeshSubdivisionDepth, MaxMeshOutputTriangles and MaxMeshTransformSamples; MaxShadingFunctionSamples controls the ordinary resampled-function path and does not control adaptive tessellation density

Axial tessellation requires an explicit finite positive-area BBox, a finite nonzero four-number axis, a covered two-number Domain or its default, and a valid two-Boolean Extend array or its default; clipping the BBox against the axis slab preserves unextended ends, while extended regions retain endpoint colors; vertical, diagonal and reversed axes use the same source-coordinate projection

Axial source intervals split into bounded strips before triangle refinement, and intersections on shared box edges use canonical equations; an empty bounded paint becomes a degenerate triangle without adding visible coverage; Coords, Domain, Extend and Function entries are removed from the resulting mesh while BBox and the resource placement remain intact

Function caches retain original integer sample values without applying Decode or clipping early; aggregate cache storage obeys MaxDecodedStreamBytes, and cache preparation, lookups, calculator execution and mesh sampling retain their respective shared budgets and cancellation checks; insufficient budgets or unsupported input reject conversion before destination publication

FunctionMeshesConverted counts generated function/identity meshes once through the shading cache, and AxialMeshesConverted counts the axial subset; these also contribute to the existing adaptive mesh counters and remain staged work until Succeeded and Complete confirm publication

The declared RGB native profile checks the original retained counterexample pixels on AGG and Skia through three saved generations, alongside independent function/ICC vertex values, geometry, axial area and shared-edge coverage; the required channel-error limit remains 10; radial tessellation, Indexed function sources, arbitrary device-space error guarantees and continuous witness proofs are outside this profile

Mesh functions and matching encoded components

Type 4 free-form triangles, Type 5 lattices, Type 6 Coons patches and Type 7 tensor patches accept one-input sampled, exponential, stitching or calculator functions and component-function arrays; each function must cover the mesh Decode parameter interval, and its converted sampled function still runs after parameter interpolation

Gray meshes without a Function entry can promote to a scalar identity function before ICC conversion; ConvertIsolatedMatchingGroups preserves multicomponent device/ICC meshes with byte-identical source/target ICC profiles, retaining their encoded components without a PCS round trip

Mesh validation checks legal coordinate/component/flag widths, complete triangle connections, complete lattice rows and patch reuse, with a fixed limit of 1048576 vertex or patch records; decoded and normalized data obey MaxDecodedStreamBytes, and final staging still obeys MaxOutputBytes

Triangle stream bytes remain unchanged; patch streams normalize to 8-bit edge flags and losslessly promote 1-bit or 2-bit components to 4 bits, retaining exact coordinate words, decoded parameter fractions, Decode arrays and control geometry; this avoids short-flag and trailing-padding interpretation failures in native rendering

Acceptance checks actual AGG output and normalized Skia patch output through three saved generations, with independent packed-data interpretation, ICC/sample values and interior pixels; finite interior limits account for native lookup/subdivision quantization, while MuPDF function-mesh and packed-coordinate visual differences remain diagnostic; these checks do not certify universal pixel equality

Shared function graphs and storage budgets since v3.303.0

Indirect functions retain their source-object identity during one conversion, so shared acyclic Type 3 graphs and component arrays reuse parsed nodes instead of expanding every reference into a separate subtree; adaptive sample-word caches also prepare each shared node once, independently of its shading color-space context

MaxFunctionNodes defaults to 4096 and accepts 1 through 65536, counting parsed node attempts including inline values and retries after a depth-specific failure; repeated valid indirect references do not consume another node attempt; cycles remain unsupported, and the function nesting limit of 16 applies to every path even when a node was previously cached at a shallower depth

MaxFunctionStorageBytes defaults to 67108864 (64 MiB) and accepts 1 through 536870912 (512 MiB); its cumulative logical charges cover function dictionaries and token metadata, lookup/cache capacities, component and numeric arrays, decoded sample tables, calculator payloads and adaptive sample-word caches across the entire conversion

Charges are conservative and are not refunded when temporary metadata is released; bounded transient decoder/compiler workspace, active-object/source budgets, per-stream decoded limits and the shared evaluation-work limit remain separate; this option does not promise a bound on process RSS or allocator overhead

Function array cardinalities are checked while tokenizing; function streams receive the remaining decoded-storage limit before decompression; node, storage and decoded function-stream budget failures abort the operation even when FailOnUnsupported=False, preserving the destination bytes and source position before publication

FunctionNodesParsed, FunctionReferencesReused, FunctionCachePreparations and FunctionStorageBytes report attempted parsing, successful cached references, completed adaptive cache preparations and cumulative logical storage charges; these counters can describe staged work on failure and do not imply publication

Adaptive component meshes since v3.300.0

Type 4-7 meshes without a Function entry can convert nonmatching RGB/CMYK, CalRGB and Lab components through the configured provider; source components interpolate before color conversion, and Coons/tensor patch geometry evaluates before triangulation into a target-profile Type 4 mesh

Indexed mesh vertices round and clamp their decoded index, expand the selected palette entry into the base color space, and interpolate those base components; interpolating palette indices would change the source shading and is not used; Indexed meshes with a Function entry remain rejected

Each refinement attempt uses the same dyadic subdivision level across all primitives; shared line and cubic boundaries evaluate in a canonical direction, including reversed patch reuse, to retain identical encoded boundary coordinates; output uses 32-bit coordinates and 16-bit target components, retaining the original BBox and resource placement

MeshColourTolerance defaults to 1/512 of one target component and accepts finite values greater than zero through one; MeshGeometryTolerance defaults to 0.01 source user units and must be finite and positive; midpoint, centroid and quarter-point witnesses measure transformed-color interpolation error and geometric approximation separately; these finite checks are sampled approximation criteria, not a continuous error proof or a device-space pixel guarantee

MaxMeshSubdivisionDepth defaults to 8 and accepts 0 through 12; MaxMeshOutputTriangles defaults to 131072 and accepts 1 through 349525; MaxMeshTransformSamples defaults to 2097152 and accepts 1 through 16777216, counting source evaluations across refinement attempts and meshes; primitive storage, witness arrays, provider buffers and output also obey MaxDecodedStreamBytes

Steep gamut boundaries can require more subdivision than the configured budgets allow; insufficient depth, triangles, samples, decoded bytes, output bytes or coordinate precision rejects conversion before destination publication; increasing depth alone does not increase the other limits, and cancellation preserves the source position and destination bytes

AdaptiveMeshesConverted, AdaptiveMeshTriangles, AdaptiveMeshSamples and AdaptiveMeshMaxDepth report staged work; AdaptiveMeshColourError and AdaptiveMeshGeometryError report the maximum accepted witness errors; use Succeeded and Complete to determine whether the result was published

CalRGB matrices follow the PDF column order [XA YA ZA XB YB ZB XC YC ZC]; optional Gamma and Matrix arrays require exactly three and nine entries, respectively; Lab Range requires four entries; nonzero calibrated BlackPoint values remain unsupported and are rejected rather than silently ignored

Unsupported boundaries include DCT/JPX images without an original-component decoder, sub-byte images outside Indexed spaces, nondefault ICC ranges, nonzero calibrated BlackPoint values, Indexed meshes with functions, sampled functions with more than two inputs, Type3 glyph programs, malformed or non-device /DA strings, XFA color content, uncoloured tiling pattern content that violates the stencil constraint by setting colour state, and any paint state whose policy is not enabled

Forms with their own resources must establish their color space before bare sc/scn operands; shared forms, images or shadings with conflicting resolved color contexts abort the whole conversion even when FailOnUnsupported is False, preserving the destination; context identity includes calibrated parameters, Lab ranges and Indexed base/palette data, and cached failures propagate to every invoking scope

FailOnUnsupported defaults to true and preserves the destination on failure; setting it to false allows independent supported updates, sets Complete to false and never writes a new OutputIntent for a partial conversion

A partial result can retain an existing OutputIntent from its source; OutputIntentWritten specifically reports whether this operation installed a new target declaration

TPdfDocumentOutputIntentKind = (pdoikPdfX, pdoikPdfA) selects the OutputIntent subtype through OutputIntentKind: default pdoikPdfX writes GTS_PDFX, while pdoikPdfA writes GTS_PDFA1; the concrete PDF/A color repair provider selects the latter

A complete result embeds the supplied target ICC profile and writes an OutputIntent with the requested identifier; this does not certify PDF/X, PDF/A or another conformance level

Source and destination must be distinct streams; the source position is restored, preparation failures leave the destination unchanged, and cancellation preserves EPdfOperationCancelled

Publishing the prepared result replaces the destination through its stream API; an exception while truncating or writing the destination can leave partial output, so callers needing atomic file publication should write to a temporary file and rename it after success

Encryption and existing signatures require a separately prepared unencrypted, unsigned source; incremental color conversion does not preserve signature validity

Defaults allow 64 MiB per decoded content/image stream, 512 MiB for output staging, 10,000 issue reports and depth 64, in addition to the active-object reader budgets

The output budget conservatively includes source bytes, staged replacement objects and reserved xref/trailer overhead before accumulating each update; the complete trailer length is included before serialization, and a bounded output stream rejects writes beyond the limit before growing its logical size

This bounds logical output staging rather than all process memory or the memory allocator's capacity rounding, and the final serialized size is checked again before publication

TPdfDocumentColourOptions groups the conversion settings: ReadOptions passes TPdfActiveObjectReadOptions to the active-object reader, MaxDecodedStreamBytes caps each decoded or converted content and image stream, MaxOutputBytes caps the serialized revision, MaxIssues caps how many issues are recorded before the next one aborts the run, and MaxDepth must sit between 1 and 128 and bounds indirect reference chains, nested forms and the graphics state stack

OutputIntentIdentifier supplies the /OutputConditionIdentifier text of the complete conversion's OutputIntent, defaults to 'ICC converted output' and has its length validated against MaxDecodedStreamBytes; MaxShadingFunctionSamples must sit between 2 and 65536 and bounds total domain evaluations whenever a function is resampled, including mesh functions, with a minimum of four for Type 1 conversion; matching encoded meshes need no resampling; TPdfSpotColourNames is the dynamic array of decoded colorant names carried by PreservedSpotColours

TPdfDocumentColourOptions.Default fills the record with ReadOptions from TPdfActiveObjectReadOptions.Default, the 64 MiB decoded-stream, 512 MiB output, 10,000-issue and depth-64 limits, 256 shading function samples, FailOnUnsupported and PreserveAllSpotColours enabled, empty spot-name and device-profile fields, and OutputIntentIdentifier preset to 'ICC converted output'

TPdfDocumentColourIssue pairs the ObjectNumber of one unsupported finding with its human-readable Reason; TPdfDocumentColourIssues is the dynamic array that collects these entries

TPdfDocumentColourReport summarizes the attempt: Succeeded becomes true only after a converted revision was published, ErrorText explains a failure, and Issues lists the findings counted by UnsupportedCount

ContentStreamsConverted, FormsConverted and ImagesConverted count converted page contents, Form XObjects and images, ColourOperatorsConverted counts rewritten color operators, CalibratedSpacesConverted counts operator conversions through calibrated math, IndexedImagesConverted counts palette-expanded images, PatternsConverted counts converted tiling and shading pattern dictionaries, and ShadingsConverted counts converted shading dictionaries, while PreservedSpotSelections and PreservedMasks count spot selections and stencil or referenced masks left intact

CodecImagesDecoded still reports actual ImageDecoder use, and IndexedImagesConverted images never require a codec

PdfDocumentColourConvertibleSourceKinds returns the converted source families (DeviceGray, DeviceRGB, DeviceCMYK, ICCBased, CalGray, CalRGB, Lab and Indexed), while PdfDocumentColourPreservedSpotSourceKinds returns the Separation and DeviceN preservation families; use them to preflight documents before conversion

Real calibrated operator and image conversion, PCS Lab identity checks, indexed palette expansion, paint-policy acceptance and rejection, save/reopen/render and destination preservation are verified on the ordinary Delphi Win64 runtime, in addition to the cross-compiler colour provider matrix

Example

ProviderOptions := TPdfLittleCmsOptions.Default;
Provider := CreatePdfLittleCmsColourTransform(LibraryPath, ProviderOptions);
Options := TPdfDocumentColourOptions.Default;
Options.DeviceCMYKProfile := SourceCmykProfile;
TargetProfile := CreatePdfLittleCmsGrayProfile(LibraryPath);
if not ConvertPdfDocumentColours(Source, Destination, pcsDeviceGray,
  TargetProfile, Provider, Options, Report, CancellationToken) then
  raise Exception.Create(Report.ErrorText);

Public declarations

type
  TPdfSpotColourNames = array of AnsiString;
  TPdfDocumentColourPaintPolicy = (pdcpAllowOverprint, pdcpAllowBlendModes,
    pdcpAllowTransferFunctions, pdcpAllowRenderingIntents);
  TPdfDocumentColourPaintPolicies = set of TPdfDocumentColourPaintPolicy;
  TPdfDocumentColourSourceKind = (pdcskDeviceGray, pdcskDeviceRGB,
    pdcskDeviceCMYK, pdcskICCBased, pdcskCalGray, pdcskCalRGB, pdcskLab,
    pdcskIndexed, pdcskSeparation, pdcskDeviceN);
  TPdfDocumentColourSourceKinds = set of TPdfDocumentColourSourceKind;
  TPdfDocumentColourOptions = record
    ReadOptions: TPdfActiveObjectReadOptions;
    ImageDecoder: IPdfImageComponentDecoder;
    MaxDecodedStreamBytes: Integer;
    MaxOutputBytes: Int64;
    MaxIssues: Integer;
    MaxDepth: Integer;
    FailOnUnsupported: Boolean;
    PreserveAllSpotColours: Boolean;
    PreservedSpotColours: TPdfSpotColourNames;
    PaintPolicies: TPdfDocumentColourPaintPolicies;
    ConvertIsolatedRgbGroups: Boolean;
    ConvertIsolatedMatchingGroups: Boolean;
    DeviceGrayProfile, DeviceRGBProfile, DeviceCMYKProfile: TBytes;
    OutputIntentIdentifier: string;
    OutputIntentKind: TPdfDocumentOutputIntentKind;
    MaxShadingFunctionSamples: Integer;
    MeshColourTolerance, MeshGeometryTolerance: Double;
    MaxMeshSubdivisionDepth, MaxMeshOutputTriangles,
      MaxMeshTransformSamples: Integer;
    TessellateShadingFunctions: Boolean;
    MaxFunctionNodes: Integer;
    MaxFunctionStorageBytes: Int64;
    AllowJpxDeviceFallback: Boolean;
    class function Default: TPdfDocumentColourOptions; static;
  end;
  TPdfDocumentColourIssue = record
    ObjectNumber: Integer;
    Reason: string;
  end;
  TPdfDocumentColourIssues = array of TPdfDocumentColourIssue;
  TPdfDocumentColourReport = record
    Succeeded: Boolean;
    Complete: Boolean;
    ContentStreamsConverted, FormsConverted, ImagesConverted: Integer;
    CodecImagesDecoded, JpxDeviceFallbackImages: Integer;
    ColourOperatorsConverted, CalibratedSpacesConverted: Integer;
    IndexedImagesConverted, PreservedSpotSelections, PreservedMasks: Integer;
    TransparencyGroupsConverted, AlphaSoftMaskSelections: Integer;
    PageTransparencyGroupsConverted, MatchingProfileBuffersPreserved: Integer;
    PatternsConverted, ShadingsConverted: Integer;
    AdaptiveMeshesConverted, AdaptiveMeshTriangles, AdaptiveMeshSamples,
      AdaptiveMeshMaxDepth: Integer;
    AdaptiveMeshColourError, AdaptiveMeshGeometryError: Double;
    FunctionMeshesConverted, AxialMeshesConverted: Integer;
    FunctionNodesParsed, FunctionReferencesReused, FunctionCachePreparations: Integer;
    FunctionStorageBytes: Int64;
    UnsupportedCount: Integer;
    OutputIntentWritten: Boolean;
    Issues: TPdfDocumentColourIssues;
    ErrorText: string;
  end;

function ConvertPdfDocumentColours(Source, Destination: TStream;
  TargetSpace: TPdfColourSpace; const TargetProfile: TBytes;
  Transform: IPdfColourTransform; const Options: TPdfDocumentColourOptions;
  out Report: TPdfDocumentColourReport;
  CancellationToken: IPdfCancellationToken = nil): Boolean;
function PdfDocumentColourConvertibleSourceKinds: TPdfDocumentColourSourceKinds;
function PdfDocumentColourPreservedSpotSourceKinds: TPdfDocumentColourSourceKinds;