Technical Article

Import SVG into PDF as Reusable Form XObjects

A hand-rolled SVG-to-PDF converter usually gets the shapes of a logo right on the first try and the tagline upside down. SVG measures Y downward from the top-left corner, PDF measures it upward from the bottom-left, and the one flip that puts the geometry in place also mirrors every glyph. Undo it locally for text, write the result once as a PDF Form XObject, and the same vector artwork can then be stamped on hundreds of pages as a single object

One import, many placements with ImportSVGFormXObject

HotPDF splits the job into two calls. THotPDF.ImportSVGFormXObject takes the SVG file as TBytes, builds a Form XObject from it and returns the resource name of that form, or an empty string when the file is refused. THPDFPage.DrawSVGFormXObject then places the form on the current page at a position and size you choose. The import happens once per document; placement can happen as often as you like, and each placement adds a transformation matrix and a Do operator to the page, nothing more

The economics are easy to work out on paper. A logo rasterized at 300 DPI and dropped on 400 pages is 400 bitmaps unless the generator deduplicates them, and every one of them is frozen at the resolution somebody picked at build time. The same logo as a Form XObject exists once in the file, prints at device resolution and still shows clean curves at 800 percent zoom

HotPDF diagram of one SVG import creating a single PDF Form XObject that DrawSVGFormXObject places on many pages at different sizes, compared with hundreds of raster bitmap copies
One import writes the artwork once as a Form XObject with its own resources, and each placement is a small invocation that adds no duplicate bytes

The statistics record type, THPDFSVGImportStatistics, is declared in the HPDFSafeSVG unit, so that unit has to appear in your uses clause next to HPDFDoc. If you only call the overload without statistics, HPDFDoc alone is enough

uses
  System.SysUtils, System.IOUtils, HPDFDoc, HPDFSafeSVG;

var
  Pdf: THotPDF;
  SvgBytes: TBytes;
  FormName: AnsiString;
  Stats: THPDFSVGImportStatistics;
  I: Integer;
begin
  Pdf := THotPDF.Create(nil);
  try
    Pdf.AutoLaunch := False;
    Pdf.FileName := 'catalog.pdf';
    Pdf.BeginDoc;

    SvgBytes := TFile.ReadAllBytes('brand-logo.svg');
    FormName := Pdf.ImportSVGFormXObject(SvgBytes, Stats);
    if FormName = '' then
      raise Exception.Create('brand-logo.svg was refused by the SVG import profile');

    // X and Y are the top-left corner in page units, measured from the top;
    // 120 x 40 keeps the 3:1 width/height ratio declared by the SVG itself
    for I := 1 to 40 do
    begin
      if I > 1 then
        Pdf.AddPage;
      Pdf.CurrentPage.DrawSVGFormXObject(FormName, 40, 30, 120, 40);
    end;

    Pdf.EndDoc;
  finally
    Pdf.Free;
  end;
end;

Watch the last two arguments. DrawSVGFormXObject scales the form horizontally by W divided by the form width and vertically by H divided by the form height, and the two factors are independent. Pass a box with a different aspect ratio from the SVG and the logo stretches. The form's bounding box comes from the root element's width and height (or the viewBox when those are absent), so derive W and H from those numbers instead of from whatever space happens to be left on the page

Why does the form carry its own resources?

A Form XObject is PDF's own mechanism for reusable content (ISO 32000-1 §8.10): a self-contained content stream with a bounding box and its own resource dictionary, invoked by name. That last part is where naive implementations go wrong. A form that borrows a font or graphics-state name from whichever page was current at import time renders correctly on that page. On every other page it is placed on, the name resolves to nothing. The first page looks perfect, so the mistake survives review

ImportSVGFormXObject writes everything the artwork needs into the form's own /Resources: opacity states, embedded images, tiling patterns, transparency groups and the forms that hold text. The importer also trims that dictionary to the names the content stream actually uses, which you can verify by opening the form object in any PDF inspector and comparing its /Resources entries with the Do, gs, Tf and scn operators in its stream

