PDFium Delphi Component Docs

SaveAsRedacted method

Enterprise edition: link FPdfEnterprise with Lib\Enterprise on the search path; otherwise this method raises EPdfEnterpriseRequired; see the edition matrix

Component: TPdf  ·  Unit: PDFium
Applies PDF redaction annotations to an isolated snapshot and writes a clean single-revision result without modifying the loaded document

Syntax

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;

Description

SaveAsRedacted captures the current document into an isolated random-access snapshot, opens that snapshot as a separate TPdf, and processes every /Redact annotation rectangle

The default options enable both PreservePartialObjects and PreserveComplexObjects to retain supported safe geometry; this bounded profile rebuilds text from retained character fragments, clips solid filled paths, and clears intersecting pixels in affine images

When any redaction annotation exists, the detailed profile expands every Form XObject instance on every page, including unredacted pages, before applying redactions; instance transforms are composed and original shared Form streams can then be removed by resource pruning

Set PreservePartialObjects := False to remove whole intersecting objects, or keep it enabled and set PreserveComplexObjects := False to use the simpler text, axis-aligned rectangle, and axis-aligned image fragmentation profile. 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 to keep clipped content 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 sanitized rewrite with catalog /AF, active content, forms, metadata, and unreachable objects stripped. Page thumbnails, page and catalog /PieceInfo, page metadata, page /AF, page /AA actions, article beads and the catalog /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

The output has one clean revision without earlier document revisions, while the loaded source document remains unchanged; unsupported source semantics or unsupported detailed geometry abort the operation rather than producing a partially redacted result

Options

The Form, path, image, geometry, and tolerance options above are validated and used by the detailed profile; they do not raise the independent source inspection budgets

Opt-in isolated transparency rasterization

Since v3.248.0, RasterizeIsolatedTransparency = True enables a finite-resolution alternative for isolated transparency Forms and Alpha graphics soft masks while 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 rasterization 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/normalized 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; normalization must satisfy it over the whole content render, and the exact sanitized/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);

Opt-in complete page composition

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 rasterizer that reports PdfRedactionCompositeTransferFunctions also accepts custom graphics TR and TR2, so calibration functions no longer force a rejection; the ordinary native profile keeps rejecting them, and a rasterizer 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 color 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 sanitized 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 color-managed composite rasterizer 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);

Report

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 work adds ExpandedFormCount, ScannedFormChildCount, FlattenedCurveCount, GeneratedPathPointCount, MaskedImageCount, ScannedImagePixelCount, MaskedImagePixelCount, PixelIntersectionTestCount, and GeometryOperationCount; CurveTolerancePdfPoints records the configured tolerance after successful processing

ScannedFormChildCount counts native objects visited during expansion, including root Form instances, and GeneratedPathPointCount includes intermediate clipping points as well as flattened curve points

MaskedImagePixelCount counts pixels whose complete color and alpha samples were cleared, while PreservedFragmentCount counts replacement objects rather than individual retained pixels or polygon contours; processing counters on failure can be partial and do not imply a committed output

CMYK Forms and explicit page groups

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 rasterize 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, while 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

Security boundary

Since v3.203.1, partial stroke redaction checks the initialized 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, while intersecting dashed strokes still remove whole

Example

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;

See Also

SaveAsSanitised, SaveAsReachable, CreateAnnotation, FPdfRedaction geometry helpers