Technical Article

Print a Loaded PDF in Delphi with HotPDF and TPrinter

A US Letter page measures 612 by 792 points. Render it into a printer device context at 300 DPI and it covers 2550 by 3300 device pixels, which fills the sheet on a 300 DPI printer and shrinks to 4.25 by 5.5 inches on a 600 DPI laser, a quarter-size page tucked into the top-left corner. Typing a bigger number into the DPI field fixes one printer and breaks the next. A print path that works on every desk has to agree with the printer on three things at once: its resolution, the strip near the paper edge it cannot reach, and which way up the paper goes

Printing a loaded PDF with PrintLoadedDocument and TPrinter

HotPDF prints a loaded document with THotPDF.PrintLoadedDocument(Printer, Options): you pass an assigned VCL TPrinter and a THPDFPrintOptions record, and the function returns the number of pages it sent to the driver. Inside, it opens the job with Printer.BeginDoc, emits Printer.NewPage between pages and closes with Printer.EndDoc. If rendering raises an exception halfway through, it calls Printer.Abort so the spooler discards the partial job, then re-raises so your code still sees the error

uses Printers, HPDFDoc;

var
  Pdf: THotPDF;
  Opts: THPDFPrintOptions;
  PagesSent: Integer;
begin
  Pdf := THotPDF.Create(nil);
  try
    if Pdf.LoadFromFile('invoice.pdf') > 0 then
    begin
      Printer.PrinterIndex := -1;          // -1 selects the default printer
      Opts := THPDFPrintOptions.Default;   // all pages, 300 DPI, FitPage, AutoRotate
      Opts.PageRange := '1,3-5';           // one-based; empty prints every page
      Opts.Copies := 2;
      Opts.Collate := True;
      PagesSent := Pdf.PrintLoadedDocument(Printer, Opts);  // 8 = four pages x two copies
    end;
  finally
    Pdf.Free;
  end;
end;

The PageRange string reads the way a print dialog does: '1,3-5' selects page 1 and pages 3 through 5. The return value counts every page that went to the driver, copies included, so the call above returns 8. THPDFPrintOptions.Default gives an empty range, 300 DPI, one copy, Collate False, FitPage True, AutoRotate True, IgnoreHardMargin False, and zero in Duplex, PaperBin, PrintQuality, PaperSize, PaperWidth and PaperLength, where zero means the driver keeps its own setting

Each page reaches the printer as drawing commands. PrintLoadedDocument renders through RenderLoadedPageToDC, which walks the page's content stream and issues the matching GDI calls straight onto Printer.Canvas.Handle, so text and line art are rasterized once, by the printer, at the printer's own resolution. A bitmap-first approach has to choose its resolution before the job starts. Stretch a 300 DPI raster onto a 1200 DPI drum and every glyph edge goes soft, and diagonal rules turn into staircases that no driver setting can recover

Diagram comparing two Delphi PDF print paths: rasterizing a HotPDF page to a soft bitmap versus replaying vector GDI calls into the printer device context for one clean rasterization
RenderLoadedPageToDC replays the content stream as GDI calls so the printer rasterizes text and line art once at its native resolution

Why does the printed page come out too small?

Almost always because FitPage was switched off and Options.DPI does not match the printer. With FitPage True, PrintLoadedDocument reads each page's visible box (the CropBox clipped to the MediaBox, as ISO 32000-1 §14.11.2 defines the page boundaries) and computes the scale that fits it inside Printer.PageWidth by Printer.PageHeight with the aspect ratio locked. Options.DPI plays no part in that mode, because the rendering resolution falls out of the fit. With FitPage False the page renders one-to-one at Options.DPI: 72 PDF units become DPI device pixels, and the printer decides how large a device pixel is on paper

Leave FitPage on for documents that arrive from elsewhere, where A4 files land on Letter trays and the reverse happens just as often. One-to-one mode pays off when the physical size has to be exact, such as a scale drawing or a form that a scanner reads back. In that case, ask the printer for its resolution instead of hard-coding one

uses Windows, Printers, HPDFDoc;

Opts := THPDFPrintOptions.Default;
Opts.FitPage := False;
Opts.DPI := GetDeviceCaps(Printer.Handle, LOGPIXELSX);  // the printer's real horizontal DPI
// If you also set Opts.PrintQuality, give DPI the same value: the DEVMODE
// change is applied inside PrintLoadedDocument, after this query has run
Pdf.PrintLoadedDocument(Printer, Opts);

