Technical Article

Shrinking PDFs in Delphi: Orphan Objects and Resource Dedup

A contract loses its twelve-page appendix in an editor, gains a merged cover sheet, and comes back from the save larger than it went in. Writing that file again through FPDF_SaveAsCopy with FPDF_NO_INCREMENTAL gives you a tidy single-revision PDF that still carries the deleted pages, their content streams and every scanned image they drew. The bytes are not in a hidden revision any more. They are ordinary objects in the new cross-reference table, listed as in use, and no page refers to any of them

Why does FPDF_SaveAsCopy keep deleted pages in the file?

PDFium keeps orphan objects because it loads every in-use cross-reference entry into its document and writes back whatever it holds, whether or not anything still points at it. ISO 32000-1 §7.5.6 defines an incremental update as new object versions plus a new xref section appended to the end of the file. Deleting a page appends a new page-tree node with a shorter /Kids array and a smaller /Count; the old page dictionary, its content stream and any font or image used only by that page stay listed as in-use objects. From the object table's point of view they are perfectly valid, so a full rewrite reproduces them faithfully

The same leftovers appear after page merges, form flattening done by other tools, and repair saves of damaged files. PDFium has no public call that lists indirect objects, deletes one, or rewrites references, so the cleanup cannot be expressed through its object API. It has to happen on the bytes

TPdf.SaveAsReachable, TPdf.SaveAsDeduplicated and TPdf.SaveAsFlateRecompressed in the PDFium Component for Delphi each ask PDFium for a non-incremental copy of the current document, parse that copy into an object graph in the wrapper layer, and write a new file containing a single classic revision. Because the starting point is PDFium's serialization of the loaded document, edits you made through TPdf before the call are part of the output. Objects that lived inside object streams come out as ordinary indirect objects, and the result always uses a plain xref table

Mark-and-sweep from two trailer roots

TPdf.SaveAsReachable keeps only the objects reachable from the trailer's /Root and /Info entries and drops the rest. The walk is depth-first with an explicit stack and a visited set, so reference cycles such as page-tree /Parent links or annotation /P back-pointers cannot hang it. A reference to an object number that is already free is simply not followed. Slightly damaged input gets through

The catalogue named by /Root leads to the page tree, page resources, fonts, images, Form XObjects, AcroForm, the structure tree, outlines, name trees, optional content, XMP metadata, output intents and embedded files. The document information dictionary is not on that list. ISO 32000-1 §7.5.5 hangs it off the trailer's /Info entry, outside the catalogue's graph entirely, so a sweep seeded only from /Root deletes the Title, Author and Producer of every file it touches. SaveAsReachable seeds the walk with both entries, and the rebuilt trailer carries /Info forward only when that object survived

PDFium Component TPdf.SaveAsReachable mark-and-sweep in Delphi: the depth-first walk is seeded from both trailer /Root to the catalogue and trailer /Info to the information dictionary, marks every reachable object, and writes swept orphans as free xref entries while survivors keep their original object numbers, so no reference is rewritten and object 0 heads the free list
SaveAsReachable seeds the walk with /Root and /Info, so the information dictionary survives while orphaned page objects become free entries

Object numbers stay where they were

Every surviving object keeps its original object number and generation. Swept objects become free entries in the xref table (ISO 32000-1 §7.5.4), gaps between live numbers are filled with free entries too, and object 0 remains the head of the free list. Since nothing is renumbered, every surviving reference is already correct and no object body has to be edited. The price is one unused xref line per swept object. Each line is 20 bytes. That trade is easy to accept: renumbering would mean rewriting every reference in the file and trusting an old-to-new mapping to be complete. The first element of the trailer /ID array is kept, and the second is recalculated because the file content changed

uses
  SysUtils, PDFium, FPdfCompress;

procedure PruneOrphans(const SourcePdf, TargetPdf: string);
var
  Pdf: TPdf;
  Report: TPdfPruneReport;
begin
  Pdf := TPdf.Create(nil);
  try
    Pdf.FileName := SourcePdf;
    Pdf.Active := True;
    if not Pdf.SaveAsReachable(TargetPdf, Report) then
      raise Exception.Create(Report.ErrorMessage);
    Writeln(Format('kept %d object(s), pruned %d; %d -> %d bytes',
      [Report.KeptObjectCount, Report.PrunedObjectCount,
       Report.SourceByteCount, Report.OutputByteCount]));
  finally
    Pdf.Free;
  end;
end;

TPdfPruneReport carries SourceByteCount, OutputByteCount, KeptObjectCount, PrunedObjectCount, Succeeded and ErrorMessage. Read SourceByteCount for what it is: the size of the non-incremental copy PDFium produced, which already lost the superseded revisions of the original. To report the saving a user actually sees, compare the target's size on disk with the size of the file you opened. The file-name overload writes to a temporary file in the target's directory and replaces the target only after the rewrite succeeded, so a failed run leaves whatever was there before untouched

What counts as a duplicate resource?

