Technical Article

Render PDF Pages to Bitmap in Delphi with HotPDF

A thumbnail strip for a batch of supplier invoices looks right at a glance: table rules in place, logo crisp, columns aligned. Zoom into one and the customer name is a row of hollow boxes, while the totals column holds letters that spell nothing. Every broken invoice uses the same font, ABCDEF+Arial, and every one of them reads fine in a desktop PDF viewer on the same machine. The thumbnail code took the font name, dropped the six-letter subset tag, asked Windows for Arial and handed it the raw character codes from the page. Those codes were never Arial's. Getting a faithful bitmap out of a PDF page takes two things: running the page's content stream as a program, and drawing text from the glyph outlines stored in the file instead of from whatever fonts the rendering machine happens to have installed

A PDF page is something you execute

ISO 32000-1 §8 describes a page as a content stream: operators that change the transformation matrix with cm, save and restore graphics state with q and Q, build paths, select fonts with Tf, place glyphs with Tj, and paint images and forms with Do. Nothing in the file records what any pixel looks like. To get a bitmap, something has to run that stream against a current transformation matrix, a state stack, a clipping path and a pair of fill and stroke color spaces, then rasterize whatever comes out

HotPDF's RenderLoadedPageToBitmap is that interpreter. It walks the operators of a loaded page, keeps the matrix and graphics state the way the specification defines them, resolves color spaces, turns PDF paths into GDI paths, and takes glyph advances from the font's /Widths array rather than from GDI. Image XObjects go through the same decoders the library uses for extraction, so every image filter HotPDF can decode for extraction, JPXDecode-compressed JPEG 2000 images included, also shows up in the rendered page

HotPDF page rendering pipeline: a PDF content-stream interpreter tracks the transformation matrix, graphics state, color spaces, paths, glyph widths and embedded glyph outlines, and returns a caller-owned 24-bit RGB TBitmap
Each operator updates the matrix, graphics state, color, path or text state it touches, and the result is one caller-owned bitmap

Rendering a loaded page to a TBitmap in Delphi

THotPDF.RenderLoadedPageToBitmap(PageIndex, DPI) takes a zero-based page index and a resolution in dots per inch, where 72 DPI maps one PDF unit to one pixel, and returns a new 24-bit RGB TBitmap. An out-of-range index or a page that cannot be built returns nil instead of raising. That suits a viewer, which should skip one damaged page and carry on with the rest. The bitmap belongs to the caller

var
  Pdf: THotPDF;
  Bmp: TBitmap;
begin
  Pdf := THotPDF.Create(nil);
  try
    if Pdf.LoadFromFile('report.pdf') > 0 then
    begin
      Bmp := Pdf.RenderLoadedPageToBitmap(0, 144);  // first page at 144 DPI
      if Bmp <> nil then
      try
        Image1.Picture.Assign(Bmp);
      finally
        Bmp.Free;  // the caller owns the returned bitmap
      end;
    end;
  finally
    Pdf.Free;
  end;
end;

Pixel dimensions follow from the page's visible area. The renderer takes /CropBox clipped to /MediaBox, as ISO 32000-1 §14.11.2 defines the visible region, uses /MediaBox when there is no usable crop box, scales by DPI/72 and rounds up. A US Letter page without a separate crop box therefore comes back as exactly 612×792 pixels at 72 DPI. An A4 page (595.28×841.89 points) at 96 DPI works out to 794×1123, because 793.7 and 1122.5 both round up. A /Rotate of 90 or 270 swaps width and height, and the flip from PDF's bottom-left origin to GDI's top-left happens inside the page matrix, so the image arrives upright with no post-processing

DPI is the only scaling knob, and it covers the common jobs. Thumbnails at 36 or 48 DPI are small and quick. A screen preview at 96 or 144 DPI matches typical display density. Export at 300 DPI gives print-grade output, at the price of a 2550×3300 bitmap for every Letter page, roughly 24 MiB each at three bytes per pixel

Why do substituted fonts draw the wrong glyphs?

Wrong glyphs in a rendered PDF almost always mean the rasterizer swapped in an installed font for the one embedded in the file. The shortcut from the invoice example is tempting because it often works: strip the subset prefix from /BaseFont, request a GDI font by the remaining name, draw the string. For plain Arial or Times New Roman text with standard encoding, nobody complains