The second size problem is the hard margin. Every laser and inkjet has a border it cannot reach, and a printer device context puts its origin at the corner of the printable area. By default the whole page therefore shifts right and down by that border, a few millimeters that nobody notices on a letter and everybody notices on a label sheet. With IgnoreHardMargin True, PrintLoadedDocument reads PHYSICALOFFSETX and PHYSICALOFFSETY from the printer DC and moves the viewport origin back by that amount for each page, so PDF coordinates line up with the physical corner of the sheet. Whatever falls inside the dead strip still does not print, since the hardware cannot put toner there. Keep the option off for ordinary documents and turn it on for labels and preprinted stationery, where position relative to the paper edge matters more than the sliver lost at the border

AutoRotate, on by default, compares each page's visible box width with its height just before rendering it and sets Printer.Orientation to landscape for wide pages and portrait for tall ones. A report that mixes portrait text pages with a landscape spreadsheet page prints the wide page without clipping. Set Orientation to 1 (portrait) or 2 (landscape) and the per-page check stops; your choice then applies to every page in the job

Diagram of HotPDF print scaling in Delphi: each page's visible box read, an AutoRotate orientation check, FitPage versus fixed DPI scaling, and IgnoreHardMargin canceling the printer hardware offset
FitPage fills the sheet while fixed DPI keeps one-to-one scaling, and IgnoreHardMargin shifts the origin past the unprintable hardware border

Copies, collation and driver settings

PrintLoadedDocument handles collation itself. It sets Printer.Copies to 1 for the duration of the job, builds the full page sequence for every copy, and restores your original Printer.Copies value afterwards. With Collate True, the '1,3-5' range and two copies come out as 1, 3, 4, 5, 1, 3, 4, 5. With Collate False they come out as 1, 1, 3, 3, 4, 4, 5, 5. The price is spool size, because the driver receives every copy as real pages instead of one set plus a copy count. That trade is worth making: collation support in VCL has shifted between Delphi versions, drivers treat the copy count in their own ways, and a stapled stack in the wrong order costs far more than a larger spool file

Duplex, paper tray, print quality and paper size are written into the printer's DEVMODE before the job starts. Duplex takes 1 for simplex, 2 for long-edge and 3 for short-edge binding. PaperBin takes a DMBIN_* constant or a driver bin code, PrintQuality a positive DPI, and PaperSize a DMPAPER_* code. A custom sheet goes in PaperWidth and PaperLength, both in tenths of a millimeter, and both must be set together. Supplying only one raises an exception before Printer.BeginDoc runs, and so does a dimension above the DEVMODE ceiling of 32767, so a half-configured job never reaches the spooler

Tray codes are the awkward part, because every driver numbers its trays differently. HPDFGetPrinterCapabilities queries the driver through DeviceCapabilities and returns its bins, paper sizes, resolutions, maximum copy count, and duplex and color support. BinNames is index-parallel to BinCodes, and HPDFGetInstalledPrinters fills a TStrings whose indexes match Printer.PrinterIndex

var
  Caps: THPDFPrinterCapabilities;
  I: Integer;
begin
  Opts := THPDFPrintOptions.Default;
  // An empty name queries the printer currently selected in Printer.PrinterIndex
  if HPDFGetPrinterCapabilities('', Caps) then
  begin
    if Caps.SupportsDuplex then
      Opts.Duplex := 2;                      // long-edge binding
    // Bin names are driver text; matching on a word is a heuristic you
    // would tune for the printers your users actually own
    for I := 0 to High(Caps.BinNames) do
      if Pos('Manual', Caps.BinNames[I]) > 0 then
        Opts.PaperBin := Caps.BinCodes[I];
  end;
  Pdf.PrintLoadedDocument(Printer, Opts);
end;

Color versus grayscale output follows the driver setting, so let the user pick it in TPrinterSetupDialog before printing; the DEVMODE fields PrintLoadedDocument writes are duplex, tray, quality and paper size, and orientation goes through TPrinter. In a Lazarus build the DEVMODE step is skipped (the custom paper check still runs), so duplex and tray selection belong in the printer dialog there

Rendering a page into any device context

