Technical Article

HotPDF Page Extraction Performance in Delphi

Two minutes to copy three pages out of a 40-page PDF is not a performance tuning problem. It is a signal that the wrong API path is being used. When I first saw this timing on page-copy code built on the HotPDF Delphi Component, my instinct was to look at the document structure first and the code second. That order turned out to be backwards

What was actually slow

The PDF in question was a 40-page reference document with a non-trivial page tree: multiple intermediate /Pages nodes instead of a single flat array. The code in question was calling LoadFromFile, then building a new document with BeginDoc, looping over selected page numbers, and on each iteration loading the source document again from disk to pull a page. That is the full parse cost multiplied by however many pages you want. A 12 MB file hit disk six times for a three-page extraction because nobody looked at whether the file needed to stay open across iterations

The second contributor was invisible in the code: HotPDF's LoadFromFile builds the in-memory object model the editing API works on. That is the right behaviour for a document you are about to modify, but it is more work than you need if you only want page count and a subset of pages. For read-only access to structure, DAOpenFileReadOnly avoids deserialising the full object tree, which matters on compressed files with large image resources

Both come down to choosing the API designed for one job and using it for a different one

Diagram contrasting repeated LoadFromFile calls inside an extraction loop against a single parse followed by ExtractPagesToFile for fast PDF page extraction in Delphi
Reloading the source on every iteration multiplies the full parse cost, turning a three-page copy into a two-minute job. One parse followed by a single extraction call brings the same work down to about 1.3 seconds

Using ExtractPagesToFile for page extraction

The right path for copying a range of pages out of a loaded HotPDF document into a new file is ExtractPagesToFile, called after LoadFromFile on the source. You load the source once, and the call builds the destination document, copies the selected pages into it, and writes it to disk, all from the copy that is already in memory:

procedure ExtractPages(const SourceFile, DestFile: string;
  const PageRange: string);
var
  Source: THotPDF;
begin
  Source := THotPDF.Create(nil);
  try
    // Load source once: full parse happens here and only here
    if Source.LoadFromFile(SourceFile) <= 0 then
      raise Exception.Create('Source PDF has no pages');

    // Write the requested range ('1-3', '1,5,7-9') straight to a new file
    Source.ExtractPagesToFile(DestFile, PageRange);
  finally
    Source.Free;
  end;
end;

The PageRange parameter accepts the same format as the command-line sample: a comma-separated list of page numbers or ranges such as '1-3' or '1,5,7-9'. Pages are 1-based. ExtractPagesToFile copies each selected page together with the content streams and resources it references, so for a three-page extraction from a 40-page document the working set stays small

Timing on the same 12 MB file that previously ran for two minutes: about 1.3 seconds with this pattern. Most of that time is the single LoadFromFile call. The document structure is irrelevant once the object table is resolved the first time

When LoadFromFile is too much: the Direct File API

If you only need to count pages, inspect document info, or copy a file without touching its contents, the Direct File API avoids the full parse entirely. DAOpenFileReadOnly maps the cross-reference table without decompressing object streams, so page count is O(xref size) rather than O(file size):

procedure InspectPDF(const FileName: string);
var
  Pdf: THotPDF;
  Handle, PageCount: Integer;
begin
  Pdf := THotPDF.Create(nil);
  try
    Handle := Pdf.DAOpenFileReadOnly(FileName, '');
    if Handle <= 0 then
      Exit;
    try
      PageCount := Pdf.DAGetPageCount(Handle);
      Writeln('Pages: ', PageCount);

      // DACopyFile is a byte-preserving copy, no re-serialization
      Pdf.DACopyFile(FileName, 'archive-copy.pdf');
    finally
      Pdf.DACloseFile(Handle);
    end;
  finally
    Pdf.Free;
  end;
end;

The caveat: DAOpenFileReadOnly accepts a password parameter but falls back to a full parse for encrypted inputs, because decryption requires the object tree to resolve the encryption dictionary. If your source files are encrypted, decrypt them first with DecryptFile to get an unencrypted copy, then open that with the Direct File API. The file-level DecryptFile function takes a direct AES-256 rewrite path for standard encryption and is faster than LoadFromFile followed by SaveLoadedDocument for large files, because it does not build the full in-memory object model

Decision diagram choosing between the full HotPDF editing path and the read-only Direct File API, with decryption handled first for encrypted inputs
Read-only tasks belong on the direct file access path, where page counting scales with the cross-reference table instead of file size. Encrypted inputs fall back to a full parse unless decrypted first

Memory during large-batch processing

Batch jobs that process dozens of files in a loop have a pattern that looks correct but accumulates memory: creating THotPDF inside the loop, calling LoadFromFile, doing work, calling Free. That is structurally fine. The problem is when the inner work allocates scratch objects, catches exceptions, and leaves those scratch objects live on error paths. Delphi's memory manager does not compact, so a hundred error-path leaks across a batch run can push memory high enough to slow allocation for everything else

The fix is not exotic. Every THotPDF and every intermediate TStream or TBitmap that participates in PDF work belongs in a try/finally block where Free is the last statement. Set local pointers to nil before the try so the finally branch can use if Assigned(x) then x.Free safely when initialisation fails partway through. This is standard Delphi ownership discipline and it is the full story for this class of problem

One more thing to know in batch contexts: AddImage registers each image with the document being built, and HotPDF releases those registrations when EndDoc finishes that file. The registry follows the BeginDoc/EndDoc cycle, not LoadFromFile, so the clean pattern for a batch is one THotPDF instance per document: create it, do the work, save, free it

Measuring before changing anything

Before reaching for any of these patterns, measure. Delphi's TStopwatch from System.Diagnostics wraps QueryPerformanceCounter and is accurate enough for wall-clock profiling of file I/O. Wrap LoadFromFile alone and see how long it accounts for. If it is 90% of the total time, the fix is the Direct File API or reducing how many times you parse the same file. If it is under 20%, the bottleneck is somewhere else and you are chasing the wrong thing

The two-minute extraction that started this post turned out to be entirely the repeated-load pattern. The document structure contributed nothing; a flat page tree would have run the same way. Switching to a single LoadFromFile followed by one ExtractPagesToFile call brought it to about 1.3 seconds on the same hardware without touching anything else

The page manipulation API shown here is part of the HotPDF Delphi Component for Delphi and C++Builder