Enterprise edition: link FPdfEnterprise with Lib\Enterprise on the search path; otherwise this method raises EPdfEnterpriseRequired; see the edition matrix
function SaveAsRedacted(Stream: TStream;
const Options: TPdfRedactionOptions;
out Report: TPdfRedactionReport): Boolean; overload;
function SaveAsRedacted(const FileName: string;
const Options: TPdfRedactionOptions;
out Report: TPdfRedactionReport): Boolean; overload;
SaveAsRedacted captures the current document into an isolated random-access snapshot, opens that snapshot as a separate TPdf, and processes every /Redact annotation rectangle
Defaults enable PreservePartialObjects and PreserveComplexObjects together to keep supported safe geometry; this resource-limited profile reconstructs retained text fragments, clips solid-filled paths and clears intersecting affine-image pixels
If there is any redaction annotation, the detailed profile expands every Form XObject instance on all pages, including unredacted ones, before applying cuts; composed instance transforms allow the original shared Form streams to be pruned afterwards
Set PreservePartialObjects := False to remove entire intersecting objects, or leave it enabled and use PreserveComplexObjects := False for simpler text, axis-aligned rectangle and axis-aligned image fragmentation; all three profiles run the source safety checks. Its path and image fragments keep their original paint order and supported content marks. Intersecting paths and images with a native clipping path are removed whole, so clipped content stays hidden
The method removes all redaction annotations, optionally removes other intersecting annotations, removes file-attachment annotations on redacted pages, deletes native embedded attachments, strips the embedded streams of every remaining file specification, and runs the sanitised rewrite with catalogue /AF, active content, forms, metadata and unreachable objects stripped. Page thumbnails, page and catalogue /PieceInfo, page metadata, page /AF, page /AA actions, article beads and the catalogue /Threads are removed as well. Bookmark (/Outlines) titles are kept as they are and are not redacted
After page content is regenerated, precise resource pruning scans page, Form XObject, pattern, appearance, inherited and nested resource scopes and removes only unused names before unreachable objects are discarded
Output contains one clean revision without earlier revisions, and the loaded source stays as it was; unsupported source semantics or detailed geometry abort the operation instead of yielding partial redaction
FillColor — the opaque replacement colour, initially clBlackRemoveIntersectingAnnotations — removes non-redaction annotations whose rectangles overlap a redaction rectangle, default TrueMaxPageObjects — maximum number of top-level page objects scanned across redacted pages, default 1000000PreservePartialObjects — retains supported non-intersecting text, path and image fragments, default TrueMaxSplitObjects — maximum number of safe fragments created across the operation, default 1000000PreserveComplexObjects — with PreservePartialObjects enabled, allows limited Form expansion, solid-fill path clipping and affine-image pixel clearing; defaults to TrueMaxFormDepth — deepest nested Form expansion, initially 32, accepting 1..64MaxPathPoints — allowance for segments in each affected path and total generated path points, initially 262144, accepting 1..1000000MaxImagePixels — total decoded pixels handled by detailed image replacement, initially 16777216, accepting 1..67108864MaxGeometryOperations — accumulated detailed work, including annotation/text scans, path subdivision and clipping, and pixel intersections, initially 67108864, accepting 1..1000000000CurveTolerancePdfPoints — page-space cubic-flattening tolerance, initially 0.01, accepting finite 0.0001..0.1; cuts expand by this tolerance plus 0.001 PDF points, which may remove a narrow extra safe marginOverlayText, RepeatOverlayText, OverlayFontName, OverlayFontSize, OverlayTextColor, and OverlayAlignment — fallback replacement text styling for redaction boxes when individual /Subtype /Redact annotations do not override /OverlayText, /Repeat, /DA, /Q, or /ICThe detailed profile validates and uses the Form, path, image, geometry and tolerance settings above; none raises the separate source-inspection allowances
Since v3.248.0, RasterizeIsolatedTransparency = True enables a finite-resolution alternative for isolated transparency Forms and Alpha graphics soft masks whilst retaining the default rejection policy when disabled
This option requires both detailed preservation flags; when any redaction exists, every Form instance and transparency-carrying top-level object on every page is rendered separately on transparent BGRA and replaced at its original painting position before normal pixel redaction
Text and vector semantics inside those converted objects become image samples, including on unredacted pages; outside top-level native text remains searchable, and this policy does not preserve resolution-independent vector detail or every original tagged relationship
Since v3.319.0, retained-layer rasterisation also revokes non-rendering Form aliases and their indirect private ownership branches, including arrays, cycles and nested Forms, and removes stale page thumbnails before publication
Since v3.319.1, the same cleanup also revokes non-rendering image XObjects and their private ownership branches, including images painted with graphics-state opacity and fully transparent images; effective resources include bounded page-tree inheritance so that still-visible images and independent annotation appearance images remain available
Transaction-local provenance identifies original page-owned Forms through the native save; an original Form that remains reachable through active rendering resources or an annotation appearance rejects the operation instead of deleting a required appearance or publishing the original stream
Resource-graph inspection shares MaxGeometryOperations, limits nesting to 64, and uses the active-object reader's bounded source and object inventory; both early and final cleanup failures preserve the destination and loaded source
This Form/image cleanup does not certify arbitrary unrelated private payloads or general retained active-source reuse; image soft masks retain the isolated profile's rejection, annotation painting remains outside the retained-layer native pixel comparison, and independent appearance resources keep their ordinary retention policy
Groups must be Form XObjects with explicit resources, /S /Transparency, /I true, absent or false /K, and explicit /DeviceRGB or /DeviceGray blending
Graphics soft masks require /S /Alpha, a G Form satisfying that group profile, no backdrop /BC and absent or Identity /TR; page groups, nonisolated/knockout groups, luminosity masks, custom transfer, image soft masks, non-normal blending, optional-content state and inactive page objects remain rejected
Non-normal blending is judged on page content. A stream reachable only as an annotation appearance (an /AP target of a dictionary carrying /Type /Annot, or /Rect when the producer omits /Type) is exempt: the redaction removes every annotation it overlaps and copies each surviving appearance out byte-identical, so its blend mode is never re-composited by the rewrite. This is what lets a document whose highlights PDFium renders with /BM /Multiply be redacted at all
TransparencyDpi defaults to 144 with range 72..600; raster dimensions follow the effective CropBox and intrinsic rotation and must not exceed 32768 pixels per side
MaxTransparencyPixels defaults to 16777216 with range 1..67108864 and cumulatively covers retained layer bitmaps, original/normalised composition checks and original/final saved-output renders; normal image pixel budgets apply independently during masking
MaxTransparencyChannelDelta defaults to 2 with range 0..8 on 8-bit rendered channels; normalisation must satisfy it over the whole content render, and the exact sanitised/pruned saved bytes must satisfy it outside redaction rectangles plus a one-pixel antialias halo before publication
Rendering comparisons exclude annotation appearances, which retain the ordinary annotation-removal policy; native rendering and decoding are synchronous, and these finite checks do not prove equivalence at other scales, optional-content states or processors
RasterizedTransparencyObjectCount and RasterizedTransparencyPixelCount report converted layers, TransparencyVerificationPixelCount reports comparison renders, and TransparencyMaximumChannelDelta records the largest observed difference
Options := TPdfRedactionOptions.Default; Options.RasterizeIsolatedTransparency := True; Options.TransparencyDpi := 144; // Accept the documented loss of vector and searchable text semantics in converted Forms if not Pdf.SaveAsRedacted(OutputStream, Options, Report) then raise Exception.Create(Report.ErrorMessage);
Since v3.315.0, RasterizeCompositePages = True, default False, provides a separate whole-document raster strategy for backdrop-dependent nonisolated and knockout groups, Luminosity masks, supported blend modes and mask transfer functions in device blending spaces
From internal version 3.384.0 a composite rasteriser that reports PdfRedactionCompositeTransferFunctions also accepts custom graphics TR and TR2, so calibration functions no longer force a rejection; the ordinary native profile continues to reject them, and a rasteriser without that capability leaves the source rejected
Explicitly set PreserveTaggedStructure = False; both detailed preservation flags must remain enabled for bounded pixel clearing; this strategy deliberately discards all page-content text, vector, tag and interactive annotation semantics on every page when any redaction exists, including unredacted pages
Page content and annotation appearances are composed against white before redaction, then colour and alpha samples touching the redaction rectangles are cleared and the ordinary opaque replacement/overlay policy is applied; source annotation appearances are never replayed after masking, including when RemoveIntersectingAnnotations = False
Only final visible pixels and page geometry enter a fresh sanitised document; original content streams, semantic MCR references, ActualText/Alt/expansion payloads, private catalog/page aliases, thumbnails and annotation metadata cannot survive through retained source references
The clean output retains page count, supported MediaBox/CropBox/other page boxes and intrinsic rotation; every output page has one opaque RGB image, and searchable overlay text becomes pixels along with the other page content
CompositeOutputPixelCount counts the final clean-document rasters, RemovedTaggedStructure reports discarded source structure, and RemovedAnnotationCount includes annotations flattened into the final image; source structure is discarded rather than repaired or certified
The existing DPI, pixel, image and operation budgets remain cumulative; the clean-document render is charged in addition to initial composition and final-byte verification, so the pixel budget describes aggregate work rather than an exact native-memory ceiling
Final saved bytes are reopened and compared with the original complete page render, including annotation appearances, outside redaction rectangles plus a one-pixel antialias halo; failure preserves the loaded source and destination bytes/position
The default native path rejects ICC/CIE blending groups and Default* blending-space overrides before publication because its retained ICC RGB discrepancy reaches 18 channel levels; since v3.317.0, an explicitly selected colour-managed composite rasteriser supplies an alternative source-rendering path, with its own qualified limits and capability-gated soft-mask transfer support
Since v3.316.0, complete composition supports page-local positive UserUnit values up to 75000, including bounded indirect scalar references; physical raster dimensions, pixel clearing, cumulative budgets and final-byte verification explicitly include the scale ignored by native page geometry
Only the validated numeric unit enters the fresh page dictionary, retaining the original physical size with its page boxes and rotation; invalid or unresolved units, reference cycles, raster sides over 32768 pixels and cumulative budget exhaustion reject without changing destination bytes or position
Signed sources, AcroForm and XFA remain excluded; native rendering is synchronous, and finite-DPI/channel checks do not establish resolution-independent detail, appearance equality on other processors or PDF/UA conformance
Options := TPdfRedactionOptions.Default; Options.RasterizeCompositePages := True; Options.PreserveTaggedStructure := False; Options.TransparencyDpi := 144; if not Pdf.SaveAsRedacted(OutputStream, Options, Report) then raise Exception.Create(Report.ErrorMessage);
TPdfRedactionReport returns RedactionCount, RedactedPageCount, ScannedObjectCount, RemovedObjectCount, RemovedAnnotationCount, RemovedAttachmentCount, OverlayCount, OverlayTextCount, SplitTextObjectCount, SplitPathObjectCount, SplitImageObjectCount, PreservedFragmentCount, the byte counts, nested SanitiseReport and ResourcePruneReport, Succeeded, and ErrorMessage
Detailed processing adds ExpandedFormCount, ScannedFormChildCount, FlattenedCurveCount, GeneratedPathPointCount, MaskedImageCount, ScannedImagePixelCount, MaskedImagePixelCount, PixelIntersectionTestCount and GeometryOperationCount; successful processing records the chosen tolerance in CurveTolerancePdfPoints
ScannedFormChildCount includes every native object visited during expansion, including root Form instances; GeneratedPathPointCount includes intermediate clipping points and flattened-curve points alike
MaskedImagePixelCount counts pixels cleared in every colour and alpha sample; PreservedFragmentCount counts replacement objects rather than pixels or contours, and failed processing may leave partial counters without committed output
Since v3.260.0, the isolated Form raster policy also accepts explicit DeviceCMYK blending, retaining the same isolation, normal-blend, Alpha-mask, no-knockout and no-backdrop restrictions
Separately enable RasterizeIsolatedPageGroups, default False, together with RasterizeIsolatedTransparency to rasterise an isolated DeviceRGB, DeviceGray or DeviceCMYK page group as a single full-page composite
The page-group policy deliberately replaces all content and searchable text on each converted page, including content outside the redaction rectangle; annotations continue through the ordinary annotation policy
RasterizedTransparencyPageCount counts whole-page composites; object and pixel counters include the replaced objects and one full-page layer respectively, whilst all rendering shares the existing transparency pixel/work budgets
After physical RGB/alpha clearing, obsolete page Group declarations and unreachable original streams are removed before the exact saved output is reopened and compared outside the redaction area at the selected DPI and channel threshold
Removing the old blending group prevents the new RGB composite from being interpreted again through its original page blending space; nonisolated, knockout, special/ICC blending spaces and backdrop-dependent groups remain rejected
The isolated raster options reject tagged sources because retained semantic MCR references can keep original Form streams alive; the ordinary non-raster tagged-redaction profile and the explicit complete-composition strategy retain their separate structure policies
Rebuild packages and clients and regenerate C++ headers after the public option/report record additions
0.001 PDF points, RGB and alpha are both cleared; an opaque FillColor overlay then covers the redaction rectangle/Decode endpoints in the range [0, 1]. It also accepts Indexed images with a DeviceGray or DeviceRGB base, default decoding or an explicit /Decode pair of integer endpoints inside the palette index range, and a complete palette stored as a direct or indirect string, an unfiltered stream, or a single /FlateDecode stream without decode parameters. The replacement stores the decoded colours. It erases pixels through the image transform even where the clip already hides them, removes private aliases to the original stream, and refuses output where a retained rendering dependency still references that stream/ActualText or /Alt replacement payloads and XFA; PreserveTaggedStructure defaults to true and mends Tagged relationships and optional-content layers by way of dense marked-content renumbering and a rebuilt parent tree, with counters kept in StructureRepairReport; the separate complete-composition strategy accepts semantic payloads only because all source content and structure are discardedArtifact marks and marks carrying a single nonnegative integer MCID. The optional FPDFTextObj_GetRedactionStrokePadding export also enables supported solid horizontal stroke and fill-and-stroke text with an untransformed stroke state. With FPDFTextObj_CreateRedactionGlyph the same glyph-preserving process also handles supported invisible, stroke and fill-and-stroke text without a path clip. A conservative stroke bound can remove a neighbouring glyph near the redaction area. With the optional native glyph-clip exports, the vector profile supports clip-only text (7 Tr) and qualified opaque fill, stroke or fill-and-stroke text with clipping (4 Tr through 6 Tr) on pages and in eligible Form XObjects followed by qualified solid path fills. The clip must use one Tj with a literal or hexadecimal string, or one TJ array of strings and numeric spacing adjustments, inside a text object and a graphics-state scope closed within the same content stream. The vector profile subtracts redaction regions from the serialised clip geometry itself. It removes clip-only text, converts visible clipping text to the corresponding ordinary paint mode, and retains supported glyphs whose paint bounds lie outside the redaction regions. Stroked clipping text needs the native stroke-padding export and the supported untransformed solid stroke state. A glyph that crosses a cut is removed from the visible text as a unit. Form instances are expanded and their glyph clips are cut in page coordinates. ISO 32000-2 §9.3.6 excludes Type 3 glyphs from text clipping geometry. With the optional FPDFTextObj_UsesType3Font export, documents can retain Type 3 text on separate pages that need no redaction, Form expansion or glyph clip rewrite. With FPDFTextObj_GetRedactionType3Bounds, a page undergoing detailed vector redaction, with or without glyph clipping, can retain eligible Type 3 text on the page or in expanded Forms whose paint bounds lie outside all redaction regions. The rewrite preserves Tc character spacing, Tw word spacing and TJ adjustments. This path requires opaque fill text with filled glyph paths and accounts for the path geometry even where the declared glyph bounds are smaller. The font and its glyph streams can declare aliases for DeviceGray, DeviceRGB or DeviceCMYK in direct or indirect local resource dictionaries. A glyph stream can override a font-local alias. Local ExtGState dictionaries may state constant alpha through ca and CA. The rewrite can remove several intersecting shows that share a font or glyph resources. For eligible shared fonts with qualified path glyphs, it can remove unused CharProc streams and every alias to those streams from the font. The shared font retains the colour and alpha entries its surviving glyphs need and drops entries that only removed glyphs used. An active reference to a revoked resource prevents the save. Indirect glyph-local dictionaries are revoked together with the removed glyph. Where retained content still depends on one of those dictionaries, the exporter refuses to save. The exporter checks retained page and appearance text and external object references before pruning. It supports shading patterns and eligible tiling patterns with explicit resources in annotation-only appearances. It inspects tiling cells for references to the glyph being removed, encoding aliases included. Without glyph clipping, the exporter can preserve pattern paint on unredacted pages that need no Form expansion and do not share the pattern-bearing content stream with a redacted page. Without glyph clip rewriting or Form expansion, a redacted page can retain pattern fills across several isolated content streams with FPDFPage_GenerateRedactionContentWithPatternStreams. With FPDFPage_GenerateRedactionContentWithPatternStream it can retain one isolated content stream. With FPDFPage_GenerateRedactionContentWithPatternPaintStreams, a stream can also retain rectangular strokes in isolated graphics state scopes with a resolved shading or coloured tiling pattern and an explicit positive line width up to 4,096. Matching native modules from internal version 3.431.76 also retain open or closed subpaths with straight or cubic Bézier segments. Detailed redaction supports up to four subpaths per stroke and 16 explicit line or curve segments across those subpaths. A dash array of up to 16 nonnegative entries and its phase may precede the path. A nonempty array must hold a positive entry. Consecutive strokes in one balanced graphics state scope can reuse the selected pattern and stroke settings. An explicit pattern switch before the next stroke must resolve to an eligible resource and be followed by an explicit positive line width. In the same scope, a finished path paint can be followed by a switch between /Pattern cs and /Pattern CS, an explicit pattern selection, and a separate fill or stroke. Each paint must qualify for retention on its own. Pattern fills also support up to four subpaths and 16 explicit straight or cubic Bézier segments per paint. A fill keeps its original nonzero or even-odd rule and must have a conservative path bound disjoint from every redaction region. Line cap, line join and miter settings may precede the path in the isolated scope. A conservative bound that includes the curve control points, line caps and maximum mitre extent must be disjoint from every redaction region. Each protected stream can follow streams whose supported operators restore the initial graphics state and leave no open text object or pending path. With FPDFPage_GenerateRedactionContentWithTranslatedPatternStreams, preceding streams may also end with a pure translation after their balanced graphics state scopes. Matching native modules from internal version 3.431.76 support translation components in increments of 1/16 PDF user-space unit. For translation-only modules, both translation components and their cumulative offsets must stay within 4,096 PDF user-space units in either direction at every stream boundary. With FPDFPage_GenerateRedactionContentWithAffinePatternStreams, each stream may instead end with one affine matrix whose operands are multiples of 1/16 and bounded by 4,096 in magnitude. The native module checks that inverses and boundary deltas can be serialised and replayed exactly. It refuses singular matrices and fills whose transformed bounds intersect the redaction regions. With FPDFPage_GenerateRedactionContentWithClippedPatternStreams, a page can also retain separate streams that hold only a rectangular clip defined by re W n or re W* n. Each clip must contain every redaction region so the overlay can cover it completely. With FPDFPage_GenerateRedactionContentWithAffineClippedPatternStreams, the clip may inherit an exactly replayable affine transform. In that case every redaction corner must lie inside the transformed clip itself, with strict containment where the clip carries a nonidentity transform. Matching native modules from internal version 3.431.76 accept up to four closed straight-line contours per clipping stream, each with 3 to 16 vertices. They also accept cubic Bézier segments (c, v and y) within those contours. The vertex limit counts the start point and segment endpoints, an explicit endpoint at the contour start included. A final line or cubic segment can return to the start before the close operator. Those modules also retain subpaths that the clipping fill rule closes implicitly and check the implied closing edges. The exporter retains the original curve operators and refuses to save where bounded subdivision cannot certify separation from every redaction rectangle. Coordinates must be multiples of 1/16 within 65,536 user-space units in either direction. Contours may be concave or nested. The same modules also accept intersections between separate contours. The exporter checks the specified nonzero winding or even-odd rule and requires each redaction rectangle to lie entirely inside the transformed filled area. The native module also supports self-crossing contours. In this profile it refuses degenerate edges and any contour edge inside or touching a redaction rectangle. For the first content stream, the optional FPDFPage_GenerateRedactionContentWithFirstPatterns export supports several fills, and modules that expose only FPDFPage_GenerateRedactionContentWithFirstPattern support one fill. The stream must be private to the page and hold only the fills within balanced graphics state scopes. Each fill must use a resolved shading pattern or a coloured tiling pattern with explicit resources and be disjoint from every redaction region. If the stream would be rewritten, or the pattern still uses a Type 3 glyph slated for removal, the export fails. Removing an eligible show also revokes its indirect alpha state dictionaries. Removing an eligible show also revokes its indirect colour resource dictionaries. A retained dependency on those dictionaries prevents the save. Expanded Form text is evaluated after transformation into page coordinates and retains supported path clips, the Form bounding box included. With FPDFTextObj_MarkRedactionType3Source, a qualified intersecting show is removed as a unit. The exporter revokes its indirect font and glyph streams, private aliases included, and refuses to save where a retained page or appearance still depends on a revoked resource. It also refuses unsupported Type 3 text and rewrites whose required exports are unavailable. It accepts an unused clipping rendering mode where the same content stream explicitly resets it, or restores an earlier nonclipping graphics state, before any glyph is shown. The preflight checks intervening text positioning and spacing operands and rejects saved clipping states that could be restored in a later stream. RasterizeCompositePages can preserve the resulting appearance outside the redaction area in a fresh raster-only document, with no source text objectsArtifact marks and marks with a single nonnegative integer MCID qualify. Text clips, clips that exceed the configured budgets and other cropped paint use conservative handling. Older DLLs keep the convex-clip pathFPDFPageObj_GetStrokeMiterLimit export enables miter joins on supported rebuilt polylines and cubic Bézier strokes, with the original limit selecting a miter or bevel at original corners. Subdivision points within each curve use round joins to approximate the smooth outline. A qualified path with both fill and stroke keeps the original fill rule and colour beneath the rebuilt stroke. Both paints are cut and retain the applicable path clip. Stroke-to-fill conversion can change edge antialiasingTr operands, and scn/SCN pattern or special-colour-space paint; supported inspected content streams are unfiltered or use a single named /FlateDecode filter; complete composition uses its separate native-renderable device-blending profile and fresh-document boundary256 MiB of source data, 64 MiB per active body, 256 MiB of active bodies, 64 MiB per decoded object stream and 256 MiB of them altogether, and 1000000 object slots; checked-content decoding separately allows 32 MiB per stream and 64 MiB overall/AF, the /Names tree, native embedded attachments and file-attachment annotations on redacted pages are removed; every other file specification in the output, one in a file-attachment annotation on an unredacted page, an /AF array of an annotation, XObject or structure element, or a GoToE action for instance, loses its /EF and /RF references, escaped keys in dictionaries nested within indirect arrays included. Removed entries are counted in RemovedAttachmentCount/Redact annotations, calling the method produces sanitised single-revision security outputSince v3.203.1, partial stroke redaction checks the initialised native dash count before splitting, fixing spurious solid-stroke rejection on FPC Win32; two-point strokes and open polylines retain their safe segments without added closing edges, whilst intersecting dashed strokes still remove whole
var
Options: TPdfRedactionOptions;
Report: TPdfRedactionReport;
begin
Options := TPdfRedactionOptions.Default;
Options.FillColor := clBlack;
if not Pdf1.SaveAsRedacted('C:\redacted.pdf', Options, Report) then
raise Exception.Create(Report.ErrorMessage);
end;