Text gets one more level of nesting. Each SVG text run becomes a small form of its own, built by the same font engine HotPDF uses for its own text output, and the artwork form references those run forms by name. Generic CSS families are mapped to system substitutes: serif to Times New Roman, sans-serif to Arial, monospace to Courier New. Helvetica and Courier are a separate case — PDF base font names rather than CSS keywords, resolved the way viewers substitute base fonts: Helvetica to Arial, Courier to Courier New. Only the first family in a font-family list is used, so a stack like "Brand Sans", Arial, sans-serif resolves to Brand Sans or to whatever the font engine falls back to for it

Transparency has a version cost. Opacity below 1, masks and images with an alpha channel require PDF 1.4, and the import raises the document version to 1.4 on its own unless StrictVersionLock is set, in which case the import fails instead. A document in strict PDF/A-1 mode refuses transparent artwork outright, because PDF/A-1 forbids transparency

Two flips, one for geometry and one for glyphs

The root viewBox transform performs the single Y-axis flip that maps SVG user space onto PDF form space, including the preserveAspectRatio centering when the viewport and the viewBox disagree. Text then takes a second, local flip at each run's baseline. Without it, every glyph is drawn in the already-flipped frame and arrives upside down

HotPDF diagram of the two Y-axis flips between SVG and PDF coordinates: the root viewBox transform corrects the geometry and text glyphs need a second local flip to stay upright
The root viewBox transform flips the Y axis once so geometry lands in PDF space, and text takes a second, local flip or every glyph arrives upside down

The same correction appears in reverse when a PDF page is written out as SVG, described in exporting PDF pages to SVG. A logo without text hides a wrong flip almost completely, since many marks are roughly symmetric. A logo with a tagline exposes it at a glance. Keep one of those in your test inputs

Text runs have a few hard rules. A run must sit on one baseline; if the font engine would have to wrap it, the import fails. Text filled with a gradient fails too, because painting a gradient through glyphs needs outlines or a text clip, and the importer does neither. A document can carry up to 128 text runs, and characters the primary font lacks may come from fallback fonts, which the importer realigns to the same alphabetic baseline SVG asks for

What the importer refuses, and why failing is the point

SVG is an XML dialect with scripting, external references and entity expansion, which makes an arbitrary SVG upload a hostile input in the same way an arbitrary HTML file is. ImportSVGFormXObject is fail-closed: when it meets a construct that could reach outside the document, or an element it does not know how to draw, it rejects the whole file and returns an empty name. It does not strip the offending part and carry on

  • Any <! construct other than comments and CDATA sections, which covers DOCTYPE declarations and entity definitions; processing instructions other than a leading <?xml declaration
  • <script>, <foreignObject>, any attribute starting with on, javascript: anywhere, and CSS @import
  • Every url() that is not a local #fragment, and every <use> that points outside the document
  • Link targets other than http:, https: and mailto:; <image> sources other than base64 data: URIs carrying PNG or JPEG
  • Element types the importer does not draw, such as a stray <filter> placed outside <defs>

Size limits are part of the same profile. The input may be at most 8 MiB, gzip-compressed .svgz data is accepted and may expand to at most 32 MiB, the document may hold up to 4096 elements nested at most 64 deep, and the generated content may not exceed 16 MiB. Embedded images are capped at 128 per file and 16,777,216 pixels in total

HotPDF diagram of a fail-closed SVG import profile that accepts local vector features and refuses scripts, external references and DTDs by failing the import instead of dropping them silently
The import profile refuses scripts, external references and DTDs by failing outright, which gives you a file to quarantine instead of a document that is quietly incomplete

For a batch pipeline, the refusal is the outcome that costs less. A sanitizer that drops what it dislikes produces a catalog page with a missing badge that nobody notices until a customer does; a refusal produces one file you can quarantine and look at. If you accept SVG from users, pair this profile with the process-level containment described in codec process isolation for untrusted images. OpenType fonts with SVG color glyphs go through the same parser and the same refusal rules, so a font's SVG table gets no more latitude than an uploaded file

Why are the import statistics all zero after a failure?

Because the record is only filled when the import succeeds. ImportSVGFormXObject clears Statistics on entry and copies the counters into it as its last step, after the form has been registered. A failed import also rolls back everything it created along the way: the partial form, image and pattern objects are discarded and the document version is restored, so the PDF you are writing is the same as before the call

