Table of Contents

PDF Library

TMS FNC Core includes TTMSFNCPDFLib, a cross-platform PDF generation library that creates documents, pages, and page content including HTML-formatted text, plain text, drawing primitives, images, form fields, and more. The code is shareable between VCL, FMX, and WEB Core.

Add the appropriate unit to your uses clause:

uses
  FMX.TMSFNCPDFLib;   // FMX
  VCL.TMSFNCPDFLib;   // VCL
  WEBLib.TMSFNCPDFLib; // WEB Core

Key class: TTMSFNCPDFLib

Starting a New Document

Call BeginDocument to start a document, always paired with EndDocument. When AFileName is empty, EndDocument returns the content as a TMemoryStream. Pass True as the second parameter to EndDocument to open the generated file in the default PDF viewer.

procedure TForm1.GeneratePDF(AFileName: string);
var
  p: TTMSFNCPDFLib;
begin
  p := TTMSFNCPDFLib.Create;
  try
    p.BeginDocument(AFileName);
    p.NewPage;
    p.EndDocument;
  finally
    p.Free;
  end;
end;

Adding Pages

Call NewPage to start a new page. Each NewPage call clears the content buffer but preserves appearance settings (fill, stroke, font) from the previous page. EndDocument raises an error if no page was added.

Use InsertPage(APageIndex) to insert at a specific position, GetPageCount to get the total page count, and GetPageIndex to get the zero-based index of the current page.

Drawing Content

After calling NewPage, use p.Graphics to draw on the page.

Lines, Rectangles, and Paths

p.Graphics.Stroke.Color := gcRed;
p.Graphics.Stroke.Width := 3;
p.Graphics.Stroke.Kind := gskDashDotDot;
p.Graphics.DrawLine(PointF(10, 50), PointF(100, 50));

Drawing content on a page

Rectangles support fill with optional gradients:

p.Graphics.Fill.Kind := gfkGradient;
p.Graphics.Fill.Color := gcBlue;
p.Graphics.Fill.ColorTo := gcOrange;
p.Graphics.DrawRectangle(RectF(10, 50, 100, 150));

Drawing content on a page

Custom Paths

Build paths with DrawPathBegin / DrawPathMoveToPoint / DrawPathAddLineToPoint / DrawPathClose / DrawPathEnd:

p.Graphics.DrawPathBegin;
p.Graphics.DrawPathMoveToPoint(PointF(x, y));
for I := 1 to 5 do
begin
  x := rad * sin((i * 4 * pi + angle) / 5) + st.X;
  y := rad * cos((i * 4 * pi + angle) / 5) + st.Y;
  p.Graphics.DrawPathAddLineToPoint(PointF(x, y));
end;
p.Graphics.DrawPathClose;
p.Graphics.DrawPathEnd;

Drawing content on a page

Path Drawing Modes

Value Description
dmPathFill Fill using the non-zero winding rule
dmPathEOFill Fill using the even-odd rule
dmPathStroke Stroke the outline only
dmPathFillStroke Fill and stroke (default)
dmPathEOFillStroke Fill (even-odd) and stroke

Clipping Paths

Use DrawPathBeginClip / DrawPathEndClip to define a clipping mask. Call DrawRestoreState to release it.

Linear Gradient Paths

Replace DrawPathEnd with DrawPathEndLinearGradient(StartPoint, EndPoint) to fill a path with a linear gradient.

Transforms

Apply a transformation matrix with DrawSetTransform. Use DrawSaveState / DrawRestoreState to scope the effect.

Clearing a Region

DrawClear(Rect) erases the content inside a rectangle by painting it with the background color.

Drawing Text

Use DrawText to draw plain or wordwrapped text. Control font appearance via p.Graphics.Font:

p.Graphics.Font.Name := 'Segoe UI';
p.Graphics.Font.Size := 16;
p.Graphics.Font.Color := gcRed;
p.Graphics.Font.Style := [TFontStyle.fsBold];
p.Graphics.DrawText('Hello World !', PointF(10, 50));

Drawing text

Pass a TRectF instead of TPointF to enable word wrapping. Pass an integer column count as a third argument to flow text across multiple columns:

