PDFium Delphi Component Docs

Bounded redaction geometry helpers

The geometry helpers on this page are part of every edition; the redaction engine routines and TPdf.SaveAsRedacted require the Enterprise edition (link FPdfEnterprise with Lib\Enterprise on the search path), otherwise they raise EPdfEnterpriseRequired; see the edition matrix

FPdfRedaction provides conservative source inspection and geometry operations used by TPdf.SaveAsRedacted; the high-level method supplies the transaction, annotation processing, opaque overlays, content regeneration, sanitisation, and resource pruning

The helpers alter native objects only in the caller's isolated transaction copy, raising EPdfRedactionGeometry for unsupported geometry or exhausted allowances; using them alone does not constitute a complete secure export

Public declarations

const
  PdfRedactionCompositeSoftMaskTransfer = 1;
  PdfRedactionCompositeTransferFunctions = 2;

type
  IPdfRedactionCompositeDocument = interface
    function GetPageCount: Integer;
    function RenderPage(PageNumber, Width, Height: Integer;
      out Bgra: TBytes; out ErrorText: string): Boolean;
  end;
  IPdfRedactionCompositeRasterizer = interface
    function OpenDocument(Source: TStream;
      out Document: IPdfRedactionCompositeDocument;
      out ErrorText: string): Boolean;
  end;
  IPdfRedactionCompositeCapabilities = interface
    function GetCapabilities: Cardinal;
  end;
  EPdfRedactionGeometry = class(Exception);
  TPdfRedactionGeometryOptions = record
    MaxFormDepth, MaxObjects, MaxPathSegments, MaxFragments: Integer;
    MaxImagePixels, MaxGeometryOperations: Int64;
    CurveTolerance: Double;
    class function Default: TPdfRedactionGeometryOptions; static;
  end;
  TPdfRedactionStructureOptions = record
    ReadOptions: TPdfActiveObjectReadOptions;
    MaxElements, MaxDepth, MaxContentStreams: Integer;
    MaxOutputBytes: Int64;
    class function Default: TPdfRedactionStructureOptions; static;
  end;
  TPdfRedactionStructureReport = record
    Succeeded, HasStructure: Boolean;
    PreservedMarkedContentCount, RemovedMarkedContentCount: Integer;
    RemovedElementCount, RemovedObjectReferenceCount: Integer;
    RenumberedMarkedContentCount, RenumberedStreamCount: Integer;
    PreservedOptionalContentCount: Integer;
    ErrorText: string;
  end;
  TPdfRedactionGeometryReport = record
    ExpandedFormCount, ScannedChildCount, ClippedPathCount: Integer;
    FlattenedCurveCount, GeneratedPointCount, FragmentCount: Integer;
    MaskedImageCount: Integer;
    ScannedPixelCount, MaskedPixelCount, PixelIntersectionTestCount: Int64;
    GeometryOperationCount: Int64;
  end;
  TPdfRedactionJustification = (prjLeft, prjCenter, prjRight);
  TPdfRedactionAnnotationSpec = record
    PageNumber, AnnotationIndex: Integer;
    HasRect: Boolean;
    Rect: FS_RECTF;
    HasInteriorColor: Boolean;
    InteriorColorR, InteriorColorG, InteriorColorB: Byte;
    OverlayText: WideString;
    HasRepeat, RepeatOverlayText: Boolean;
    HasDefaultAppearance: Boolean;
    DefaultAppearance, FontName: AnsiString;
    FontSize: Single;
    HasTextColor: Boolean;
    TextColorR, TextColorG, TextColorB: Byte;
    HasJustification: Boolean;
    Justification: TPdfRedactionJustification;
  end;
  TPdfRedactionAnnotationSpecs = array of TPdfRedactionAnnotationSpec;

function ParseRedactionDefaultAppearance(const DA: AnsiString;
  out FontName: AnsiString; out FontSize: Single;
  out HasColor: Boolean; out R, G, B: Byte): Boolean;
procedure ExtractRedactionAnnotationSpecs(Source: TStream;
  out Specs: TPdfRedactionAnnotationSpecs);