The practical consequence is that there is no reason code to log. An error message that says "see the import statistics" sounds helpful and points at a record full of zeros. Log the file name and keep the original bytes instead

function ImportOrQuarantine(Pdf: THotPDF; const Path: string;
  out FormName: AnsiString): Boolean;
var
  Stats: THPDFSVGImportStatistics;
begin
  FormName := Pdf.ImportSVGFormXObject(TFile.ReadAllBytes(Path), Stats);
  Result := FormName <> '';
  if not Result then
  begin
    // Stats is all zeros here; QuarantineFile is your own routine,
    // not part of the library
    QuarantineFile(Path);
    Exit;
  end;
  Writeln(Format('%s: nodes=%d text runs=%d images=%d form bytes=%d',
    [ExtractFileName(Path), Stats.NodeCount, Stats.TextRunCount,
     Stats.ImageCount, Stats.OutputBytes]));
end;

Diagnosing a refused file is manual. Open it in a text editor and look first for a DOCTYPE line, a remote href on an <image>, or an element outside the list in the next section. A DOCTYPE that declares no entities contributes nothing to the drawing, so deleting that line from a trusted file changes no pixel and removes that particular reason for refusal

Gradients, masks and links at placement time

The importer draws path, rect, circle, ellipse, line, polyline, polygon, text, tspan, image, a and local use, inside svg, g, switch and symbol containers. Gradient fills become 32 color bands clipped by the shape's own outline: strips for linear gradients, concentric ellipses for radial ones. Gradient strokes are painted through a tiling pattern. Masks become PDF soft masks, luminance by default or alpha when mask-type="alpha" says so, and group opacity becomes an isolated transparency group, so overlapping children inside a half-transparent group do not show through each other

Banding is the deliberate trade here. Thirty-two bands across a small badge are invisible at normal viewing size; across a full-page background they can show as steps. Large smooth backgrounds are better drawn with PDF's native shadings, covered in rendering axial and radial shadings, and artwork stacked with many overlapping soft effects can look closer to the original as a high-resolution image

Links cannot live inside the form at all. A Form XObject is content, while PDF links are annotations attached to a page (ISO 32000-1 §12.5), so an <a> element cannot be copied into a content stream. The importer records each link's rectangle in form space, and DrawSVGFormXObject turns those rectangles into page-level URI link annotations at every placement, scaled through the W and H you pass. The rectangles are rounded to whole page units, and the link description comes from aria-label when the SVG has one, otherwise from the URL. Pass AddLinks = False for a print-only placement

// Counters are meaningful only after a successful import
Writeln(Format('nodes=%d css rules=%d gradients=%d masks=%d groups=%d',
  [Stats.NodeCount, Stats.CSSRuleCount, Stats.GradientCount,
   Stats.MaskCount, Stats.GroupCount]));
Writeln(Format('text runs=%d links=%d images=%d form bytes=%d',
  [Stats.TextRunCount, Stats.LinkCount, Stats.ImageCount,
   Stats.OutputBytes]));

// The same form at two sizes produces two correctly scaled link sets
Pdf.CurrentPage.DrawSVGFormXObject(FormName, 40, 100, 240, 80);
Pdf.CurrentPage.DrawSVGFormXObject(FormName, 320, 100, 120, 40);

// Print-only placement: artwork without the hit areas
Pdf.CurrentPage.DrawSVGFormXObject(FormName, 40, 700, 120, 40, False);

Where SVG import fits next to the other vector routes

SVG import suits artwork exported from design tools and anything that arrives through a web pipeline. Metafile import, covered in EMF and WMF vector import, suits output from Windows applications and charting components that draw to a device context. Direct drawing through the page API suits geometry your own code computes, where an intermediate format would only add a parsing step

The reuse argument favors SVG import for elements that repeat: letterheads, logos, watermarks, certification marks, decorative rules. For a 500-page catalog with one vector logo per page, the comparison is one form plus 500 short invocations against 500 inline copies of the same path data, and the gap grows with every curve in the logo. Run both variants against your own artwork before deciding the difference is negligible

ImportSVGFormXObject and DrawSVGFormXObject are available to Delphi and C++Builder projects alike; the rest of the drawing, import and compliance API is listed on the HotPDF Delphi PDF component page