TPdf.SaveAsDeduplicated merges two resources only when their dictionaries, their whole reachable subgraphs and their raw stream bytes match. It runs the same reachability walk first, then looks at seven kinds of resources: fonts, image XObjects, Form XObjects, graphics state dictionaries (/ExtGState), colour spaces including ICC profile streams, shadings and patterns. Each group of matches collapses onto the member with the lowest object number, every reference in the file is rewritten to that survivor, and the merged copies become free xref entries just like orphans. Mail-merge and report tools that re-embed the same logo and the same font subset on every page they produce are the classic source of this bloat

Identity is a 64-bit FNV-1a fingerprint computed recursively. For each candidate, the walker takes the object body, replaces every N G R reference with the fingerprint of the object it points to, and hashes the result. That makes the value independent of numbering: two copies of the same font whose descriptors happen to be objects 12 and 87 still produce the same fingerprint. Results are memoized so a shared subobject is hashed once, and back edges return a fixed sentinel so cyclic graphs terminate. Fingerprints are only compared within one category, so a font and an image can never be merged even if their 64-bit values coincided

To find references safely, the scanner works on a copy of each object in which stream data, strings and comments are blanked out with spaces; otherwise a run of compressed pixel data that happens to read 12 0 R would be followed as a reference. Hash only that blanked copy, and two photos with identical dictionaries — same /Width, /Height, /BitsPerComponent, /Filter and /Length — collapse to one fingerprint. The second photo now shows the first. SaveAsDeduplicated appends the raw bytes between stream and endstream to the hashed data, so the pixels are part of the identity

PDFium Component TPdf.SaveAsDeduplicated identity rule: duplicate fonts, images and Form XObjects are fingerprinted by a recursive 64-bit FNV-1a hash over sanitized structure plus raw stream bytes, and equal fingerprints merge onto the lowest object number
Dedup identity combines the sanitized structure fingerprint with the raw stream bytes, so identical dictionaries with different pixels never merge

Reference rewriting uses the blanked copy in the opposite direction. References are located there, but the bytes written out are copied from the original body, so only dictionary and array structure changes and binary payloads pass through untouched

procedure MergeDuplicateResources(Pdf: TPdf; const TargetPdf: string);
var
  Report: TPdfDedupReport;
begin
  if not Pdf.SaveAsDeduplicated(TargetPdf, Report) then
    raise Exception.Create(Report.ErrorMessage);
  Writeln(Format('fonts %d, images %d, forms %d, gstates %d, ' +
    'color spaces %d, shadings %d, patterns %d merged',
    [Report.MergedFontCount, Report.MergedImageCount,
     Report.MergedFormXObjectCount, Report.MergedExtGStateCount,
     Report.MergedColorSpaceCount, Report.MergedShadingCount,
     Report.MergedPatternCount]));
  Writeln(Format('kept %d, merged away %d; %d -> %d bytes',
    [Report.KeptObjectCount, Report.PrunedObjectCount,
     Report.SourceByteCount, Report.OutputByteCount]));
end;

Read TPdfDedupReport with care. In this record PrunedObjectCount counts merged duplicates only; unreachable objects are still dropped, but they do not appear in that number. If your log needs the orphan count, take it from a SaveAsReachable run. Two more details matter when you compare outputs. Matching is byte-exact on the encoded stream, so the same logo compressed by two producers at two Flate levels stays two objects. And reachability is decided before merging, so the font descriptor and font program that only a merged-away font pointed to are still written in this pass. They become orphans in the output and disappear on the next rewrite

Recompressing Flate streams at maximum level

TPdf.SaveAsFlateRecompressed inflates each reachable stream whose dictionary names FlateDecode and deflates it again at the highest zlib level, keeping the result only when it is smaller and clears your thresholds. Plenty of producers write Flate at a fast default level, so content streams and embedded font programs often have room left. Object numbers and generations stay put; only the payload and its direct /Length change

TPdfFlateRecompressOptions has two fields and no constructor, so set both. MinSavingBytes is the minimum absolute saving per stream, and MinSavingRatio is a fraction of the original encoded length (0.05 means 5%); a ratio of 0 turns the ratio test off. Keep a floor on both. Without one, nearly every Flate stream is rewritten for a handful of bytes, which makes the output harder to diff against the source for no visible gain

Only the Flate layer is redone. For a filter chain such as [/FlateDecode /DCTDecode] the JPEG data inside is carried over bit for bit, and PNG-style predictor bytes declared in /DecodeParms survive because the payload is never un-predicted. A stream whose /Length is an indirect reference counts toward SkippedCount, because the rewrite stores a direct integer; so does any Flate stream that misses the thresholds. A payload that fails to inflate counts toward FailedCount and is copied unchanged. Streams encoded only with DCTDecode, JPXDecode, JBIG2Decode or CCITTFaxDecode are not candidates at all. For lossy image savings use adaptive image resampling with PDFium Component before the final save

procedure RecompressFlate(Pdf: TPdf; const TargetPdf: string);
var
  Options: TPdfFlateRecompressOptions;
  Report: TPdfFlateRecompressReport;
  Gain: Double;