Subset fonts break it first. A subset may carry only the forty glyphs a document uses, numbered in an order private to that file, so code 1 might be "T" and code 2 "h". An installed font cannot know that. Custom encodings, symbol and barcode fonts, and any typeface missing from the rendering machine fail for the same reason. And even when the substitute has every character, its advance widths differ from the embedded face, so lines grow or shrink and right-aligned columns stop lining up

HotPDF: System-font substitution strips the subset prefix from ABCDEF+Arial and draws wrong glyphs, while embedded glyph rendering replays the FontFile outlines for exact shapes
Substitution survives only on common system faces and fails on exactly the subset fonts that made embedding necessary

Drawing text from the embedded font program

HotPDF draws text from the font programs stored in the PDF. When a font carries an embedded TrueType program (/FontFile2) or a CFF program (/FontFile3), each glyph is outlined from that data and filled as a GDI path, with font size, text matrix and current transformation matrix composed into one transform. Subset fonts, private encodings and faces the machine has never seen come out with their real shapes. How a character code reaches a glyph depends on the font type, and each type has its own trap:

  • TrueType outlines: contours come from the glyf and loca tables. Quadratic segments are raised to the cubic Béziers GDI draws, which is an exact conversion, the implied on-curve point between two consecutive off-curve points is reconstructed, and composite glyphs recurse into their components with each component transform applied
  • CID-keyed TrueType: Type0 fonts over CIDFontType2 reach glyph IDs through /CIDToGIDMap, either Identity (also the default when the entry is missing) or an explicit map stream, and take advances from /W and /DW, so two-byte Identity-H text steps by the right amount. Predefined CJK CMaps and embedded CMap streams decode variable-length codes before the lookup
  • CFF programs: Type1C, CIDFontType0C and CFF wrapped in an OpenType container run through a Type 2 charstring interpreter that handles lines, curves, the flex family, hint masks, and local and global subroutine calls with the subroutine bias applied. CID-keyed programs map each code through the font's charset, which matters for subsets whose glyph order differs from CID order, and select the per-glyph private dictionary through FDArray and FDSelect
  • Simple TrueType fonts: one-byte codes go through the embedded cmap, trying the Unicode subtables (3,1) and (3,10) first, then the (3,0) symbol subtable both directly and at the U+F000 mirror symbol fonts use, then the old Macintosh (1,0) table

Two rules sit on top of that. A simple font's /Encoding dictionary is resolved in the order ISO 32000-1 §9.6.6 prescribes: /Differences override the base encoding, which overrides the program's built-in mapping. TeX and other PostScript-derived toolchains lean on this heavily, so getting the order wrong scrambles exactly the math and symbol text where a wrong glyph is hardest to spot. Type3 fonts, whose glyphs are small content streams of their own, are replayed through the same interpreter with the font matrix, font size and text matrix composed; glyph-space /Widths go through /FontMatrix as §9.6.5 requires, and a glyph procedure that declares a d1 bounding box is clipped to it, so a malformed barcode glyph cannot paint outside its cell

When a single code cannot be mapped, because the program is damaged or the subset lacks that glyph, that one character is drawn with the installed font of the same name and the rest of the run still uses the embedded outlines. Dropping the whole run would hide the problem; one odd letter is easier to notice. Fonts with no usable embedded program follow the installed-font route described in rendering non-embedded fonts with system faces

How do you keep repeated renders fast?

For anything interactive, call RenderLoadedPageToBitmapCached instead of the plain method. It keeps recently rendered pages in a most-recently-used cache keyed by page index, DPI and the current render settings (color intent, overprint preview, fallback policy and which optional content layers are visible), and a hit hands back a fresh caller-owned copy without interpreting the content stream again. Flipping between two pages, or a resize that re-requests the same page at the same DPI, hits the cache every time. For a one-shot export that visits each page once, the plain RenderLoadedPageToBitmap is the better call, since the cached variant copies every bitmap it returns and would keep pages around that nobody will ask for again

HotPDF: MRU rendered-page cache flow: a hit returns a fresh TBitmap copy without re-interpreting the page, a miss renders and stores up to RenderCacheCapacity pages
A cache hit skips the content stream entirely, while invalidation and memory budgeting keep repeated renders correct and safe
// Thumbnail strip: the first pass renders, scrolling back hits the cache
Pdf.RenderCacheCapacity := 32;   // entry limit; default is 8
for I := 0 to Pdf.LoadedPageCount - 1 do
begin
  Bmp := Pdf.RenderLoadedPageToBitmapCached(I, 48);
  if Bmp <> nil then
  try
    ThumbList.AddThumbnail(I, Bmp);  // your own UI code
  finally
    Bmp.Free;
  end;
end;