procedure ValidateDetailedRedactionSource(Source: TStream;
  AllowIsolatedTransparency: Boolean=False; AllowIsolatedPageGroups: Boolean=False;
  AllowCompositePages: Boolean=False; AllowCompositeColour: Boolean=False;
  AllowCompositeMaskTransfer: Boolean=False; AllowCompositeTransfer: Boolean=False);
procedure ValidateDetailedRedactionText(PageObject: FPDF_PAGEOBJECT);
procedure ExpandRedactionForms(Page: FPDF_PAGE;
  const Options: TPdfRedactionGeometryOptions;
  var Report: TPdfRedactionGeometryReport);
procedure ClipRedactionPath(Page: FPDF_PAGE; PageObject: FPDF_PAGEOBJECT;
  ObjectIndex: Integer; const Redactions: array of FS_RECTF;
  const Options: TPdfRedactionGeometryOptions;
  var Report: TPdfRedactionGeometryReport);
procedure CopyRedactionObjectMarks(Document: FPDF_DOCUMENT;
  Source, Target: FPDF_PAGEOBJECT);
type
  TRedactionClipKind = (rckNone, rckContainingRect, rckCroppingQuad);
  TRedactionClipPoint = record X, Y: Double; end;
  TRedactionClipPolygon = array of TRedactionClipPoint;
  TRedactionClipPolygons = array of TRedactionClipPolygon;
  TRedactionClipQuad = array[0..3] of record X, Y: Double; end;
  TRedactionClipQuads = array of TRedactionClipQuad;
  TPdfRedactionPatternPage = record
    HasPattern, HasBoundaryTransform, HasBoundaryClip, HasPatternStroke: Boolean;
    Streams: TArray;
  end;
  TPdfRedactionPatternPages = array of TPdfRedactionPatternPage;
function ClassifyRedactionClip(PageObject: FPDF_PAGEOBJECT;
  out Effective: FS_RECTF): TRedactionClipKind;
function ReadRedactionClipPolygons(PageObject: FPDF_PAGEOBJECT;
  out Effective: FS_RECTF; out CroppingPolygons: TRedactionClipPolygons): TRedactionClipKind;
function CanRetainCroppedFillMarks(PageObject: FPDF_PAGEOBJECT): Boolean;
procedure RewriteRedactionGlyphClip(PageObject: FPDF_PAGEOBJECT;
  const Cuts: array of FS_RECTF; const Options: TPdfRedactionGeometryOptions;
  var Report: TPdfRedactionGeometryReport);
procedure ValidateRedactionClipGeometry(PageObject: FPDF_PAGEOBJECT);
procedure RequireMaskableImageState(PageObject: FPDF_PAGEOBJECT);
function RedactionClipCropsContent(PageObject: FPDF_PAGEOBJECT;
  out Effective: FS_RECTF): Boolean;
procedure RepairRedactedTaggedStructure(Source, Destination: TStream;
  const Options: TPdfRedactionStructureOptions;
  out Report: TPdfRedactionStructureReport);
procedure MaskRedactionImage(Document: FPDF_DOCUMENT; Page: FPDF_PAGE;
  PageObject: FPDF_PAGEOBJECT; ObjectIndex: Integer;
  const Redactions: array of FS_RECTF;
  const Options: TPdfRedactionGeometryOptions;
  var Report: TPdfRedactionGeometryReport;
  SourceBitmapOverride: FPDF_BITMAP=nil);

Coordinates and supported geometry

Redaction rectangles and curve tolerances are expressed in PDF user-space points; paths are transformed into page space before clipping, and ObjectIndex is the original zero-based native page-object index that maintains painting order

Expansion and partial geometry refuse transparency, blend states, unsupported children, singular matrices, patterned fills and complex or nonredundant clipping paths; an accepted redundant rectangular clip must enclose the entire object

Options and accumulated reporting

OptionDefaultPurpose
MaxFormDepth32Depth allowed for nested Form expansion
MaxObjects1000000Limits for page enumeration and accumulated expanded children
MaxPathSegments262144Segments in each input path and accumulated generated path points
MaxFragments1000000Retained rectangular regions and accumulated replacement fragments
MaxImagePixels16777216Total decoded image pixels processed
MaxGeometryOperations67108864Total geometry work and pixel intersection tests
CurveTolerance0.01Tolerance in PDF points for flattening cubic curves