begin
  Options.MinSavingBytes := 256;    // ignore tiny wins
  Options.MinSavingRatio := 0.05;   // and anything under 5%
  if not Pdf.SaveAsFlateRecompressed(TargetPdf, Options, Report) then
    raise Exception.Create(Report.ErrorMessage);
  Gain := 0;
  if Report.OriginalStreamBytes > 0 then
    // Plain "/" is real division in Delphi and FPC alike. Writing
    // Single(Report.OriginalStreamBytes) compiles in Delphi but FPC 3.2.2
    // rejects it: Illegal type conversion: "Int64" to "Single"
    Gain := 1 - Report.RecompressedStreamBytes / Report.OriginalStreamBytes;
  Writeln(Format('recompressed %d, skipped %d, failed %d; %.1f%% smaller streams',
    [Report.RecompressedCount, Report.SkippedCount, Report.FailedCount,
     Gain * 100]));
end;

OriginalStreamBytes and RecompressedStreamBytes total only the streams that were actually replaced, which is why the ratio above describes the recompressed set rather than the whole file. The cast in the comment is the portability trap worth knowing: in FPC, Single(x) on an Int64 is a typecast and not a numeric conversion

Which documents do the rewrites refuse?

All three APIs refuse encrypted documents and, by default, signed ones, and they report the two cases differently. An input whose trailer carries /Encrypt returns False with Succeeded = False and an ErrorMessage rather than raising. A single-revision rewrite cannot preserve the object numbers, byte ranges and per-object keys that the encryption dictionary depends on, so the output would not open. A document with digital signatures raises EPdfError before anything is written, unless you pass AllowSignedDocument = True as the last argument

That flag exists because a full rewrite always moves the bytes covered by each signature's /ByteRange, so every signature in the output will verify as broken. Pass it for an archive or search-index copy where the signatures were already validated and recorded somewhere else. Leave it at False for any file that is going back to a counterparty, and shrink the unsigned draft before it is signed instead

Running the three passes in order

Run SaveAsDeduplicated first, reload its output, then run SaveAsFlateRecompressed. Deduplication already includes the reachability sweep, so a SaveAsReachable pass in front of it adds nothing; keep SaveAsReachable for jobs that only want orphan cleanup and an exact pruned count. Recompressing second means the inflate-and-deflate work runs once per surviving stream instead of once per duplicate. The recompression pass also walks the graph from /Root and /Info again, which is what removes the descriptors and font programs orphaned by the merge

PDFium Component shrink pipeline order in Delphi: SaveAsDeduplicated runs first and already includes the reachability sweep, the output is reloaded, then SaveAsFlateRecompressed inflates each reachable FlateDecode stream and deflates it at maximum level keeping only wins above MinSavingBytes 256 and MinSavingRatio 5 percent, while SaveAsReachable stays the orphan-only tool
Run SaveAsDeduplicated first and recompress the reloaded output so the inflate-and-deflate work runs once per surviving stream
procedure ShrinkPdf(const SourcePdf, TargetPdf: string);
var
  Pdf, Reloaded: TPdf;
  TempPdf: string;
  SourcePages: Integer;
  SourceTitle: WString;
begin
  TempPdf := ChangeFileExt(TargetPdf, '.dedup.pdf');
  Pdf := TPdf.Create(nil);
  try
    Pdf.FileName := SourcePdf;
    Pdf.Active := True;
    SourcePages := Pdf.PageCount;
    SourceTitle := Pdf.Title;
    MergeDuplicateResources(Pdf, TempPdf);   // sweep + merge

    Pdf.Active := False;
    Pdf.FileName := TempPdf;
    Pdf.Active := True;
    RecompressFlate(Pdf, TargetPdf);         // sweep again + re-deflate
  finally
    Pdf.Free;
    DeleteFile(TempPdf);
  end;

  // Suggested check of your own: reopen the result before it replaces anything
  Reloaded := TPdf.Create(nil);
  try
    Reloaded.FileName := TargetPdf;
    Reloaded.Active := True;
    if (Reloaded.PageCount <> SourcePages) or (Reloaded.Title <> SourceTitle) then
      raise Exception.CreateFmt('Shrunk copy of %s does not match the source',
        [SourcePdf]);
  finally
    Reloaded.Free;
  end;
end;

The reload costs one parse. It catches the two losses a reader would notice first: missing pages and a blank document title. Because /Info is a root of every sweep, the title comparison should always pass on files whose information dictionary was intact; when it fails, the input deserves a closer look before anyone overwrites the original. To see what each stage contributed on your own documents, log the file size on disk after every step next to the report counters, and run the same file once through SaveAsReachable alone to separate orphan savings from merge savings

If the job also applies redactions, do those before any of this. Physically removing content is what creates new orphans in the first place, and the article on operator-level redaction and resource pruning covers that side of the pipeline

The PDFium Component for Delphi and C++Builder ships these three rewrites on TPdf, so the same component that renders and edits a document can also hand back a leaner copy of it