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, sanitization, and resource pruning
The helpers mutate native objects in the caller's isolated transaction copy and raise EPdfRedactionGeometry on unsupported geometry or exhausted budgets; they do not perform a complete secure export by themselves
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);
All redaction rectangles and curve tolerances use PDF user-space points; path points are transformed to page space before clipping, and ObjectIndex is the original zero-based native page-object index used to preserve painting order
ExpandRedactionForms recursively detaches text, path, and image children, composes nonsingular instance transforms and native clips, and inserts the expanded objects at the original Form position; a separate expansion of each shared instance avoids editing the original shared Form stream in placeClipRedactionPath accepts solid stroked, filled or mixed paths, reads the native dash state before permitting a stroke to split, flattens cubic segments with a bounded subdivision depth, subtracts rectangular cuts, and preserves winding or even-odd filling across retained contoursCurveTolerance + 0.001 PDF points; the tolerance bounds curve approximation and can remove a small additional margin outside the requested rectangleMaskRedactionImage accepts nonsingular affine transforms including rotation, reflection, and skew, and supported decoded Gray, BGR, BGRx, or BGRA samples; it retains the decoded resolution and creates a fresh replacement image0.001 PDF points has both its color and alpha bytes cleared; retained pixels keep their decoded color samplesValidateDetailedRedactionText requires normal filled text for partial retention; character mapping and fragment reconstruction remain the responsibility of the high-level methodExpansion and partial geometry reject transparency or blend states, unsupported child types, singular matrices, patterned fills, and complex or nonredundant clip paths; a supported redundant rectangular clip must contain the complete object bounds
| Option | Default | Meaning |
|---|---|---|
MaxFormDepth | 32 | Nested Form expansion depth |
MaxObjects | 1000000 | Page enumeration and cumulative expanded child limits |
MaxPathSegments | 262144 | Input segments per path and cumulative generated path points |
MaxFragments | 1000000 | Retained rectangle regions and cumulative replacement fragments |
MaxImagePixels | 16777216 | Cumulative decoded image pixels processed |
MaxGeometryOperations | 67108864 | Cumulative geometry and pixel intersection work |
CurveTolerance | 0.01 | Cubic flattening tolerance in PDF points |
Initialize options with TPdfRedactionGeometryOptions.Default and zero the report once before a transaction; keep the same report across helper calls so generated points, image pixels, fragments, and operation budgets 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
ExpandedFormCount and ScannedChildCount describe expansion; the visited count includes root Form instances as well as children; ClippedPathCount, FlattenedCurveCount, and GeneratedPointCount describe path work, including intermediate clipping points; MaskedImageCount, ScannedPixelCount, MaskedPixelCount, and PixelIntersectionTestCount describe image work
FragmentCount counts replacement objects rather than polygon contours or pixels, and GeometryOperationCount accumulates bounded helper work; a report left by an exception can describe partial work on the discarded transaction copy
Since v3.315.0, optional AllowCompositePages, default False, selects the complete-composition preflight used by RasterizeCompositePages; it permits native-renderable device-space composition while retaining 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 while retaining security/active-object limits and rejecting custom TR/TR2 functions unless the renderer advertises PdfRedactionCompositeTransferFunctions; this flag alone does not provide a color-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 retains Type3 glyph-program rejection and validates actual ExtGState resources separately so extra G/S keys cannot authorize graphics TR/TR2
From internal version 3.384.0, optional AllowCompositeTransfer, default False, admits custom graphics TR and TR2 only for a source renderer that reports PdfRedactionCompositeTransferFunctions; the Enterprise path derives it from GetCapabilities instead of asking the caller, so a bridge without 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 behavior and does not authorize 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
/ActualText and /Alt replacement payloads including #xx-escaped key spellings, and XFA are rejected, while Tagged structure and optional-content layers are preserved through the structure repair passTr operand, and scn/SCN pattern or special-color-space paint are rejected/FlateDecode filter; decoding is limited to 32 MiB per content stream and 64 MiB totalThe 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. TPdf.SaveAsRedacted can retain a supported straight or cubic Bézier fill under a complex path clip when the native clip-copy exports are available. With 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 with bevel, round, or supported miter joins, TPdf.SaveAsRedacted constructs the painted outline in object space before applying its affine matrix. Solid and supported dashed cubic Bézier strokes with butt, round, or projecting square caps use the same process, with or without a path clip. They preserve 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. When a qualified path has both fill and stroke, the original fill rule and color are retained beneath the rebuilt stroke. For supported dashed straight subpaths and open or closed polylines, it normalizes 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 when the source has 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 containing Type 3 text while 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. Multiple intersecting shows may share resources slated for removal. With matching native exports, eligible shared fonts with qualified path glyphs and font-level or glyph-local device color or constant alpha resources can retain unaffected glyphs after unused CharProc entries and their stream are removed. Font-level color and alpha entries used only by the removed glyphs 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. With 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 with shading or colored tiling patterns across multiple isolated content streams when each fill is disjoint from every redaction region and preceding streams restore their graphics state apart from supported affine transforms that the native module can replay exactly. The matching native module can also retain separate clipping streams with supported line and cubic Bézier contours, including implicit or explicit closures, concave contours, holes, and crossings within or between contours, including clips under a supported affine transform, when the actual clip contains every redaction region. A remaining active dependency on any of those resources prevents saving. Filled glyph paths can use aliases for device color 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 when 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 when the source has no path clip
ClipRedactionPath rebuilds stroked, filled or mixed paths: stroke colour, width, line join and line cap copy to the retained contour set, and the cut margin grows by half the matrix-scaled stroke width so 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, including non-containing rectangles) restricts painting, so RedactionClipCropsContent reports its effective region and the caller preserves untouched objects whose painted region never meets a redaction, removing whole objects otherwise because a dropped clip would reveal hidden content; ReadRedactionClipPolygons exposes every accepted clip as its own TRedactionClipPoint list alongside the effective rectangle, and the TRedactionClipQuad overload projects each polygon to 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 transparency-carrying path or text paint intersecting a redaction remove whole; untouched objects keep their stream state verbatim, and image alpha still converts through the verified BGRA masking route
RequireMaskableImageState applies the legacy clip check. The high-level detailed profile can retain qualified image path clips using the optional native export and verifies that the original image stream is removed before writing. ValidateRedactionClipGeometry checks the convex path subset for callers using legacy Form expansion. CanRetainCroppedFillMarks reports whether a path object's content marks can survive a retained fill under a cropping clip, and RewriteRedactionGlyphClip subtracts cut rectangles from a text object's serialized glyph clip, rejects a glyph whose paint leaves its own clip, and records the work in the cumulative report
CopyRedactionObjectMarks copies every content mark with its numeric and string parameters 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 prune from /K, and the catalog is republished so the sparse update writer accepts the revision; the output is transactional and the source position is restored
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), while ParseRedactionDefaultAppearance resolves standard-14 font names and AcroForm aliases (/Helv, /HeBo, /TiRo, /TiBo, /Cour) along with Tf font size and g/G, rg/RG, or k/K color operators
TPdfRedactionStructureOptions bounds the repair with ReadOptions, MaxElements 200000, MaxDepth 64, MaxContentStreams 10000 and a 512 MiB output budget; TPdfRedactionStructureReport reports Succeeded, HasStructure, removed elements and renumbered stream counts through TPdfRedactionReport.StructureRepairReport
A TPdfRedactionPatternPage entry records the shaded or tiling pattern state a detailed redaction must rewrite for one expanded page: the pattern presence, boundary transform, boundary clip and stroke flags plus the referenced pattern streams, and TPdfRedactionPatternPages collects them in page order
Direct callers must provide an isolated document copy, validate native capabilities and finite positive budgets, discard the copy on failure, regenerate modified page content, and complete sanitization and resource pruning before exporting