A point at (96, 96) on an XPS FixedPage sits exactly one inch from the top-left corner of the sheet. Copy those two numbers into a PDF content stream and the same point lands about 1.33 inches from the bottom-left corner, because PDF counts 72 units to the inch and measures upward from the bottom edge. Anyone writing an XPS-to-PDF converter fixes that on day one with a multiply and a subtraction, and the first flat page comes out right. The trouble starts on the page that carries a rotated RenderTransform, a nested Canvas or a tiled brush
The usual reason a Windows shop ends up here is a print path nobody wants to touch: a legacy ERP report already prints to the Microsoft XPS Document Writer, and the retention policy says PDF. So the spool file has to become a page-for-page PDF, and the XML turns out to be the easy part. XPS and PDF disagree about where the origin is, what a unit is worth and what a brush is allowed to contain
Opening an XPS or OpenXPS package in Delphi
HotPDF has no dedicated XPS class. The entry point is THPDFDocumentHandlerRegistry in the HPDFDocumentHandlers unit: RegisterStandardHandlers installs three handlers (XPS, EPUB and CBZ), each one scores the input, and the highest score wins. The scores look at content first. A ZIP that contains [Content_Types].xml and at least one .fpage part scores 95 for XPS, an archive with META-INF/container.xml scores 98 for EPUB, and a bare .xps, .oxps or .epub extension, or the matching MIME type, earns only 10. An EPUB renamed to statement.xps therefore still goes to the EPUB handler, which matters as soon as you accept uploads from people you do not control
uses
System.Classes, System.SysUtils, HPDFDocumentHandlers;
procedure ConvertSpoolFile(const XPSName, PDFName: string);
var
Registry: THPDFDocumentHandlerRegistry;
Options: THPDFDocumentHandlerOptions;
Handled: IHPDFHandledDocument;
OpenInfo, WriteInfo: THPDFDocumentHandlerInfo;
Output: TFileStream;
begin
Registry := THPDFDocumentHandlerRegistry.Create;
try
Registry.RegisterStandardHandlers;
Options := THPDFDocumentHandlerOptions.Default;
// Parsing and PDF generation both happen here; failures come back in OpenInfo
if not Registry.OpenFromFile(XPSName, '', Options, Handled, OpenInfo) then
raise Exception.CreateFmt('%s: %s', [XPSName, OpenInfo.Diagnostic]);
if Handled.Format <> hdfXPS then
raise Exception.CreateFmt('%s was recognized by %s',
[XPSName, Handled.HandlerName]);
Output := TFileStream.Create(PDFName, fmCreate);
try
if not Handled.WritePDF(Output, Options, WriteInfo) then
raise Exception.Create(WriteInfo.Diagnostic);
finally
Output.Free;
end;
if OpenInfo.UnsupportedFeatureCount > 0 then
Writeln(Format('%s: %d page(s), %d construct(s) not mapped',
[XPSName, OpenInfo.PageCount, OpenInfo.UnsupportedFeatureCount]));
finally
Registry.Free;
end;
end;
The real work happens inside OpenFromFile: the handler parses every fixed page, renders it and keeps the finished PDF bytes in memory, so WritePDF only copies those bytes to your stream and can be called a second time for another destination. The registry does not raise for a bad package either. It returns False, sets Info.Status to a THPDFDocumentHandlerStatus value such as dhsNoHandler or dhsUnsupportedContent, and puts the reason in Info.Diagnostic
Budgets and cancellation for server-side conversion
THPDFDocumentHandlerOptions.Default is sized for a desktop batch job: 10,000 archive entries, 1 GiB of expanded archive data, a compression ratio cap of 200, 4,096 resources, 10,000 pages, 100 million rendered pixels and a 2 GiB output ceiling. An upload endpoint should not inherit those numbers
uses
System.Classes, HPDFTypes, HPDFDocumentHandlers;
function ConvertUpload(Registry: THPDFDocumentHandlerRegistry;
Upload, Output: TStream; const UploadName: string;
Token: THPDFCancellationToken): THPDFDocumentHandlerStatus;
var
Options: THPDFDocumentHandlerOptions;
Handled: IHPDFHandledDocument;
Info: THPDFDocumentHandlerInfo;
begin
Options := THPDFDocumentHandlerOptions.Default;
Options.MaxPages := 500;
Options.MaxArchiveExpandedBytes := Int64(256) * 1024 * 1024;
Options.MaxOutputBytes := Int64(512) * 1024 * 1024;
Options.CancellationToken := Token; // another thread may call Token.Cancel
// Options.MaxPages := 0; // wrong: zero is not "unlimited", the record
// // is rejected as dhsInvalidOptions
if Registry.OpenFromStream(Upload, UploadName, '', Options, Handled, Info) then
Handled.WritePDF(Output, Options, Info);
Result := Info.Status; // dhsSucceeded, dhsBudgetExceeded, dhsCancelled, ...
end;
The page cap is checked against the package's page list before rendering begins, so a 600-page upload against MaxPages = 500 comes back as dhsBudgetExceeded without page one ever being drawn. The trap in that record is zero. Plenty of option records treat 0 as "no limit"; this one requires every cap to be positive and refuses the whole record as dhsInvalidOptions when one is not. Set a large number when you mean large. Cancellation is cooperative: the converter checks the token repeatedly while it works through pages and resources, and a cancelled job returns dhsCancelled from the open call, before a single byte has gone to your output stream
Why does an XPS page need a matrix instead of rewritten coordinates?
Because rewriting leaf coordinates throws away the transform stack. An XPS FixedPage uses 96 units per inch with Y growing downward; PDF user space uses 72 with Y growing upward. Multiply-and-subtract works only while every number lives directly in page space. A RenderTransform, a nested Canvas or a brush-local Transform is defined in XPS space, and once a converter has rewritten the path numbers into PDF space there is no correct place left to apply them
HotPDF keeps the projection as one matrix (scale by 0.75, flip Y, translate by the PDF page height), composes it with the accumulated XPS transform and writes a single cm operator ahead of each visual. Path data then goes into the content stream as the original XPS numbers. That is also why XPS abbreviated geometry can run through the same bounded parser as SVG path data, with only the leading F0 or F1 fill-rule token handled on the XPS side. The PDF page size is the FixedPage Width and Height times 0.75, and a page that omits them gets 793.33 × 1122.67 XPS units, which is A4 at roughly 595 × 842 points. The same matrix-first reasoning runs through EMF and WMF vector import
Your own code needs the same matrix when it has to find something on the converted page, such as stamping a review note at a position an XPS tool reported. The public HPDFRenderMatrix unit has the pieces
uses
HPDFRenderMatrix;
// A helper you write yourself: maps an XPS point, expressed inside its
// element's RenderTransform, to PDF points on the converted page
function XPSPointToPDF(const RenderTransform: THPDFAffineMatrix;
X, Y, FixedPageHeight: Double): THPDFPoint;
var
PageMatrix: THPDFAffineMatrix;
begin
PageMatrix := HPDFMatFromOps(0.75, 0, 0, -0.75, 0, FixedPageHeight * 0.75);
// HPDFMatMul(A, B) applies B first, then A
Result := HPDFMatApplyPoint(HPDFMatMul(PageMatrix, RenderTransform),
HPDFPointOf(X, Y));
end;
// Letter-size page (Height="1056"), no transform:
// XPSPointToPDF(HPDFMatIdentity, 96, 96, 1056) -> (72, 720)
Operand order inside HPDFMatMul is the classic slip. Swap the two arguments and the element's translation is applied in PDF points instead of XPS units, so an element that its RenderTransform moves 96 units to the right lands 96 points to the right, 24 points (a third of an inch) past where it belongs
How do you reuse a VisualBrush without drawing it twice?
A VisualBrush paints an arbitrary visual tree of Canvas, Path and Glyphs children into a region, often repeated across it. Drawing that tree once per tile would multiply the content stream by the tile count. HotPDF compiles the visual once into a PDF Form XObject and places the Form wherever the brush appears, the same resource strategy described in SVG import via Form XObjects
Three details decide whether the result is right. The visual is walked strictly as direct XML children; a flat scan for drawable elements would pull nested visuals up to page level and wreck both resource scoping and painting order. Content is captured with the page matrix already applied, so the Form is published through the inverse of that matrix, and skipping the inverse makes every placement apply the 0.75 scale and the Y flip a second time. And the Form owns its resources: only the fonts, XObjects, patterns, ExtGStates and color spaces that its content stream actually references are copied in. Cloning the page's whole resource dictionary looks harmless and is not, because the Form being registered would then sit inside its own resource graph and close a cycle
Two consequences are visible from outside. A document with no reusable visuals keeps its fonts in a plain direct dictionary, and the shared indirect font dictionary appears only when captured content really contains a Tf operator. Hyperlinks inside a VisualBrush visual are dropped, because one visual definition repeated across a page would otherwise scatter link annotations that match nothing the reader can see
ECMA-388 §13.4 requires ViewboxUnits and ViewportUnits on a VisualBrush to be Absolute. HotPDF counts a VisualBrush that lacks a Viewbox or Viewport, or that declares a relative Viewbox, as unsupported and moves on. A RelativeToBoundingBox viewport is tolerated and resolved against the bounding box of the path being filled
ImageBrush tiling: four modes, four cell sizes
XPS tile modes become native PDF tiling patterns (ISO 32000-1 §8.7.3) instead of one image drawn over and over across the covered area, so output size stays flat no matter how much of the page the brush covers. Reflection is expressed by putting mirrored placements inside one pattern cell and enlarging the cell to match
Tile: one placement, the cell stays one viewport wide and highFlipX: two placements, the cell is widened to 2 × 1FlipY: two placements, the cell is heightened to 1 × 2FlipXY: four placements, the cell grows to 2 × 2
Each placement carries its own clip rectangle, because a Viewbox mapping that overruns its sub-cell would bleed into the neighboring reflection. A pattern is anchored to the default coordinate space of the page, so the cm operators in force when it is selected do not move it. The converter therefore folds all three layers into /Matrix explicitly: the fixed-page projection, the Path's transform and the brush-local Transform
RegisterImageTilingPattern is a public THotPDF method, so the same construct is available to your own drawing code. The sketch below builds a FlipX tile from an image shown at 100 × 60 points: one normal placement, one mirrored copy, a cell twice as wide
uses
HPDFDoc, HPDFRenderMatrix;
// HPDF is a THotPDF with BeginDoc already called
procedure FillWithMirroredTile(HPDF: THotPDF);
var
ImageIndex: Integer;
Placements: THPDFImageTilingPlacements;
Pattern: AnsiString;
begin
ImageIndex := HPDF.AddImage('tile.jpg', icJpeg);
SetLength(Placements, 2);
// Placement 0: the image unit square scaled to 100 x 60 at the cell origin
Placements[0].Matrix := HPDFMatFromOps(100, 0, 0, 60, 0, 0);
Placements[0].ClipX := 0;
Placements[0].ClipY := 0;
Placements[0].ClipWidth := 100;
Placements[0].ClipHeight := 60;
// Placement 1: mirrored horizontally into the right half of the cell
Placements[1].Matrix := HPDFMatFromOps(-100, 0, 0, 60, 200, 0);
Placements[1].ClipX := 100;
Placements[1].ClipY := 0;
Placements[1].ClipWidth := 100;
Placements[1].ClipHeight := 60;
Pattern := HPDF.RegisterImageTilingPattern(ImageIndex,
0, 0, 200, 60, // cell bounding box
200, 60, // XStep, YStep: the doubled cell
Placements, pttNoDistortion, HPDFMatIdentity);
HPDF.CurrentPage.SaveState;
try
HPDF.CurrentPage.SetFillPattern(Pattern);
HPDF.CurrentPage.AppendRawContent('50 400 500 180 re f'#10); // PDF points
finally
HPDF.CurrentPage.RestoreState;
end;
end;
Validation runs before the pattern is registered. The method accepts between 1 and 1,024 placements, requires finite, positive clip rectangles and invertible placement matrices, and raises ERangeError for an image index that does not exist. The XPS converter uses pttNoDistortion for every brush, with XStep and YStep equal to the cell size so the tiles pack edge to edge. Tiling patterns and the Pattern color space walks through the PDF operators underneath
When a radial gradient is an ellipse
XPS defines a RadialGradientBrush with GradientOrigin, Center, RadiusX and RadiusY, so the brush is an ellipse. PDF shading type 3 (ISO 32000-1 §8.7.4.5.4) blends between two circles and has no ellipse form. Averaging the two radii is the tempting shortcut, and it is wrong on any brush that is not close to round. A brush with RadiusX="200" and RadiusY="50" would turn into a 125-unit circle that overshoots the shape vertically by 75 units and falls short horizontally by the same amount
An ellipse needs a non-uniform scale, and the place for it is the pattern's /Matrix. A shading pattern is anchored to the default space of its parent content stream (ISO 32000-1 §8.7.3.1), the same rule that governs the tiling patterns above, so a cm emitted just before scn never reaches it. Divide the gradient's Y coordinates by RadiusY / RadiusX, put that factor into /Matrix, and the circle of radius RadiusX becomes the ellipse. For the 200 × 50 brush above the factor is 0.25, and the shading itself stays a plain 200-unit circle
HotPDF registers the circular shading with its Y coordinates divided by RadiusY / RadiusX, through RegisterMultiStopRadialGradient, a public THotPDF method that takes the two circles plus parallel arrays of stop positions and stop colors
Relative mapping mode adds a second trap. With relative coordinates, RadiusX has to be resolved against the path width and RadiusY against the path height. Scaling both by one edge length changes the aspect ratio of the ellipse on every path that is not square
What the converter counts instead of drawing
A JPEG ImageSource goes in as a JPEG image, a PNG with a real alpha channel is split into a base image plus an /SMask, and an opaque PNG becomes a Flate image. TIFF and JPEG XR parts are decoded through Windows Imaging Component and flattened onto white, so PNG is the format to pick when transparency has to survive. Intrinsic size is pixel × 96 / DPI, reading PNG pHYs or JPEG JFIF density first and falling back to 96 DPI. A 1,200-pixel-wide PNG tagged at 300 DPI therefore occupies 384 XPS units, or 288 points on the PDF page
Constructs without a faithful PDF mapping increment UnsupportedFeatureCount: unresolved matrix resources, non-standard RelativeTransform values, ColorConvertedBitmap image sources and malformed geometry among them. Malformed input fails closed, so a broken Glyphs element or an invalid clip is never swapped for a different drawing that merely looks plausible. Treat a non-zero count as a finding. For an archive job, a conversion that names four constructs it could not represent beats one that quietly approximates them, because the count gives a reviewer something concrete to check before the PDF is sealed into a records system
The document handler registry, the matrix helpers and the tiling pattern API used above all ship in the HotPDF component for Delphi and C++Builder, whose product page covers the rest of an archive pipeline (font embedding, signatures, PDF/A) and the supported IDE versions