p.Graphics.DrawText(s, RectF(10, 50, 500, 400), 3);

Drawing text

DrawText returns either the calculated text rectangle or the character overflow count. Use CalculateTextOverflow(Text, Rect, Columns) to calculate overflow without drawing.

HTML Text

DrawHTMLText renders Mini HTML-formatted text in a rectangle. HTML supports <b>, <i>, <u>, <s>, <sup>, <sub>, <br>, <font>, <a href>, and <img src>:

p.Graphics.DrawHTMLText(s, RectF(10, 50, 300, 400));

Drawing text

Text Alignment

Set p.Graphics.Alignment to gtaLeading (default), gtaCenter, or gtaTrailing.

Note

For multiline HTML text, use a <p> tag for alignment rather than Graphics.Alignment.

Line Break Mode

Value Description
bmLineBreakModeWordWrap Wrap at word boundaries (default)
bmLineBreakModeCharacterWrap Wrap at any character
bmLineBreakModeClip Clip at the boundary
bmLineBreakModeHeadTruncation Truncate at the start
bmLineBreakModeMiddleTruncation Truncate in the middle
bmLineBreakModeTailTruncation Truncate at the end

Full support on macOS/iOS; limited on other platforms.

Line Height and URL Font

  • Graphics.LineHeightFactor — scales vertical line spacing. Call LineHeightFactorResetToDefault to restore the default.
  • Graphics.URLFont — controls the appearance of <a href> links in HTML text.

Font Embedding

By default, a font subset is embedded in the PDF for portability. Set EmbedFonts := False to disable embedding (smaller files, faster generation) for print-only workflows.

EmbedFontType controls the embedding strategy:

Value Description
eftNative Platform native embedding (default)
eftCustom TMS cross-platform embedding

On Android, set Graphics.Font.FileName to a TTF file path to use a font not registered in the system directory.

Images

Draw images with DrawImage, DrawImageFromFile, or DrawImageWithName (requires a BitmapContainer):

p.BitmapContainer := TMSFNCBitmapContainer1;
p.Graphics.DrawImageWithName('MyImage', PointF(10, 50));
p.Graphics.DrawImageFromFile('MyImage.jpg', PointF(160, 50));
MyImage.LoadFromFile('MyImage.jpg');
p.Graphics.DrawImage(MyImage, PointF(310, 50));

Images

Graphics Engine

TTMSFNCGraphicsPDFEngine exposes the same drawing API as a regular FNC canvas, eliminating the need to build raw PDF paths manually. Add FMX.TMSFNCGraphicsPDFEngine to the uses clause:

uses
  FMX.TMSFNCPDFLib, FMX.TMSFNCGraphicsTypes, FMX.TMSFNCGraphicsPDFEngine;

var
  p: TTMSFNCPDFLib;
  g: TTMSFNCGraphicsPDFEngine;
  pth: TTMSFNCGraphicsPath;
begin
  p := TTMSFNCPDFLib.Create;
  g := TTMSFNCGraphicsPDFEngine.Create(p);
  pth := TTMSFNCGraphicsPath.Create;
  try
    p.BeginDocument('output.pdf');
    p.NewPage;
    pth.MoveTo(PointF(200, 200));
    pth.AddLine(PointF(200, 200), PointF(300, 300));
    pth.ClosePath;
    g.DrawPath(pth);
    g.DrawText(RectF(100, 200, 300, 400), 'Hello!', False, gtaCenter, gtaCenter, gttNone, -45);
    p.EndDocument(True);
  finally
    pth.Free;
    g.Free;
    p.Free;
  end;
end;

Graphics engine

Form Fields

Note

Form fields are supported on Windows and Linux only.

Add form fields via p.FormFields:

Type Method
Text edit AddEdit
Multiline text edit AddMemo
Password edit AddPasswordEdit
Check box AddCheckBox
Radio group AddRadioGroup
Radio button AddRadioButton
Combo box AddComboBox
List box AddListBox

Each field requires a unique name. All fields except radio groups also require a TRectF position.