// Caching 300 DPI pages too? Give the raster cache a bigger byte budget
// (Policy: THPDFCacheAdmissionPolicy)
if Pdf.GetCacheAdmissionPolicy(clkRaster, Policy) then
begin
  Policy.MaxTotalBytes := Int64(512) * 1024 * 1024;
  Pdf.SetCacheAdmissionPolicy(clkRaster, Policy);
end;

// After changing page content directly:
Pdf.InvalidateRenderedPageCache;  // the next render reflects the edit

RenderCacheCapacity is only one of two limits. The raster cache also has a byte budget, 128 MiB by default, with a 64 MiB ceiling per entry, and it counts four bytes per pixel when budgeting. Suppose a viewer caches Letter pages at 300 DPI: each entry is counted as about 32 MiB, so only three fit, whatever RenderCacheCapacity says. At 48 DPI the same page is counted as about 0.82 MiB, and up to 32 thumbnails from the loop above stay resident in under 27 MiB. When the cache is full, a page requested once may not displace a page requested often; it is still rendered and returned, just not kept. If a viewer turns pages in a predictable order, PrefetchLoadedPages fills the same cache on a worker thread ahead of the user

Loading a new document clears the cache. Several of the library's own page-editing calls, such as FlattenLoadedFormFields, drop the affected pages by themselves; after any change you make to page objects or content streams directly, call InvalidateRenderedPageCache, because the cache cannot tell that the bytes behind a page changed. Underneath sits a second store for decoded image XObjects, bounded by ImageCacheMaxBytes (32 MiB by default), so a logo or letterhead repeated on every page decodes once per document load instead of once per Do operator. InvalidateRenderedPageCache clears that one too. If thumbnails should survive an application restart, the disk tier of the render cache covers that case

Finding out when a page was approximated

Most pages never hit a fallback, because the renderer covers far more than text and images. CalGray, CalRGB, Lab and ICC-based color spaces are converted with the rendering intent in effect, which RenderColourIntent can override, and ConfigureRenderICCWorkflow takes proof and output ICC profiles for soft-proofing. Indexed palettes, Separation and DeviceN tints and sampled Type 0 function color lookups are covered. Function-based, axial, radial and mesh shadings render both through the sh operator and through shading patterns, and transparency groups, knockout groups and alpha or luminosity soft masks composite with their blend modes, as described in blend-mode groups and luminosity masks

Real-world files still contain things that cannot be drawn exactly: a resource the page names but never defines, an image whose data fails to decode, a Form XObject that paints itself. RenderFallbackPolicy decides what happens then. The default, rfpIgnore, draws the closest approximation and moves on. rfpReport does the same but records a diagnostic for each fallback, up to RenderFallbackDiagnosticLimit entries (256 by default). rfpStrict raises an exception instead of returning an approximate bitmap. Form nesting stops at 32 levels and a form that refers to itself is skipped, so a broken or hostile file cannot recurse without bound

// rfpReport and THPDFRenderFallbackDiagnostics are declared in HPDFPageRenderer
var
  Diags: THPDFRenderFallbackDiagnostics;
  J: Integer;
begin
  Pdf.RenderFallbackPolicy := rfpReport;
  Bmp := Pdf.RenderLoadedPageToBitmap(PageIndex, 150);
  try
    Diags := Pdf.GetLastRenderFallbackDiagnostics;
    for J := 0 to High(Diags) do
      Log.Add(Format('page %d: %s %s - %s', [PageIndex + 1,
        string(Diags[J].OperatorName), string(Diags[J].ObjectName),
        string(Diags[J].Reason)]));
    if Pdf.LastRenderFallbackDroppedCount > 0 then
      Log.Add(Format('%d more fallbacks not recorded',
        [Pdf.LastRenderFallbackDroppedCount]));
  finally
    Bmp.Free;  // Free is safe on nil
  end;
end;

Run QA and ingestion builds with rfpReport. The bitmap is identical to what rfpIgnore produces, and the log shows which pages were approximated and why, before a customer reports that page 14 looks odd. Keep rfpStrict for archival conversion, where a quietly approximated page is worse than a failed one. A cache hit restores the diagnostics recorded when that page was first rendered, so GetLastRenderFallbackDiagnostics gives the same answer whether or not the cached variant did any work

RenderLoadedPageToBitmap, the cached variant and the embedded-glyph text path are part of the HotPDF Delphi Component, a native VCL library for Delphi and C++Builder with no external DLLs, which also creates, edits and extracts text from the same loaded documents you render