Point TPdfDocumentColourOptions.ImageDecoder at the optional FPdfImageComponents provider for original-component DCT/JPX decoding; CodecImagesDecoded reports genuine provider use, and the default nil keeps the existing unsupported-codec rejection
ConvertPdfDocumentColours obtains the active PDF revision, transforms original component operands and image samples through an IPdfColourTransform, then appends a consistent revision to a separate output stream
Supported input covers text and vector fill/stroke operators in DeviceGray, DeviceRGB, DeviceCMYK and ICCBased spaces together with CalGray, CalRGB, Lab and Indexed sources decoded through the ICC PCS Lab connection, plus inherited page resources, named default colour-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 colour 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 whilst 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 worked out with Bradford adaptation into the D50 PCS; Lab /Range values beyond the encodable +-128 domain are rejected, and Indexed palettes resolve either inline strings or their own decoded stream objects
Indexed images take 1, 2, 4 or 8-bit samples with an optional two-entry /Decode remap; a single palette conversion covers every pixel, over a device, ICCBased or calibrated base space, and Separation or DeviceN bases fall under the spot preservation policy
Since v3.307.1, each Indexed image scanline begins at a byte boundary, sub-byte rows whose final byte carries padding included; 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 take the optional IPdfImageIndexDecoder path for one-component raw JPX or JP2 input, general filter chains, signed/unsigned source precisions 1-16 and sampled grids included; unscaled source indices select the PDF palette and clamp to hival, whilst internal JP2 palette/channel interpretations and JPX Decode/BitsPerComponent entries are ignored
The source index buffer uses the inspected 8/16-bit storage and is budgeted before decoding, independently of the target palette expansion; calibrated Indexed bases keep their 16-bit output path; older bridges without index exports report unsupported input, and nonzero SMaskInData, multiple encoded components, higher precision and implicit colour-space selection keep their separate gates
Parsed colour spaces are cached per source expression and resource context, so repeated operator selections share one palette allocation
Content arrays use a common operand parser and graphics-state stack, with a space separating streams; throughout conversion, q/Q, default colour spaces and component counts refer to their original source spaces
CMYK operands are taken directly from PDF content and image streams, never from rendered RGB getters; unprofiled DeviceCMYK input needs DeviceCMYKProfile
Source ICCBased profiles are resolved from their original resource scope; only an absent or default /Range [0 1 ...] is supported, whilst 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 normalising each signed range into unsigned samples; an explicit PDF ColorSpace overrides embedded JP2 colour 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 colour families keep 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 rebuilds the complete reference-grid image before ICC conversion, including odd or non-dividing 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, mixed channel precisions and sampled grids included; 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, whilst 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 the actual target precision is checked again before ICC conversion; calibrated images count their 16-bit target components against MaxDecodedStreamBytes, four-component CMYK output included; older bridge DLLs without metadata keep the explicit supported 8/16-bit path
Since v3.307.0, JP2 PCLR/CMAP palettes and complete colour-only CDEF associations produce the logical colour 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 colour precision; palette indices must remain in range and padding bits must be zero
Since v3.310.0, PDF ColorSpace entries that are absent or null can fall back on optional IPdfImageColourMetadata declarations; the supported sources are provider-compatible RGB/Gray/CMYK ICC profiles in methods 2/3, standard sRGB 16, standard grey 17 and device CMYK 12
Declarations are considered by descending signed Precedence and then by ascending Approximation, ties keeping their input order; structurally invalid, mismatched or provider-unsupported ICC choices are skipped before any pixel decoding, and a later supported declaration may still be chosen
sRGB takes the built-in standard profile regardless of DeviceRGBProfile or DefaultRGB; standard grey runs the piecewise sRGB transfer function through neutral PCS Lab and produces 16-bit converted samples; CMYK takes the configured device profile or a resolved DefaultCMYK resource
The selection is cached within one conversion, with CMYK declarations and all device fallbacks keeping their resource-dependent context checks; conflicting interpretations of a shared source still abort strict and partial conversion before the destination is published
An explicit PDF ColorSpace bypasses implicit selection; the native codec receives neutral colour metadata once the original declarations have been inspected, leaving source interpretation to the chosen PDF or JPX declaration
Since v3.311.0, unsigned sYCC 18 rebuilds each channel at its original 1-16-bit precision before the precision-specific chroma midpoint and the sYCC matrix are applied; RGB values are clipped to the standard range and rounded to the decoded 8/16-bit precision ahead of the built-in sRGB ICC conversion; mixed precisions, supported sampled grids, nonzero origins and projected palette channels all follow this same interpretation
T.800 Table I.10 requires unsigned channels for sYCC; a signed channel makes that declaration unavailable, so selection moves on to supported lower declarations or device fallback; an explicit PDF ColorSpace still overrides sYCC
AllowJpxDeviceFallback defaults to True and applies DeviceGray, DeviceRGB or DeviceCMYK once a successful JPX metadata inspection has found no usable declaration, raw codestreams and missing declarations included; configured profiles and the DefaultGray/DefaultRGB/DefaultCMYK resources still determine these device spaces
JpxDeviceFallbackImages counts each successfully converted fallback image object once, shared images included; set AllowJpxDeviceFallback to False to require a usable declaration for implicit images, with the normal strict/partial unsupported handling; unsupported embedded profiles and other enumerated families are not interpreted accurately by the component-count fallback
Fallback selections keep every Default* resource context; conflicting interpretations of a shared source abort strict and partial conversion before the destination is published; malformed or unavailable metadata, invalid channel precision or sampling, allocation failures and cancellation never turn into device fallback
Since v3.312.0, CIELab 14 declarations use the original per-channel integer precision and signedness to recover T.801 nominal samples, taking default ranges/offsets or all seven explicit EP fields; unsigned 1-16-bit and signed 2-16-bit channels can be mixed, supported sampled grids, nonzero origins and signed palette columns included
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 carries all RL/OL/RA/OA/RB/OB/IL fields, and a zero range, an incomplete block, an unknown illuminant or a signed one-bit zero nominal maximum makes that declaration unavailable
The declared Bradford policy adapts the D50, D65, D75, SA, SC, F2, F7 and F11 standard illuminants into D50 PCS, using rounded CIE 1931 2-degree white points; D50 keeps the T.42 reference, and the declared values are compared independently against the official CIE spectral datasets to within 0.0001 in normalised 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 normalisation 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 to within 0.0005 in normalised XYZ and against published Planckian chromaticities to 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 stays 16-bit, and the 12-byte-per-pixel floating workspace is checked before pixel decoding, partial conversion mode included
Providers without the optional interface can pick another supported declaration or use the separately reported optional device fallback; an explicit PDF ColorSpace still takes priority, and ordinary integer colour conversion keeps its existing interface
Integer Pixel Format boxes require complete unique channel indices and integer format entries; malformed boxes and fixed/floating reinterpretations are rejected before native decoding and never trigger device fallback
Since v3.313.0, ROMM RGB 21 uses the published unflared ROMM encoding: the original unsigned 1-16-bit or signed 2-16-bit coordinates are reconstructed and clipped to 0..1, the inverse linear toe is applied below 1/32 or the 1.8 power curve, and the published XYZ-to-ROMM matrix is inverted into D50 PCS Lab
Extended sRGB 20 accepts 10-, 12- and 16-bit channels, mixed precision included; each unsigned channel subtracts 3*2^(p-3) and divides by 255*2^(p-9), whilst 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, keeps extended linear RGB without early clipping, and uses the PIMA 7667:2001 matrix and the declared D65-to-D50 Bradford policy ahead of floating PCS conversion
Both families require optional IPdfColourFloatTransform and produce 16-bit target samples; supported sampled grids, image/tile origins, palette projections, colour-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 characterisation 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
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 requantisation 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 behaviour; 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
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 whilst 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 that a stream is fully valid
Since v3.309.0, nonzero JPX image and tile origins use image-area Width/Height spans and keep the absolute component sampling phase; first-source-sample extension covers leading unsampled positions, consistently across original colours, 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 keep their existing budgets, absolute grid endpoints and tile dimensions are limited to 2147483647, empty component planes are unsupported, and native block/precinct validation still takes place during full decoding
16-bit image samples retain PDF big-endian ordering; exact byte geometry and destination expansion are validated before allocating samples, with no invented stride or padding
PreserveAllSpotColours is true by default; otherwise, list decoded PDF colourant names in PreservedSpotColours, as Separation or DeviceN is retained only if every named colourant is selected
Retained spot-colour operators, tint functions and resources are left intact, Indexed spaces over a preserved base included; other spots need a dedicated conversion backend and are reported as unsupported
Image stencil masks and referenced mask data are retained; colour-key masks, explicit masks and soft-mask matte components need policies of their own
PaintPolicies lets specific complex paint states out of the strict default rejection: pdcpAllowOverprint keeps overprint keys whilst target-space zeros may repaint differently, pdcpAllowBlendModes keeps non-normal blending within the converted space, pdcpAllowTransferFunctions keeps TR/TR2/BG/BG2/UCR/UCR2 entries applied to the final target components, and pdcpAllowRenderingIntents lets 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 whilst preserving the mask dictionary and binding; alpha extraction is independent of its paint colour
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 authorise 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
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 behaviour
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 authorise 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 colour arrays, widget/annotation /MK appearance-characteristics /BC (border) and /BG (background) colour 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 colour 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 colour arrays, and compliant AcroForm, field and widget /DA default-appearance strings carrying a Tf font selection and device colour operators (g/G, rg/RG, k/K) convert through the target ICC profile
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 colour 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 towards 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
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 coloured tiling-pattern resources; direct shading dictionaries inside Type 2 patterns use the same conversion path, resource names keep their escaped PDF spelling, and repeated shared shading patterns recheck the resolved source colour context
Materialised dictionaries share the source-active object count and total-body-byte budgets from ReadOptions, obey its individual-object byte limit and MaxDecodedStreamBytes, and take part 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 colour spaces must name an explicit family or use a colour-space array; arbitrary resource aliases and Indexed spaces are rejected, whilst supported Device defaults resolve through the current resources; shared shading resources reject inconsistent resolved colour contexts
Very small domains keep ordinary PDF decimal syntax without exponent notation; large integral matrix coefficients also need real syntax after native saving, so affected converted documents carry a private catalogue 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 keep 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
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, whilst other order values are rejected
Cubic segments use centred-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 falls back to linear interpolation independently, as ISO 32000-1 section 7.10.2 requires
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 survives 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 colours
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
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, keeping 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 colour through ICC; it avoids exchanging nonlinear functions or colour 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, whilst extended regions keep their endpoint colours; 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 whilst BBox and the resource placement remain intact
Function caches keep original integer sample values without applying Decode or clipping early; aggregate cache storage obeys MaxDecodedStreamBytes, and cache preparation, lookups, calculator execution and mesh sampling keep 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 feed 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 stays at 10; radial tessellation, Indexed function sources, arbitrary device-space error guarantees and continuous witness proofs sit outside this profile
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 be promoted to a scalar identity function before ICC conversion; ConvertIsolatedMatchingGroups preserves multicomponent device/ICC meshes with byte-identical source/target ICC profiles, keeping 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 normalised data obey MaxDecodedStreamBytes, and final staging still obeys MaxOutputBytes
Triangle stream bytes remain unchanged; patch streams normalise to 8-bit edge flags and losslessly promote 1-bit or 2-bit components to 4 bits, keeping 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 normalised 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 quantisation, whilst MuPDF function-mesh and packed-coordinate visual differences stay diagnostic; these checks do not certify universal pixel equality
Indirect functions keep 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 colour-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 whilst tokenising; 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
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 colour 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 colour space, and interpolate those base components; interpolating palette indices would alter 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 keep identical encoded boundary coordinates; output uses 32-bit coordinates and 16-bit target components, keeping 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-colour 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 need 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 raise 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 colour 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 colour space before bare sc/scn operands; shared forms, images or shadings with conflicting resolved colour contexts abort the whole conversion even when FailOnUnsupported is False, preserving the destination; context identity takes in 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, whilst pdoikPdfA writes GTS_PDFA1; the concrete PDF/A colour 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 whilst 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
For encrypted or already signed input, prepare an unencrypted, unsigned source separately; incremental colour conversion cannot maintain signature validity
Alongside the active-object reader's budgets, defaults permit 64 MiB per decoded content/image stream, 512 MiB of output staging, 10,000 issue reports and depth 64
Before adding each update, the output budget conservatively accounts for source bytes, staged replacement objects and reserved xref/trailer overhead; full trailer length is included before serialisation, and the limited output stream refuses excess writes before extending its logical size
The allowance covers logical output staging, not total process memory or allocator capacity rounding; the final serialised size is checked once more 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 serialised 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, mesh functions included, 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 summarises 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 colour operators, CalibratedSpacesConverted counts operator conversions through calibrated maths, and IndexedImagesConverted counts palette-expanded images, PatternsConverted counts converted tiling and shading pattern dictionaries, and ShadingsConverted counts converted shading dictionaries, whilst PreservedSpotSelections and PreservedMasks count spot selections and stencil or referenced masks left intact
CodecImagesDecoded continues to report actual ImageDecoder use, and IndexedImagesConverted images never need a codec
PdfDocumentColourConvertibleSourceKinds returns the converted source families (DeviceGray, DeviceRGB, DeviceCMYK, ICCBased, CalGray, CalRGB, Lab and Indexed), and PdfDocumentColourPreservedSpotSourceKinds returns the Separation and DeviceN preservation families; use both to preflight documents ahead of 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
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);
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;