RenderLoadedPageToDC(PageIndex, DC, DPI, W, H) is the renderer PrintLoadedDocument calls for each page, exposed for any Windows HDC: an off-screen bitmap, a custom preview control, a metafile canvas. PageIndex is zero-based, DPI sets the scale at DPI / 72 device pixels per PDF unit, and an out-of-range index returns without drawing anything. No background is painted. The caller owns the surface, so fill it white first, or leave it alone when you want to composite the page over something already drawn

W and H do not stretch the page. The renderer scales by DPI alone and uses H to anchor the page's bottom edge, so a surface taller than the page leaves the page sitting at the bottom with an empty band on top. Size the surface from the page's visible box, and swap width and height for pages whose /Rotate is 90 or 270, because the renderer expects the caller to have done that swap

var
  Surface: TBitmap;
  L, B, R, T: Single;
  W, H, Rot, Tmp: Integer;
const
  DPI = 150;
begin
  if not Pdf.GetLoadedPageVisibleBox(0, L, B, R, T) then Exit;
  W := Round((R - L) * DPI / 72);
  H := Round((T - B) * DPI / 72);
  Rot := Pdf.GetLoadedPageRotation(0);         // normalized to 0..359
  if (Rot = 90) or (Rot = 270) then
  begin
    Tmp := W; W := H; H := Tmp;
  end;
  Surface := TBitmap.Create;
  try
    Surface.PixelFormat := pf24bit;
    Surface.SetSize(W, H);
    Surface.Canvas.Brush.Color := clWhite;
    Surface.Canvas.FillRect(Rect(0, 0, W, H)); // the renderer paints no background
    Pdf.RenderLoadedPageToDC(0, Surface.Canvas.Handle, DPI, W, H);
    Surface.SaveToFile('page1.bmp');
  finally
    Surface.Free;
  end;
end;

If all you want is a finished TBitmap for a thumbnail, an image export or a cached preview, RenderLoadedPageToBitmap allocates and sizes it for you, as the article on rendering PDF pages to a bitmap shows. RenderLoadedPageToDC is for surfaces somebody else already created: the printer canvas, the DC an OnPaint handler receives, a print-preview page. Both run the same content-stream interpreter, so embedded fonts come out with identical outlines either way

Copying a page to the clipboard as a metafile or a bitmap

RenderLoadedPageToClipboard(PageIndex, DPI, AsMetafile) places one page on the Windows clipboard. With AsMetafile True it builds the page through GetLoadedPageMetafile and assigns an enhanced metafile (CF_ENHMETAFILE), in which text and vector art remain GDI drawing records; pasted into Word or PowerPoint and enlarged, it stays sharp. With AsMetafile False it renders a 24-bit bitmap through RenderLoadedPageToBitmap at the requested DPI and assigns that (CF_BITMAP). A DPI below 1 falls back to 150 in both modes. Pdf.RenderLoadedPageToClipboard(1, 300, True) copies the second page as a metafile

Default to the metafile for anything a person will paste into a document and resize: a figure in a report, a clause dropped into a contract draft. Choose the bitmap when the destination only takes raster data, which is true of many image editors and chat clients, or when you want a frozen snapshot at a known resolution. A page made mostly of photographs gains little from the metafile, since embedded images are raster data in both formats. When you need the words themselves rather than a picture of them, the text extraction API returns characters with their positions

Batch printing and platform scope

PrintLoadedDocument renders one page at a time, yet the loaded document stays in memory for the whole job. A queue that prints hundreds of large files should create, load, print and free one THotPDF per file. When only a handful of pages from a very large file need paper, the Direct File API for large-PDF workflows can pull those pages out on disk first, and the print step then loads only the slim result

All three calls are built on TPrinter, GDI device contexts, the Windows clipboard and enhanced metafiles, which makes printing and clipboard export Win32 and Win64 features; on other targets the rest of the library creates, edits and reads PDF as usual. The printed output matches what the bitmap renderer draws on screen. Contract proofs of gradient-heavy or ICC-managed artwork, where color has to be measured against a standard, belong in a color-managed proofing workflow

Printing, device-context rendering and clipboard export ship in the HotPDF Delphi Component, a native VCL library for Delphi and C++Builder with no external DLLs, alongside PDF creation, editing, text extraction and rendering