Start with TPdfRedactionGeometryOptions.Default and clear the report once before the transaction; reuse that report for all helper calls so points, pixels, fragments and operation allowances accumulate

TPdfRedactionGeometryReport is the counter record the geometry helpers fill through their var Report parameter; its cumulative values drive the MaxObjects, MaxPathSegments, MaxFragments, MaxImagePixels and MaxGeometryOperations budgets

Expansion is described by ExpandedFormCount and ScannedChildCount, counting root Form instances as well as children; path work uses ClippedPathCount, FlattenedCurveCount and GeneratedPointCount, including intermediate clipping points; image work uses MaskedImageCount, ScannedPixelCount, MaskedPixelCount and PixelIntersectionTestCount

FragmentCount counts replacement objects, not contours or pixels; GeometryOperationCount accumulates resource-limited helper work, and a report retained after an exception may describe unfinished work on the discarded copy

Source inspection and export boundary

Since v3.315.0, optional AllowCompositePages, default False, selects the complete-composition preflight used by RasterizeCompositePages; it permits native-renderable device-space composition whilst keeping active-object limits and rejecting signed, AcroForm/XFA and unqualified ICC/CIE/default blending spaces

Since v3.316.0, the Enterprise complete-composition path additionally validates page-local UserUnit scalars and bounded active indirect references from the saved source snapshot; raster dimensions and cumulative pixel budgets include physical scaling, and only the validated scalar is restored to the fresh output page

Since v3.317.0, optional AllowCompositeColour, default False, is selected by the Enterprise path only when an explicit IPdfRedactionCompositeRasterizer supplies source rendering; it allows ICC/CIE/default spaces whilst keeping security/active-object limits and rejecting custom TR/TR2 functions unless the renderer advertises PdfRedactionCompositeTransferFunctions; this flag alone does not provide a colour-managed renderer

Since v3.365.1, composition of CalGray, CalRGB, Lab and DefaultGray/DefaultRGB/DefaultCMYK sources is independently verified against ISO 32000-1 colour formulas plus ICC matrix/TRC and mft2 evaluation at the two-level bound; parent-ICC inheritance, nested differing domains and custom transfer functions remain unqualified

Since v3.318.0, optional AllowCompositeMaskTransfer, default False, permits custom Alpha/Luminosity mask TR only for an explicitly capable source renderer; it keeps Type3 glyph-program rejection and validates actual ExtGState resources separately so extra G/S keys cannot authorise graphics TR/TR2

From internal version 3.384.0, optional AllowCompositeTransfer, default False, admits custom graphics TR and TR2 only where the source renderer reports PdfRedactionCompositeTransferFunctions; the Enterprise path takes it from GetCapabilities rather than asking the caller, so a bridge lacking the transfer implementation still rejects such sources

IPdfRedactionCompositeRasterizer, IPdfRedactionCompositeDocument and IPdfRedactionCompositeCapabilities form the caller-supplied source-renderer contract behind those flags: OpenDocument opens a transaction-local session from the source stream, GetPageCount and RenderPage expose sessions that render the complete CropBox with intrinsic rotation onto opaque white BGRA, and GetCapabilities reports PdfRedactionCompositeSoftMaskTransfer and PdfRedactionCompositeTransferFunctions support; the optional Enterprise FPdfRedactionMuPdf unit provides one implementation

This preflight does not perform redaction or make ordinary Form expansion safe for those states; callers must compose before pixel clearing, discard all source structure/content references, rebuild a fresh raster-only document and verify the final bytes, as the high-level method does

Since v3.248.0, AllowIsolatedTransparency permits only the group and Alpha-mask preflight described by SaveAsRedacted; direct callers must perform that explicit raster conversion before ordinary Form expansion and complete saved-output composition checks

SourceBitmapOverride is an optional borrowed native bitmap containing verified full BGRA samples for an image replacement; its dimensions must match the native image metadata, it stays owned by the caller, and the helper never destroys it