p.FormFields.AddEdit('Textfield1', RectF(10, 10, 210, 32), 'Default text', gtaLeading);
p.FormFields.AddCheckBox('Checkbox1', RectF(10, 50, 30, 70), False);
p.FormFields.AddComboBox('Combobox1', RectF(10, 90, 70, 110), ['item1', 'item2', 'item3'], 1);

FormFields.Font sets the default font for all fields. Individual fields can override it. Set FontAutoSize := True to auto-scale font to field bounds. Set IgnoreFonts := True to suppress font embedding for form fields.

Document and Page Settings

Metadata

Set Author, Creator, Title, Subject, and Keywords directly on the TTMSFNCPDFLib instance.

Page Size and Orientation

Property Description
PageSize Standard size (A4, Letter, Legal, etc.) or psCustom
PageOrientation poPortrait or poLandscape
PageWidth / PageHeight Custom size when PageSize = psCustom

Supported sizes include ISO A0–A8, B0–B10, C2–C6, SRA and RA series, US Letter, Legal, Ledger, Tabloid, Executive, ANSI C–E, and traditional British sizes.

Property Description
Header / Footer Content text (supports HTML)
HeaderSize / FooterSize Height of the area
HeaderMargins / FooterMargins Margins around the area
HeaderAlignment / FooterAlignment Horizontal text alignment
HeaderFont / FooterFont Font for the text

Use GetHeaderRect and GetFooterRect to retrieve the bounding rectangles.

Page Numbering

Property Description
PageNumber pnNone (default), pnHeader, or pnFooter
PageNumberFormat Format string
PageNumberSize / PageNumberMargins / PageNumberAlignment / PageNumberFont Layout and appearance

Use GetPageNumberRect to retrieve the page number bounding rectangle.

PDF Standard

Set PDFStandard to pdfNone (default) or pdfA1 for PDF/A-1 archival format.

Security

Set OwnerPassword and UserPassword to protect the document. AllowsPrinting and AllowsCopying (both True by default) control permitted operations.

PDF Page Boxes

Property Description
MediaBox Physical page size
CropBox Region displayed or printed
BleedBox Bleed area
TrimBox Final trimmed dimensions
ArtBox Extent of meaningful content

Events

Event Description
OnBeforeDrawHeader / OnAfterDrawHeader Before/after header is drawn. Set ADefaultDraw := False to suppress default rendering.
OnBeforeDrawFooter / OnAfterDrawFooter Before/after footer is drawn.
OnBeforeDrawPageNumber / OnAfterDrawPageNumber Before/after page number is drawn.
OnNewPageStarted Fires after each NewPage call; provides APageIndex.
procedure TForm1.PDFBeforeDrawHeader(Sender: TObject; APageIndex: Integer;
  AHeader: UnicodeString; ARect: TRectF;
  AGraphics: ITMSFNCCustomPDFGraphicsLib; var ADefaultDraw: Boolean);
begin
  ADefaultDraw := False;
  AGraphics.Font.Size := 9;
  AGraphics.DrawText('Page ' + IntToStr(APageIndex + 1), ARect.TopLeft);
end;

Coordinate Conversion

All functions accept an optional ADPI parameter (default 72.0):

Function Description
InchToPixel(AInch, ADPI) Inches → PDF points
MillimeterToPixel(AMillimeter, ADPI) Millimeters → PDF points
MillimeterRect(AX, AY, AWidth, AHeight, ADPI) Create TRectF from mm coordinates
InchRect(AX, AY, AWidth, AHeight, ADPI) Create TRectF from inch coordinates
p.Graphics.DrawRectangle(MillimeterRect(10, 10, 100, 150));

WEB Core

Font Caching

Pre-load fonts before generating PDF in WEB Core:

AddFontToCache('http://www.myserver.com/fonts/arial.ttf');
AddFontToCache('http://www.myserver.com/fonts/tahoma.ttf');

Handle Application.OnFontCacheReady to ensure fonts are loaded before export.

Compression

WEB Core requires the Pako ZLib library for PDF compression. Enable it via Manage JavaScript Libraries → Pako ZLib Compression (PDF) in the project context menu.

WEB support

See Also