This avoids treating FPDFImageObj_GetBitmap base RGB as if it included a separate soft mask; passing no override retains the original decoded-image behaviour and does not authorise arbitrary masked source images

ValidateDetailedRedactionSource inspects active objects and, for the ordinary conservative profiles below, decoded content before mutation; TPdf.SaveAsRedacted invokes the appropriate preflight for every profile, including whole-object removal and the simpler partial profile

The ordinary profile preserves tagged relationships and optional-content layers through RepairRedactedTaggedStructure and clips stroked paths with a margin grown by half the matrix-scaled stroke width. Where the native clip-copy exports are available, TPdf.SaveAsRedacted can retain a supported straight or cubic Bézier fill under a complex path clip. Given the clip intersection export, it also carries invocation clips through nested Form expansion. It removes the original paint and attaches the effective source clip to the retained geometry before regeneration and resource pruning

For qualified single-segment strokes and open or closed polylines, with or without a path clip, that carry bevel, round or supported miter joins, TPdf.SaveAsRedacted builds the painted outline in object space before it applies the affine matrix. Solid and supported dashed cubic Bézier strokes with butt, round or projecting square caps take the same route, with or without a path clip. They keep round, bevel or supported miter joins at the original path vertices. Subdivision bounds both the geometric approximation and the accumulated arc-length deficit for dashes. It subtracts redaction regions from the transformed outline and retains the source clip on the remaining fill. Where a qualified path carries both fill and stroke, the original fill rule and colour are retained beneath the rebuilt stroke. For supported dashed straight subpaths and open or closed polylines, it normalises signed dash phases to the equivalent position in the dash cycle, restarts the phase at each subpath, and builds the painted intervals and their joins before applying the transform. In even-length dash arrays, a zero-length gap leaves adjacent intervals with their own caps. This also works where the source carries no cropping clip

With the optional glyph-clip exports, the vector preflight also supports scoped clip-only text and qualified opaque fill, stroke and fill-and-stroke text with clipping, on pages and in expanded Forms followed by qualified solid fills. With the optional Type 3 detection export, the vector route can preserve separate pages that hold Type 3 text whilst rewriting supported glyph clips in Form XObjects elsewhere in the document. With or without glyph clipping, the optional FPDFTextObj_GetRedactionType3Bounds export permits same-page retention of qualified Type 3 text on the page, or in expanded Forms whose actual paint bounds are disjoint from the redaction regions. The rewrite preserves character spacing, word spacing and kerning. With FPDFTextObj_MarkRedactionType3Source, a qualified intersecting show is removed as a unit and its source font and glyph streams are revoked. Several intersecting shows may share resources slated for removal. With matching native exports, eligible shared fonts whose qualified path glyphs carry font-level or glyph-local device colour or constant alpha resources can retain the unaffected glyphs once the unused CharProc entries and their stream are removed. Font-level colour and alpha entries that only the removed glyphs use are pruned. Selective Type 3 pruning supports shading patterns and eligible tiling patterns with explicit resources in retained annotation-only appearances and on eligible unmodified pages without glyph clip rewrites. Given the matching native module, a redacted page can retain isolated pattern fills and supported solid and dashed pattern strokes on straight and cubic Bézier paths, including sequences of separate fills and strokes with resolved patterns in one graphics state scope and shading or coloured tiling patterns across several isolated content streams, where each fill is disjoint from every redaction region and preceding streams restore their graphics state apart from supported affine transforms the native module can replay exactly. The matching native module can also retain separate clipping streams with supported line and cubic Bézier contours, implicit or explicit closures, concave contours, holes, and crossings within or between contours included, and clips under a supported affine transform, where the actual clip contains every redaction region. Any remaining active dependency on those resources prevents the save. Filled glyph paths can use aliases for device colour spaces and constant alpha graphics states in direct or indirect font and glyph stream resource dictionaries. Supported text shows include literal and hexadecimal strings and TJ arrays with numeric spacing adjustments. The exporter retains supported visible glyphs outside the redaction regions and subtracts those regions from the clip path. The vector preflight accepts an unused clipping text rendering mode where it can verify an unambiguous reset or restoration of a nonclipping graphics state in the same stream before any glyph is shown. For supported clipped horizontal text, TPdf.SaveAsRedacted uses original glyph codes and positions from the native module, verifies the retained glyph bounds, and attaches the original path clip to each fragment. The optional FPDFTextObj_CreateRedactionGlyph export also rebuilds supported horizontal invisible and stroked text where the source carries no path clip

ClipRedactionPath rebuilds stroked, filled or mixed paths: stroke colour, width, line join and line cap are copied across to the retained contour set, and the cut margin grows by half the matrix-scaled stroke width so that no stroke paint reaches into a redaction rectangle

Since v3.203.1, stroke-only contours clip as line segments rather than filled polygons, preserving two-point horizontal and vertical paths and keeping disconnected fragments open; fully retained closed contours preserve their closing join

ClassifyRedactionClip sorts every object clip into rckNone, rckContainingRect or rckCroppingQuad; a closed convex quadrilateral clip (any orientation, non-containing rectangles included) restricts painting, so RedactionClipCropsContent reports its effective region and the caller keeps untouched objects whose painted region never meets a redaction, removing whole objects otherwise since a dropped clip would uncover hidden content; ReadRedactionClipPolygons exposes every accepted clip as its own TRedactionClipPoint list alongside the effective rectangle, and the TRedactionClipQuad overload projects each polygon onto four corners for callers that only need the bounding quadrilateral

PDFium's content generator cannot re-emit graphics-state dash arrays or content-stream alpha, so dashed strokes and path or text paint carrying transparency that intersects a redaction are removed whole; untouched objects keep their stream state verbatim, and image alpha still travels through the verified BGRA masking route

RequireMaskableImageState applies the legacy clip check. The high-level detailed profile can retain qualified image path clips with the optional native export, and verifies that the original image stream is removed before writing. ValidateRedactionClipGeometry checks the convex path subset for callers that use legacy Form expansion. CanRetainCroppedFillMarks reports whether the content marks of a path object can survive a retained fill under a cropping clip, and RewriteRedactionGlyphClip subtracts cut rectangles from a text object's serialised glyph clip, rejects any glyph whose paint leaves its own clip, and records the work in the cumulative report

CopyRedactionObjectMarks copies every content mark, numeric and string parameters included, from one page object onto another, so replacement objects keep the marked-content identity of their source

RepairRedactedTaggedStructure rebuilds a redacted output's structure tree: dead marked-content ids drop out, survivors renumber densely in content order, the parent tree is rebuilt from surviving page content, dead object references are pruned from /K, and the catalog is republished so the sparse update writer accepts the revision; the output is transactional and the source position is put back

ExtractRedactionAnnotationSpecs walks the active /Pages tree and annotation dictionaries to extract ISO 32000-1 §12.5.6.23 /Subtype /Redact metadata (/Rect, /IC, /OverlayText, /Repeat, /Q, and /DA), whilst ParseRedactionDefaultAppearance resolves standard-14 font names and AcroForm aliases (/Helv, /HeBo, /TiRo, /TiBo, /Cour) along with the Tf font size and g/G, rg/RG, or k/K colour operators

TPdfRedactionStructureOptions bounds the repair by way of ReadOptions, MaxElements 200000, MaxDepth 64, MaxContentStreams 10000 and a 512 MiB output budget; TPdfRedactionStructureReport reports Succeeded, HasStructure, removed element and renumbered stream counts through TPdfRedactionReport.StructureRepairReport

A TPdfRedactionPatternPage entry records the shading or tiling pattern state that a detailed redaction has to rewrite for one expanded page: whether a pattern is present, the boundary transform, boundary clip and stroke flags, plus the referenced pattern streams, and TPdfRedactionPatternPages collects them in page order

Direct callers must isolate a document copy, check native capabilities and finite positive allowances, discard failed copies, regenerate changed page content, then finish sanitisation and resource pruning before export

See Also

TPdf.SaveAsRedacted, TPdf.SaveAsSanitised, FPdfCompress