PDF Maker 1.0.0 · manual

PDF Maker manual

Version 1.0.0. A short overview is in the README.md file and the release history is in the CHANGELOG.md file, both in the root folder of the package.

Overview

PDF Maker writes PDF files from C#. You build a PdfDocument, add content to it and save it as a byte[], to a Stream or to a file. It is pure C# with no native plugin. It was run on Windows 11 (Editor, Mono and IL2CPP players) and on Android x86-64 emulators; other platforms were not run. The Platform support section says what was run and when.

There are two layers, and they draw on the same pages, so you can mix them:

  • The canvas (PdfCanvas) draws at exact positions on one page: text, lines, rectangles, rounded rectangles, ellipses, arcs, polygons, bezier paths and images, with fill and stroke colours, opacity, dashes, clipping and transforms.
  • The layout layer (methods of PdfDocument, plus PdfTable) places headings, paragraphs, lists, tables and images one under the other between the page margins. It adds pages when a page is full, repeats table headers on every page and calls your header and footer code, so a footer can say "Page 3 of 12".

The package is made for Unity. It takes Texture2D, Color, Color32, Rect, Vector2 and TextAsset, it has helpers that put a screenshot or a camera render on a page, and a menu that turns a .ttf file into a font asset. It is plain managed C#: no native plugin and no third-party library, so there is nothing to set up per platform. The package adds no permissions and nothing to your Android manifest or Gradle files.

What it is not: PDF Maker writes PDF files and does nothing else. It does not read, edit or merge existing PDF files, and it does not show them. To show a result inside your game, see Opening the result with PDF Viewer. The full list of what is not included is under Limitations.

Requirements

  • Unity 6000.0.84f1 or newer. Tested with Unity 6000.0.84f1 and 6000.3.12f1 only. The Platform support section says which Unity versions and platforms were run.
  • The built-in modules Image Conversion (used to store a texture as a JPEG) and Screen Capture (used by PdfCapture.Screenshot). The package declares them, so Unity enables them with the package.
  • No other package is required. The demo scenes use uGUI (com.unity.ugui). The Input System package is optional for the demo. PDF Viewer (com.luanrobs.pdfviewer) is optional too: the demo uses it to open the result when it is installed.
  • The package contains no native code. It was run with the Mono and IL2CPP scripting backends in Windows 11 players and with IL2CPP on Android x86-64 emulators; other platforms were not run. The Platform support section says what was run.

If your scripts are in an assembly definition, add a reference to Luanrobs.PdfMaker. Scripts that are not in an assembly definition can use the package directly.

Installation

From the Asset Store

  1. Open the Package Manager: Window > Package Manager in Unity 6.0, Window > Package Management > Package Manager in Unity 6.3.
  2. Select My Assets and find PDF Maker.
  3. Click Install.

Unity installs PDF Maker as a package. It appears in the Project window under Packages > PDF Maker, not under Assets/, and its files are read-only. Your own scripts, scenes and fonts go under Assets/ as usual.

Folders of the package whose name ends in ~ are not shown in the Project window: Documentation~ (this manual) and Samples~ (the demo, imported as described below). To reach them, right-click Packages > PDF Maker in the Project window and choose Show in Explorer (Reveal in Finder on macOS).

Demo scenes

  1. In the Package Manager, select PDF Maker.
  2. Open the Samples tab.
  3. Click Import next to Demo.

Unity copies the sample into your project under Assets/Samples, where you can open and change it. The sample has six small scenes in its Scenes folder. Open any demo scene (01 to 05) and press Play. To use 00 Menu, first add all six scenes to the Scene List (see below).

Scene What it shows File it saves
00 Menu Launcher with one button per scene. -
01 Hello World A heading and two paragraphs. The script that builds it fits on one screen. PDF Maker - Hello World.pdf
02 Report Several pages: headings, justified text, a table long enough to repeat its header, a bar chart and a pie chart drawn on the canvas, a camera render and a screenshot, and a "Page X of Y" footer. PDF Maker - Report.pdf
03 Certificate One landscape page drawn on the canvas: border, logo, the name you type into an input field and a rotated seal. PDF Maker - Certificate.pdf
04 Invoice Addresses, an items table with right-aligned numbers and striped rows, totals and a link. PDF Maker - Invoice.pdf
05 Unicode Font Greek, Cyrillic and accented Latin text in a TrueType font that the scene finds on the device and embeds at run time. PDF Maker - Unicode.pdf

Each scene has one component (HelloWorldDemo, ReportDemo, CertificateDemo, InvoiceDemo, UnicodeFontDemo). Its Generate() method, called by the Generate PDF button, builds the document, saves it to Application.persistentDataPath and shows the page count, the size and the path in a status line. Its Open() method, called by the Open button, opens the saved file; the button works once a file has been saved. Each component also has a static Build method that creates the PdfDocument without any scene, which is the part worth reading. The scripts are kept short so that they can be read as documentation.

Things to know:

  • The scenes use uGUI with Unity's built-in font, so they need the com.unity.ugui package. They do not need TextMeshPro, and the sample contains no font file. The package itself does not need uGUI.
  • The scenes use the luanrobs colours: cream on navy. The sample PDFs use navy ink and a kraft accent. The certificate is drawn on a cream page; the other documents are on white pages, and the report and the invoice stripe the rows of their tables in cream.
  • 00 Menu has a small luanrobs.com/pdf-maker line in its footer. It opens the product page, and only when it is clicked. To remove it, delete the Site Link object of that scene (Demo Frame > Safe Area > Site Link). The footer of the hello world, report, invoice and unicode PDFs prints the same address as a link; it is drawn by DemoPaper.cs in the sample. The certificate has no footer.
  • The EventSystem is created at run time with the input module that matches your project (the Input System package or the legacy Input Manager).
  • The menu loads the other scenes by name. To run it, in Play mode in the Editor as well as in a build, first add all six scenes to the Scene List in File > Build Profiles, with 00 Menu first. Until then a menu button only says that its scene is not in the build. The five demo scenes (01 to 05) need no Scene List: open one and press Play.
  • The report scene waits for the end of a frame before it captures the screen, so building the report spans frames. Its status line is updated when the file is written.
  • The unicode scene looks through the fonts of the device for the first font file whose name is one of arial.ttf, segoeui.ttf, Roboto-Regular.ttf, NotoSans-Regular.ttf, DroidSans.ttf or DejaVuSans.ttf and that PDF Maker accepts. When it finds none, it draws the page in Helvetica and says that no font was found. To embed your own font instead, assign a PDF Font Asset to the Font Asset field of the component.
  • A font that a scene embeds at run time stays under its own license. See Embedding a TrueType font.
  • The Open button opens the saved file only when you click it. With PDF Viewer installed it uses the viewer; otherwise it asks the system to open the file, except on WebGL and on Android, where the status line says what to do instead. See Opening the result with PDF Viewer.
  • The sample data is invented ("Example Studio").
  • A README.txt in the sample folder repeats these notes.

Quick start

  1. Create a script named HelloPdf and paste the code below.
  2. Add it to a GameObject and press Play.
  3. Open hello.pdf from Application.persistentDataPath with any PDF viewer. The path is printed in the Console.
using System.IO;
using Luanrobs.PdfMaker;
using UnityEngine;

public class HelloPdf : MonoBehaviour
{
    private void Start()
    {
        var document = new PdfDocument();
        document.Metadata.Title = "Hello";

        document.AddHeading("Hello, PDF");
        document.AddParagraph("This file was created by PDF Maker while the game was running.");

        string path = Path.Combine(Application.persistentDataPath, "hello.pdf");
        document.Save(path);
        Debug.Log("Saved " + path);
    }
}

Save(string) writes a file, Save(Stream) writes to any stream and ToBytes() returns the file as a byte[]. See Saving.

The same code runs in the Editor. This script adds a menu command that saves a PDF in the root folder of your project (beside Assets) and shows it in the file browser. Put it in a folder named Editor.

using System.IO;
using Luanrobs.PdfMaker;
using UnityEditor;
using UnityEngine;

public static class ExportPdfMenu
{
    [MenuItem("Tools/My Project/Export Scene Report")]
    private static void Export()
    {
        int objects = Object.FindObjectsByType<Transform>(FindObjectsSortMode.None).Length;

        var document = new PdfDocument();
        document.AddHeading("Scene report");
        document.AddParagraph("Objects in the open scenes: " + objects);

        string path = Path.Combine(Directory.GetCurrentDirectory(), "SceneReport.pdf");
        document.Save(path);
        EditorUtility.RevealInFinder(path);
    }
}

The rest of this manual goes through the package by topic. Layout is the shortest way to a laid-out document; The canvas is for anything that has to sit at an exact place.

Coordinates, units and colours

Units. Every length is in points, 1/72 inch. PdfUnit converts everyday lengths: PdfUnit.Mm(25), PdfUnit.Cm(2.5f), PdfUnit.Inch(1) and PdfUnit.Px(96) (pixels at 96 per inch, so one pixel is 0.75 point).

Axes. The origin is the top-left corner of the page, x grows to the right and y grows downward. A Rect is given by its top-left corner and its size: new Rect(left, top, width, height).

Angles. Angles are in degrees. 0 points right (3 o'clock) and positive angles turn clockwise as seen on the page, so 90 points down.

Page sizes. The presets are portrait.

Preset Size Points (width x height)
PdfPageSize.A3 297 x 420 mm 841.8898 x 1190.5512
PdfPageSize.A4 210 x 297 mm 595.2756 x 841.8898
PdfPageSize.A5 148 x 210 mm 419.5276 x 595.2756
PdfPageSize.Letter 8.5 x 11 inches 612 x 792
PdfPageSize.Legal 8.5 x 14 inches 612 x 1008

Colours. Colours are Unity Color values (a Color32 converts to Color by itself). Red, green and blue are clamped to 0..1 and written to the file as they are, whatever colour space the project uses. The alpha of a colour is its opacity: see Opacity. Colours are RGB; PDF Maker has no CMYK drawing and no colour management.

Text. Text is a C# string. Code points are read from UTF-16, so characters outside the Basic Multilingual Plane work in a font that has them. Whether a character can be drawn depends on the font: see Fonts.

Documents and pages

The document

new PdfDocument() creates an empty document. It has no page until you add one or add content. A document is built once: the first save seals it, and a sealed document cannot be changed. See Saving.

Member Type Default Description
Metadata PdfMetadata empty Title, author and other properties. See Metadata.
DefaultPageSize PdfPageSize A4 The size of pages added without an explicit size.
DefaultOrientation PdfOrientation Portrait The orientation of pages added without an explicit size.
DefaultMargins PdfMargins 54 points (0.75 inch) on every side The margins of pages added with AddPage.
Compression PdfCompression Optimal How page content and embedded font programs are compressed. See Compression and the file.
Deterministic bool false The same calls give the same bytes. See Deterministic output.
SubsetFonts bool true Embed only the glyphs that the document uses. See Subsetting.
Header Action<PdfPageContext> null Called for every page when the document is saved. See Headers, footers and page numbers.
Footer Action<PdfPageContext> null The same, for the bottom of the page.
Styles PdfStyleSheet the default styles The styles that the layout methods use when you pass none. See Styles.
PageCount int 0 The number of pages added so far.
IsSealed bool false True once the first save has started, also when it failed. A save refused for a bad argument, such as a null path, does not seal the document.
CurrentPage PdfPage - The page where the next layout block goes: the last page.
CursorY float - Where the next layout block starts on CurrentPage. See How the flow works.

Every setter throws InvalidOperationException once the document is sealed.

Pages

using Luanrobs.PdfMaker;
using UnityEngine;

public class PageSetupExample : MonoBehaviour
{
    private void Start()
    {
        var document = new PdfDocument();
        document.DefaultPageSize = PdfPageSize.Letter;
        document.DefaultMargins = new PdfMargins(PdfUnit.Inch(1f));

        PdfPage first = document.AddPage();
        PdfPage ticket = document.AddPage(PdfPageSize.FromMillimeters(80f, 200f));
        PdfPage slide = document.AddPage(PdfPageSize.A4, PdfOrientation.Landscape);
        slide.Margins = new PdfMargins(PdfUnit.Mm(10f), PdfUnit.Mm(15f));

        Debug.Log("First page: " + first.Width + " x " + first.Height + " points");
        Debug.Log("Ticket content area: " + ticket.ContentRect);
        Debug.Log("Slide content area: " + slide.ContentRect);
        Debug.Log("Pages: " + document.PageCount + ", second page index: " + document.GetPage(1).Index);
    }
}
  • AddPage() adds a page with DefaultPageSize, DefaultOrientation and DefaultMargins.
  • AddPage(size, orientation) adds a page of a given size. Portrait makes the short side the width and Landscape makes the long side the width, whatever shape the size you pass had.
  • GetPage(index) returns a page by zero-based position. An index outside the document throws ArgumentOutOfRangeException.
  • A custom PdfPageSize has sides from 3 to 14400 points (PdfPageSize.MinSide, PdfPageSize.MaxSide). PdfPageSize.FromMillimeters converts from millimetres. Oriented(orientation) returns a size turned the way you ask; a square size is returned unchanged. A value outside the range, or not a number, throws ArgumentOutOfRangeException. A PdfPageSize that was never set, such as default(PdfPageSize), is refused by AddPage with ArgumentException.
  • Pages that the layout methods add copy the size, orientation, margins and header/footer setting of the page they continue.
PdfPage member Description
Document The document the page belongs to.
Index Zero-based position of the page.
Width, Height The page size in points, orientation applied.
Margins The margins of this page. Settable.
ContentRect The area inside the margins.
ShowHeaderAndFooter Whether Header and Footer are called for this page. Default true.
Canvas The drawing surface of the page. One canvas per page.
AddLink(rect, url) Makes an area of the page clickable. See Links.

Margins

PdfMargins has three constructors: one value for all sides, one value for left and right and another for top and bottom, or one value per side in the order left, top, right, bottom. Every value is zero or more.

The margins bound what the layout methods place on the page. Headers are drawn in the top margin and footers in the bottom margin, so leave room for them: the default 54 points is enough for a line or two of small text. Drawing on the canvas ignores margins.

PdfPage.ContentRect is the area inside the margins: x is the left margin, y is the top margin, width is the page width minus the left and right margins and height is the page height minus the top and bottom margins.

Margins that leave less than one point of width or height on a page throw ArgumentException, from AddPage or from the Margins setter. Changing Margins affects only what the layout methods place from then on; content that is already placed does not move. When you change the margins of the page the layout continues on before anything is placed on it (for example right after AddPageBreak(), or on CurrentPage of a new document), CursorY moves to the new top margin; once something is placed, the cursor stays where it is.

The canvas

page.Canvas is the drawing surface of a page. There is one canvas per page. The layout methods, your own drawing and the header and footer callbacks all draw on it, in the order of the calls, later drawing on top of earlier drawing.

State

The canvas remembers a state: fill colour, stroke colour, line width, cap, join, dash pattern, font, font size, line spacing, transform and clipping area. The table gives the defaults of every new page. In addition, lines are solid, there is no transform and there is no clipping.

Property Default Description
FillColor opaque black The colour of fills and text. Its alpha is their opacity.
StrokeColor opaque black The colour of strokes. Its alpha is their opacity.
LineWidth 1 The thickness of strokes in points. 0 draws the thinnest line the output device can show. Negative or not a number throws ArgumentOutOfRangeException.
LineCap Butt The ends of open strokes: Butt, Round or Square.
LineJoin Miter The corners of strokes: Miter, Round or Bevel.
Font PdfFont.Helvetica The font of DrawText and DrawTextBox. Null throws ArgumentNullException.
FontSize 12 The font size in points. Must be greater than zero.
LineSpacing 1.2 The height of one line of DrawTextBox as a multiple of FontSize. Must be greater than zero.

SaveState() remembers the whole state and RestoreState() brings it back. Calls can nest. Bracket temporary changes with them. Clipping can only be undone that way. RestoreState() without a matching SaveState() throws InvalidOperationException. States that are still saved when the document is sealed are restored automatically. The current path is not part of the state.

SetDash(pattern, phase) makes strokes dashed. The pattern lists the lengths of dash, gap, dash, gap and so on, in points; a single value is used for both dash and gap. SetDash(null) or an empty array makes strokes solid again. A negative or non-finite length or phase throws ArgumentOutOfRangeException, and a pattern whose lengths are all zero throws ArgumentException.

Paths and shapes

A path is built with MoveTo, LineTo, CurveTo, AddArc, ClosePath and the Add... shape methods, and then painted with Fill, Stroke, FillAndStroke or Clip, which also clear it. A path takes the colours, line settings and transform that are in effect when it is painted, not when it was built. Changing state, drawing text or drawing an image does not disturb a path that is being built.

Method Description
MoveTo(x, y) Starts a new part of the path.
LineTo(x, y) A straight segment from the current point. Throws InvalidOperationException when there is no current point.
CurveTo(c1x, c1y, c2x, c2y, x, y) A cubic bezier curve from the current point. Throws InvalidOperationException when there is no current point.
AddArc(cx, cy, radius, startDegrees, sweepDegrees) A circular arc. When the path has a current point, a straight segment joins it to the start of the arc; otherwise the arc starts a new part. The sweep is clamped to -360..360. A negative radius throws ArgumentOutOfRangeException.
ClosePath() Joins the current point to the start of the current part. Does nothing on an empty path.
AddRect(rect) A closed rectangle.
AddRoundedRect(rect, radius) A closed rectangle with rounded corners. The radius is clamped to half the shorter side.
AddEllipse(bounds) A closed ellipse that touches the four sides of the rectangle. A square gives a circle.
AddPolygon(points) A closed polygon. At least two points, otherwise ArgumentException.
Fill() Fills the path with FillColor. The non-zero winding rule is used and open parts are closed.
Stroke() Draws the outline with StrokeColor and the line settings.
FillAndStroke() Fills, then draws the outline on top.
Clip() Limits all later drawing to the inside of the path. See Clipping.

Painting an empty path does nothing. Every method checks its arguments before it writes anything, so a call that throws leaves the page as it was. Coordinates and sizes that are NaN or infinite throw ArgumentOutOfRangeException, and so does a negative rectangle size.

The shortcut methods build a shape, paint it and leave the current path as it was:

Shortcut What it does
DrawLine(x1, y1, x2, y2) Strokes a line.
FillRect(rect), StrokeRect(rect) Fills or strokes a rectangle.
FillRoundedRect(rect, radius), StrokeRoundedRect(rect, radius) The same for a rounded rectangle.
FillEllipse(bounds), StrokeEllipse(bounds) The same for an ellipse.
FillCircle(cx, cy, radius), StrokeCircle(cx, cy, radius) The same for a circle. The radius is zero or more.
FillPolygon(points), StrokePolygon(points) The same for a closed polygon.
using System.IO;
using Luanrobs.PdfMaker;
using UnityEngine;

public class ShapesExample : MonoBehaviour
{
    private void Start()
    {
        var document = new PdfDocument();
        PdfCanvas canvas = document.AddPage().Canvas;

        // A rounded rectangle, filled and outlined.
        canvas.FillColor = new Color(0.9f, 0.9f, 0.9f, 1f);
        canvas.StrokeColor = Color.black;
        canvas.LineWidth = 2f;
        canvas.AddRoundedRect(new Rect(50f, 50f, 200f, 100f), 10f);
        canvas.FillAndStroke();

        // A dashed line. SaveState and RestoreState keep the dash and the colour local.
        canvas.SaveState();
        canvas.SetDash(new[] { 6f, 3f });
        canvas.StrokeColor = Color.red;
        canvas.DrawLine(50f, 180f, 250f, 180f);
        canvas.RestoreState();

        // A filled triangle.
        canvas.FillColor = new Color(0.2f, 0.4f, 0.8f, 1f);
        canvas.FillPolygon(new Vector2(300f, 150f), new Vector2(400f, 150f), new Vector2(350f, 60f));

        // A pie slice: move to the centre, add the arc, close the path.
        canvas.FillColor = new Color(0.9f, 0.6f, 0.1f, 1f);
        canvas.MoveTo(450f, 100f);
        canvas.AddArc(450f, 100f, 50f, -90f, 120f);
        canvas.ClosePath();
        canvas.Fill();

        // A curve.
        canvas.LineWidth = 3f;
        canvas.LineCap = PdfLineCap.Round;
        canvas.MoveTo(50f, 250f);
        canvas.CurveTo(120f, 200f, 180f, 300f, 250f, 250f);
        canvas.Stroke();

        document.Save(Path.Combine(Application.persistentDataPath, "shapes.pdf"));
    }
}

Arc angles follow the page: 0 is to the right of the centre, 90 is below it and a positive sweep goes clockwise. The pie slice above starts at the top (-90) and sweeps 120 degrees clockwise.

Text

DrawText(text, x, y) draws one line of text with Font, FontSize and FillColor. (x, y) is the top-left corner of the text: the baseline lies Font.GetAscent(FontSize) below y. The text is not wrapped; line breaks and other control characters are drawn as a space. An empty text draws nothing. A null text throws ArgumentNullException.

DrawText(text, x, y, alignment) places the text relative to x: Left starts at x, Center centres the text on x, Right ends it at x, and Justify is the same as Left.

For text that wraps, use DrawTextBox (see Text in a box) or the layout methods.

using System.IO;
using Luanrobs.PdfMaker;
using UnityEngine;

public class TextExample : MonoBehaviour
{
    private void Start()
    {
        var document = new PdfDocument();
        PdfCanvas canvas = document.AddPage().Canvas;

        canvas.Font = PdfFont.TimesRoman;
        canvas.FontSize = 18f;
        canvas.FillColor = Color.black;

        float anchor = 300f;
        canvas.DrawLine(anchor, 40f, anchor, 160f);
        canvas.DrawText("Left of the line", anchor, 50f);
        canvas.DrawText("Centred on the line", anchor, 90f, PdfTextAlign.Center);
        canvas.DrawText("Right of the line", anchor, 130f, PdfTextAlign.Right);

        document.Save(Path.Combine(Application.persistentDataPath, "text.pdf"));
    }
}

Images on the canvas

  • DrawImage(image, rect) stretches the image to fill the rectangle, upright. A rectangle with zero width or height draws nothing.
  • DrawImage(image, x, y, width) puts the top-left corner at a point and takes the height from the image's proportions. It returns the rectangle that the image covers.

The image's own transparency is kept. The alpha of FillColor does not apply to images. A null image throws ArgumentNullException. How to create images is described in Images and captures.

Transforms

Translate(dx, dy) moves the origin, Rotate(degrees) rotates around the current origin, Rotate(degrees, pivotX, pivotY) rotates around a point that stays in place, and Scale(sx, sy) scales relative to the current origin. They change the coordinate system for everything drawn afterwards: text, shapes and images. Each call is relative to the system the previous calls left. Positive angles turn clockwise as seen on the page. A scale factor that the file would store as zero (the file stores four decimals, so an absolute value below 0.00005), a value that is not a number, and any transform that combined with the ones already set could no longer be undone, throw ArgumentOutOfRangeException.

Transforms last until the RestoreState() that matches the SaveState() before them. Link rectangles added with PdfPage.AddLink ignore the transform.

Clipping

Clip() limits all later drawing to the inside of the current path, intersected with the clipping area already in effect. The limit lasts until the RestoreState() that matches the SaveState() before it.

Opacity

The alpha of FillColor is the opacity of fills and text. The alpha of StrokeColor is the opacity of strokes. Images use only their own alpha.

using System.IO;
using Luanrobs.PdfMaker;
using UnityEngine;

public class TransformClipOpacityExample : MonoBehaviour
{
    [SerializeField] private Texture2D photo;

    private void Start()
    {
        var document = new PdfDocument();
        PdfPage page = document.AddPage();
        PdfCanvas canvas = page.Canvas;
        PdfImage image = PdfImage.FromTexture(photo, 85);

        // The photo, clipped to a circle.
        canvas.SaveState();
        canvas.AddEllipse(new Rect(60f, 60f, 160f, 160f));
        canvas.Clip();
        canvas.DrawImage(image, new Rect(60f, 60f, 160f, 160f));
        canvas.RestoreState();

        // A translucent watermark across the page, turned 45 degrees counter-clockwise.
        canvas.SaveState();
        canvas.Translate(page.Width / 2f, page.Height / 2f);
        canvas.Rotate(-45f);
        canvas.FillColor = new Color(0f, 0f, 0f, 0.12f);
        canvas.Font = PdfFont.HelveticaBold;
        canvas.FontSize = 90f;
        canvas.DrawText("SAMPLE", 0f, -45f, PdfTextAlign.Center);
        canvas.RestoreState();

        document.Save(Path.Combine(Application.persistentDataPath, "transforms.pdf"));
    }
}

Fonts

A PdfFont is what text is drawn and measured with. A font is immutable and belongs to no document: create it once, keep it as long as you like and use it in any number of documents and on any thread. It holds only managed memory and has nothing to dispose.

There are two kinds: twelve of the fourteen standard PDF fonts (Helvetica, Times and Courier, four styles each; Symbol and ZapfDingbats are not included), which need no setup, and TrueType fonts that you supply, which are embedded in the file.

The standard fonts

Property Name FamilyName Ascent Descent
PdfFont.Helvetica Helvetica Helvetica 718 -207
PdfFont.HelveticaBold Helvetica-Bold Helvetica 718 -207
PdfFont.HelveticaOblique Helvetica-Oblique Helvetica 718 -207
PdfFont.HelveticaBoldOblique Helvetica-BoldOblique Helvetica 718 -207
PdfFont.TimesRoman Times-Roman Times 683 -217
PdfFont.TimesBold Times-Bold Times 683 -217
PdfFont.TimesItalic Times-Italic Times 683 -217
PdfFont.TimesBoldItalic Times-BoldItalic Times 683 -217
PdfFont.Courier Courier Courier 629 -157
PdfFont.CourierBold Courier-Bold Courier 629 -157
PdfFont.CourierOblique Courier-Oblique Courier 629 -157
PdfFont.CourierBoldOblique Courier-BoldOblique Courier 629 -157

Ascent and descent are in thousandths of the font size: at size 10, Helvetica rises 7.18 points above the baseline and drops 2.07 points below it. Helvetica is a sans-serif font, Times a serif font and Courier a fixed-width font. Each property returns the same instance every time.

The standard fonts are not embedded. The file only names the font and the PDF viewer supplies it. That keeps files small and needs no font file, but it has two consequences:

  • How the letters look is up to the viewer.
  • Some viewers do not draw fonts that are not embedded. The manual of the publisher's PDF Viewer package records that on Android 6.0 (API 23) its system renderer does not draw text in fonts that are not embedded. A PDF Maker file that uses only standard fonts was not opened in that viewer on Android 6.0 or on any other Android version. If a file must look the same everywhere, embed a font.

Characters a font can draw

The standard fonts draw Latin text in the Windows-1252 character set (WinAnsiEncoding):

  • U+0020 to U+007E (printable ASCII).
  • U+00A0 to U+00FF (the Latin-1 supplement: accented letters such as é, ç, ñ, ü, ß, and symbols such as £, ©, ¿).
  • These 27 more characters, among them the euro sign, curly quotes, the en and em dashes, the bullet, the ellipsis and the trademark sign.
U+0152 U+0153 U+0160 U+0161 U+0178 U+017D U+017E U+0192 U+02C6 U+02DC
U+2013 U+2014 U+2018 U+2019 U+201A U+201C U+201D U+201E U+2020 U+2021
U+2022 U+2026 U+2030 U+2039 U+203A U+20AC U+2122

Anything else is drawn as ? and measured with the width of ?. That includes Greek, Cyrillic, Arabic, Hebrew, Asian scripts, emoji and Latin letters such as ł, ő, ğ and č. To write them, embed a TrueType font that has them.

Rules that apply to every font:

  • Text is never rejected because of its characters, and no method throws for them.
  • Control characters (U+0000 to U+001F and U+007F) are drawn and measured as a space.
  • A lone surrogate counts as U+FFFD.
  • A character the font cannot draw becomes ? in a standard font and the font's missing-glyph shape (glyph 0, often an empty box) in an embedded font. In both cases it is measured with the width of that replacement, so alignment and wrapping stay consistent.
  • Each character is drawn with its own glyph, left to right. There is no kerning, no ligature substitution and no shaping.

Ask a font before you draw: font.HasGlyph(codePoint) and font.CanDraw(text). Control characters count as drawable, and an empty text gives true. HasGlyph returns false for a value outside U+0000 to U+10FFFF and for a surrogate (U+D800 to U+DFFF).

Embedding a TrueType font

An embedded font can draw any character it has a glyph for, and the file carries a map from glyphs back to characters, so a PDF viewer can copy and search the text. Because the glyphs are in the file, the viewer does not have to substitute another font.

PdfFont.FromTrueType(byte[] fontData) makes a font from the bytes of a .ttf file, or of an .otf file whose outlines are TrueType. The array is copied. It can be called from any thread. There are three common ways to get a font:

  1. Bytes you load yourself, for example with File.ReadAllBytes(path) or from a download.
  2. A TextAsset. Unity imports a file with the extension .bytes as a TextAsset, so name your font file MyFont.ttf.bytes and call PdfFont.FromTrueType(textAsset). This one is main thread only because it reads a Unity object; the font it returns can be used on any thread.
  3. A PDF Font Asset. Select a .ttf file (or .otf file with TrueType outlines) in the Project window and choose Assets > Create > luanrobs > PDF Maker > PDF Font Asset. The asset is created next to the file, named after it with " PDF Font" added (a number is appended when the name is taken), and holds a copy of the font file. Reference it from a script with a PdfFontAsset field and read Font. The original file is not changed, and the asset carries its own copy of the data, which is what a build includes.

The command is enabled when the selection contains a .ttf or .otf file, and creates one asset for each such file. If a font is refused, a dialog shows the reason, and the other files of the selection are still processed. The new asset is selected. The Inspector of the asset shows the source file name, the PostScript name, the family, the glyph count and the data size, and reminds you that the license of the font must allow embedding.

PdfFontAsset.Font creates the font the first time it is asked for and caches it. It is main thread only. An empty asset throws PdfMakerException ("The font asset is empty."). DataSize and SourceFileName describe the stored file.

using System.IO;
using Luanrobs.PdfMaker;
using UnityEngine;

public class EmbeddedFontExample : MonoBehaviour
{
    [SerializeField] private PdfFontAsset fontAsset;
    [SerializeField] private TextAsset fontFile;
    [SerializeField] private string fontPath;

    private PdfFont FromAsset()
    {
        return fontAsset.Font;
    }

    private PdfFont FromTextAsset()
    {
        return PdfFont.FromTrueType(fontFile);
    }

    private PdfFont FromFile()
    {
        return PdfFont.FromTrueType(File.ReadAllBytes(fontPath));
    }

    public void Generate()
    {
        PdfFont font = FromAsset();

        var document = new PdfDocument();
        document.Styles.SetFont(font);

        string text = "Olá, Γειά σου, Привет";
        if (!font.CanDraw(text))
        {
            Debug.LogWarning(font.Name + " does not have every character of the text.");
        }

        document.AddHeading(font.Name);
        document.AddParagraph(text);
        document.Save(Path.Combine(Application.persistentDataPath, "unicode.pdf"));
    }
}

document.Styles.SetFont(regular, bold) switches every layout style to your fonts in one call: Body and TableCell get the regular font, and the headings and TableHeader get the bold font, or the regular one when you pass none. On the canvas, set canvas.Font. In a text style, set style.Font.

What is accepted. TrueType outlines only. PdfFont.FromTrueType throws PdfMakerException, with a message that names the reason, for:

  • a file that is not a TrueType font, or is damaged or truncated;
  • an OpenType font with CFF outlines (a file that starts with OTTO);
  • a font collection (.ttc);
  • a WOFF or WOFF2 file;
  • a font whose license flags forbid embedding: the OS/2 fsType value "Restricted License" or "Bitmap embedding only".

A font flagged "No subsetting" is embedded whole whatever SubsetFonts says. Some CJK fonts are distributed as OpenType CFF files or as collections, which are not supported; use a version with TrueType outlines.

License. PDF Maker contains no font. Embedding a font copies it, or the glyphs used, into every PDF you produce. The only checks the package makes are the two fsType flags above; it cannot judge a license. You are responsible for the license of every font you embed. This applies to the fonts you embed at run time as well, such as the font that the unicode demo scene finds on the device.

Font assets in builds

A PdfFontAsset is a normal asset. It is included in a build when a scene or another asset references it, and the whole font file goes into the build once, as the asset's data. DataSize tells you how large that is. A font file that sits in the project without being referenced is not part of the build.

Subsetting

PdfDocument.SubsetFonts is true by default. The file then carries only the glyphs that the document drew, which keeps files small, instead of the whole font file. Glyph numbers are kept, so nothing about how you use the font changes. A font flagged "No subsetting" is embedded whole, and so is a font for which the subset would not be smaller than the font file. Set SubsetFonts to false to embed every font whole. Whole fonts make the file larger by about the size of the font file; fonts with very many glyphs, such as CJK fonts, are large files.

A subset keeps only the font tables a PDF viewer needs to draw the glyphs: head, hhea, maxp, hmtx, loca, glyf and, when the font has them, cvt , fpgm and prep. It does not carry the name table. In one viewer, the PDF engine of Windows, a subset of Courier New was drawn slightly lighter than the whole font in the same file, with the glyphs at the same positions; Arial, the font used by the tests and the demo, was drawn as expected. Other fonts were not compared in a viewer. If a viewer draws an embedded font lighter or differently than you expect, set SubsetFonts to false and compare. Whole fonts make the file larger, as described above.

The font program is compressed like page content (see Compression and the file).

Measuring text

font.MeasureWidth(text, fontSize) returns the width of a text drawn on one line, in points. Line breaks count as a space. MeasureWidth(text, startIndex, length, fontSize) measures part of a text; the range is in UTF-16 code units. GetAscent(fontSize) returns how far the tallest letters rise above the baseline (positive) and GetDescent(fontSize) how far letters such as g drop below it (zero or negative). The font size must be greater than zero.

For example, Helvetica gives MeasureWidth("Hello", 10f) of 22.78 points: (722 + 556 + 222 + 222 + 556) / 1000 x 10. Measuring and drawing follow the same rules, so a width you measured is the width that is drawn.

using Luanrobs.PdfMaker;
using UnityEngine;

public class FitTitleExample : MonoBehaviour
{
    private static float FitFontSize(PdfFont font, string text, float maxWidth, float startSize)
    {
        float size = startSize;
        while (size > 8f && font.MeasureWidth(text, size) > maxWidth)
        {
            size -= 1f;
        }

        return size;
    }

    private void Start()
    {
        float size = FitFontSize(PdfFont.HelveticaBold, "A long title that may not fit on one line", 300f, 28f);
        Debug.Log("Font size that fits: " + size);
    }
}

Images and captures

A PdfImage is a picture ready to be placed in a PDF. It is immutable and belongs to no document: create it once and use it on any number of pages and in any number of documents, from any thread. Each document stores the image's data once, however often it is drawn. The pixel data is compressed when the image is created and held in managed memory. There is nothing to dispose, and the source texture or byte array is not referenced afterwards.

Transparency is kept: an alpha channel becomes a soft mask, so the page shows through. HasAlpha is true when at least one pixel is not fully opaque. Pixels are taken as sRGB values, exactly as stored in the source. Width and Height are in pixels; the largest side is PdfImage.MaxSide, 16384.

Creating images

Method Thread Description
PdfImage.FromTexture(texture, jpegQuality) main Any Texture2D, readable or not.
PdfImage.FromPng(bytes) any The bytes of a PNG file, decoded in C#.
PdfImage.FromJpeg(bytes) any The bytes of a JPEG file, stored unchanged.
PdfImage.FromPixels(pixels, width, height) any Raw Color32 pixels in the order of Texture2D.GetPixels32.

From a texture. FromTexture works whether or not the texture is readable (Read/Write enabled) and whatever its format or compression. Mip level 0 is used. The texture is not modified and not kept. A texture that cannot be read directly is copied through the GPU, which needs a graphics device: it does not work in a batchmode run started with -nographics. jpegQuality 0 (the default) stores the pixels without loss. A value from 1 to 100 stores the colours as a JPEG of that quality, which is much smaller for screenshots, renders and photos; the alpha channel, if any, is still stored without loss. A texture larger than 16384 pixels on a side, or one whose pixels cannot be read, throws PdfMakerException. A quality outside 0..100 throws ArgumentOutOfRangeException. A null texture throws ArgumentNullException.

From PNG bytes. Greyscale, RGB, palette, greyscale with alpha and RGBA files are supported, with 1 to 16 bits per channel and transparency chunks. 16-bit channels are reduced to 8 bits. Colour profiles and gamma chunks are ignored. Interlaced (Adam7) files are not supported. Data that is not a PNG file, is damaged, is interlaced, is larger than 16384 pixels on a side or needs more than 1 GiB of pixel data to decode throws PdfMakerException. The decoder inflates the PNG data with System.IO.Compression; on a platform where that is missing it throws PdfMakerException as well.

From JPEG bytes. The bytes are stored in the PDF unchanged: no decoding, no loss, no recompression. The array is copied. Baseline, extended and progressive files with 8 bits per sample and one (grey), three (colour) or four (CMYK) components are supported. The EXIF orientation is not applied: the image is drawn as its pixels are stored, so a photo from a phone may need turning before you pass it in. Other JPEG processes, data that is not a JPEG file and sizes beyond 16384 pixels throw PdfMakerException.

From pixels. FromPixels takes width x height pixels in Unity's order: left to right, bottom row first, as Texture2D.GetPixels32 returns them. The array is not kept. A length that does not match throws ArgumentException, and a width or height outside 1..16384 throws ArgumentOutOfRangeException.

using System.IO;
using Luanrobs.PdfMaker;
using UnityEngine;

public class ImageSourcesExample : MonoBehaviour
{
    [SerializeField] private Texture2D logo;
    [SerializeField] private string pngPath;
    [SerializeField] private string jpegPath;

    private void Start()
    {
        PdfImage fromTexture = PdfImage.FromTexture(logo);
        PdfImage fromTextureJpeg = PdfImage.FromTexture(logo, 85);
        PdfImage fromPng = PdfImage.FromPng(File.ReadAllBytes(pngPath));
        PdfImage fromJpeg = PdfImage.FromJpeg(File.ReadAllBytes(jpegPath));

        var pixels = new Color32[16 * 16];
        for (int y = 0; y < 16; y++)
        {
            for (int x = 0; x < 16; x++)
            {
                pixels[(y * 16) + x] = new Color32((byte)(x * 16), (byte)(y * 16), 128, 255);
            }
        }

        PdfImage fromPixels = PdfImage.FromPixels(pixels, 16, 16);

        var document = new PdfDocument();
        PdfCanvas canvas = document.AddPage().Canvas;
        canvas.DrawImage(fromTexture, new Rect(50f, 50f, 100f, 100f));
        canvas.DrawImage(fromTextureJpeg, new Rect(170f, 50f, 100f, 100f));
        canvas.DrawImage(fromPixels, new Rect(290f, 50f, 100f, 100f));
        Rect used = canvas.DrawImage(fromPng, 50f, 200f, 200f);

        // The layout continues below what the canvas drew.
        document.CursorY = used.yMax + 12f;
        document.AddImage(fromJpeg, 300f, PdfTextAlign.Center);

        Debug.Log("The PNG covers " + used);
        document.Save(Path.Combine(Application.persistentDataPath, "images.pdf"));
    }
}

Putting an image on a page

On the canvas: DrawImage(image, rect) or DrawImage(image, x, y, width). In the flow: document.AddImage(image, width, alignment); see Images, space, lines and page breaks.

Screenshots and camera renders

PdfCapture turns what the game shows into a PdfImage. Both methods are main thread only and need a graphics device: in a batchmode run started with -nographics they throw PdfMakerException. The image they return can be used on any thread.

  • PdfCapture.Screenshot(jpegQuality) captures the screen as it is shown, user interface included, at the current screen resolution. Call it at the end of a frame, from a coroutine after yield return new WaitForEndOfFrame(); earlier in the frame the picture may be incomplete. Play mode or a player only: in Edit mode it throws PdfMakerException. The image is opaque. In a run started with -batchmode no frame is presented, so a coroutine that waits for the end of a frame never continues there; use RenderCamera in batchmode runs.
  • PdfCapture.RenderCamera(camera, width, height, jpegQuality) renders one camera into a picture of a size you choose, independent of the screen resolution. Screen Space - Overlay canvases are not part of a camera's view and are not in the picture. The camera is rendered once more for this, with its viewport rectangle set to the whole picture (so a split-screen camera fills it); its target texture, viewport rectangle and other settings are left as they were. It works in Edit mode and in Play mode. The image is opaque.
  • RenderCamera calls Camera.Render(). In a scriptable render pipeline (URP, HDRP) that call draws nothing, and throws no exception, in two cases, and the picture then comes out black: a URP camera whose Render Type is Overlay (render the Base camera of the stack instead; its overlay cameras are drawn with it), and a call made while the pipeline is rendering, for example from RenderPipelineManager.endCameraRendering or OnRenderObject (call it from Update, LateUpdate or a coroutine instead). RenderCamera cannot detect either case. This comes from how those pipelines are documented to behave; the capture helpers were run in the Built-in pipeline only.

The default jpegQuality of both is 90; pass 0 to store the pixels without loss. A null camera throws ArgumentNullException, a size outside 1..16384 or a quality outside 0..100 throws ArgumentOutOfRangeException, and a capture that fails throws PdfMakerException. A camera render larger than the graphics device can render (SystemInfo.maxTextureSize) throws PdfMakerException too.

using System.Collections;
using System.IO;
using Luanrobs.PdfMaker;
using UnityEngine;

public class CaptureExample : MonoBehaviour
{
    [SerializeField] private Camera sceneCamera;

    public void Generate()
    {
        StartCoroutine(GenerateRoutine());
    }

    private IEnumerator GenerateRoutine()
    {
        yield return new WaitForEndOfFrame();

        PdfImage screenshot = PdfCapture.Screenshot();
        PdfImage render = PdfCapture.RenderCamera(sceneCamera, 1280, 720, 80);

        var document = new PdfDocument();
        document.AddHeading("Screen and camera");
        document.AddImage(screenshot, 400f);
        document.AddImage(render, 400f, PdfTextAlign.Center);
        document.Save(Path.Combine(Application.persistentDataPath, "capture.pdf"));
    }
}

Layout

The layout methods of PdfDocument place blocks one under the other between the page margins and add pages when a page is full. They draw on the same page canvases as your own code.

How the flow works

Everything is immediate: each Add... call measures, breaks and draws at once. Nothing is reflowed later, so set styles before you add the content they apply to. The exception is a keep-together group, which is held back until it ends (see Keeping blocks together).

  • The content area is CurrentPage.ContentRect: the page minus its margins.
  • The cursor, document.CursorY, is where the next block starts, as a y coordinate from the top of the page. It starts at the top margin of each new page and moves down as blocks are added.
  • A block fits when its bottom is at or above the bottom of the content area; a tolerance of 0.01 point keeps float rounding from pushing a line to the next page. The cursor is at the top when it is within 0.01 point of the top of the content area.
  • A new page is a page added like the current one: same size, orientation, margins and header/footer setting. The cursor goes to its top margin.
  • The flow follows the last page of the document. If you call AddPage() yourself, the cursor moves to the top of that page and the next block goes there. With no page yet, the first block adds one.
  • document.CurrentPage is that page. Reading it, or reading CursorY, adds the first page when the document has none.
  • You can set CursorY to leave room for something you draw yourself, or to continue below it. A value that is not a finite number throws ArgumentOutOfRangeException.

The layout methods throw InvalidOperationException once the document is sealed, and ArgumentNullException for a null text, list, table or image.

Method What it adds
AddHeading(text, level) A heading of level 1, 2 or 3.
AddParagraph(text, style) A paragraph of wrapped text.
AddLink(text, url, style) A paragraph that opens a web address when clicked.
AddBulletList(items, style) A list with a bullet before each item.
AddNumberedList(items, style) A list numbered 1., 2., 3.
AddTable(table) A PdfTable. See Tables.
AddImage(image, width, alignment) An image as a block of its own.
AddSpace(height) Empty vertical space.
AddHorizontalLine(thickness, color) A rule from margin to margin.
AddPageBreak() Starts a new page.
BeginKeepTogether(), EndKeepTogether() A group of blocks that stay on one page.

Styles

A PdfTextStyle says how a block of text looks. A style is read when the block is added; changing it afterwards does not affect blocks already added. All lengths are in points. Pass a style to AddParagraph, AddLink, AddBulletList and AddNumberedList; pass none to use document.Styles.Body.

Property Default Description
Font PdfFont.Helvetica The font. Null throws ArgumentNullException.
FontSize 11 The size in points. Must be greater than zero.
Color opaque black The text colour. Its alpha is the opacity of the text.
Alignment Left Left, Center, Right or Justify.
LineSpacing 1.2 The height of one line as a multiple of FontSize. Must be greater than zero.
SpaceBefore 0 Empty space above the block. Skipped at the top of a page. Zero or more.
SpaceAfter 6 Empty space below the block. Zero or more.
KeepTogether false Never split the block between two pages when it fits on one.
LineHeight read only FontSize multiplied by LineSpacing.

new PdfTextStyle() makes the defaults, new PdfTextStyle(font, size) sets the font and the size, and Clone() returns an independent copy.

document.Styles holds the styles that are used when you pass none. Each document has its own set. Change them before adding the content they apply to.

PdfStyleSheet member Default
Body Helvetica 11, 6 points after. Paragraphs, lists and links.
Heading1 Helvetica-Bold 20, 12 points before and 8 after.
Heading2 Helvetica-Bold 15, 10 points before and 6 after.
Heading3 Helvetica-Bold 12, 8 points before and 4 after.
TableHeader Helvetica-Bold 10. Header cells of tables.
TableCell Helvetica 10. Body cells of tables.
LinkColor A medium blue (0.05, 0.27, 0.73). The colour of link text.
SetFont(regular, bold) Switches all styles to your fonts. Sizes, colours and spacing are kept.
using System.IO;
using Luanrobs.PdfMaker;
using UnityEngine;

public class StylesExample : MonoBehaviour
{
    private void Start()
    {
        var document = new PdfDocument();
        document.Styles.Body.FontSize = 10f;
        document.Styles.Body.Alignment = PdfTextAlign.Justify;
        document.Styles.Heading1.Color = new Color32(30, 45, 69, 255);

        var quote = new PdfTextStyle(PdfFont.TimesItalic, 12f)
        {
            Color = Color.gray,
            SpaceBefore = 6f,
            KeepTogether = true
        };

        document.AddHeading("Styles");
        document.AddParagraph("Body text uses the body style of the document.");
        document.AddParagraph("A quotation uses its own style.", quote);
        document.Save(Path.Combine(Application.persistentDataPath, "styles.pdf"));
    }
}

Text breaking

One set of rules breaks text into lines for paragraphs, table cells, lists and DrawTextBox.

  1. A line break in the text (\r\n, \r or \n) ends a line. A tab becomes four spaces.
  2. A line can break after a run of spaces, after a hyphen-minus (U+002D) when the next character is not a space, and at a zero width space (U+200B), which is removed and has no width. A no-break space (U+00A0) is never a break opportunity. A hyphen-minus gives no break when it starts a word or follows a no-break space (a minus sign, as in -1250.00, or the hyphens of --force), or when it stands between two digits (as in 2026-10-09), so a number or a date is never split after its hyphen.
  3. Lines are filled greedily: a line takes words while its width, measured without trailing spaces, fits the available width.
  4. Spaces at the end of a wrapped line are neither drawn nor measured. Spaces at the start of a line that began by wrapping are dropped. Spaces at the start of a line that follows a line break are kept.
  5. A word that is wider than the available width on its own is split between characters, as many per line as fit and at least one. This is also how text without spaces, such as Chinese or Japanese, wraps: between any two characters. Line-breaking rules of those scripts, such as not starting a line with closing punctuation, are not applied.
  6. An empty text is one empty line for a paragraph or a table cell, and zero lines for DrawTextBox and MeasureTextBox.

There is no automatic hyphenation: a long word is split, not hyphenated.

Line geometry. A line box is FontSize x LineSpacing high. The text is centred vertically in its line box: the baseline lies at the top of the line box plus half of the difference between the line height and the text height (ascent minus descent), plus the ascent. Alignment: Left starts at the left edge of the available width; Center centres the line; Right ends it at the right edge. Justify widens every space of a line equally so that the line fills the width, but only for a line that ended by wrapping and has at least one space. The last line of a paragraph, a line that ends with a line break and a line with a single word stay left-aligned.

Headings and paragraphs

Paragraph. AddParagraph(text, style):

  1. SpaceBefore is added to the cursor, unless the cursor is at the top of the page.
  2. If the style has KeepTogether, the whole paragraph does not fit in what is left of the page and it is no taller than a page, it starts a new page.
  3. Each line goes to a new page if it does not fit and the cursor is not at the top.
  4. SpaceAfter is added after the last line.

An empty text adds one empty line. A line break starts a new line.

Heading. AddHeading(text, level) is a paragraph in Styles.Heading1, Heading2 or Heading3 (levels outside 1..3 are clamped) that is kept on one page. It needs room for its own height, its SpaceAfter and two lines of body text (two times the line height of Styles.Body). Without that room, and when the cursor is not at the top, it starts a new page. A heading wraps like a paragraph.

That check is all a heading does: it is not tied to the block that follows. When the next block is a table, an image or a paragraph whose style has KeepTogether, and that block does not fit and moves to the next page, the heading stays behind at the bottom of the page. To keep a heading with such a block, put both between BeginKeepTogether() and EndKeepTogether(), or call AddPageBreak() before the heading.

using System.IO;
using Luanrobs.PdfMaker;
using UnityEngine;

public class FlowExample : MonoBehaviour
{
    private void Start()
    {
        var document = new PdfDocument();
        document.Styles.Body.Alignment = PdfTextAlign.Justify;

        document.AddHeading("Field notes");
        for (int i = 1; i <= 14; i++)
        {
            document.AddHeading("Entry " + i, 2);
            document.AddParagraph("The quick brown fox jumps over the lazy dog. " +
                "The quick brown fox jumps over the lazy dog. " +
                "The quick brown fox jumps over the lazy dog. " +
                "The quick brown fox jumps over the lazy dog.");
        }

        document.AddSpace(12f);
        document.AddHorizontalLine();
        document.AddParagraph("End of notes.");
        document.Save(Path.Combine(Application.persistentDataPath, "flow.pdf"));
    }
}

Lists. AddBulletList(items, style) and AddNumberedList(items, style) put a label in a column before each item. Items wrap with a hanging indent, so continuation lines line up with the first. The label column is FontSize x 1.5 wide for bullets; for numbers it is the width of the label of the last item (such as 10.) plus FontSize x 0.5. The bullet is U+2022 when the font has it, otherwise a hyphen. Numbers start at 1. Between items there are FontSize x 0.25 points. SpaceBefore and SpaceAfter of the style apply once, around the whole list. A null item is treated as empty. An empty collection adds nothing.

Text in a box. PdfCanvas.DrawTextBox wraps text inside a rectangle you choose; see Text in a box.

Images, space, lines and page breaks

AddImage(image, width, alignment). The width is in points; 0 (the default) uses the natural size of 0.75 point per pixel (96 pixels per inch). The image is scaled down, keeping its proportions, when it is wider than the content area, and again when it is taller than the content area. When it does not fit in what is left of the page, and the cursor is not at the top, it starts the next page. alignment places a narrower image between the margins; Justify is the same as Left. After the image the cursor moves down by its height plus 6 points. A negative or non-finite width throws ArgumentOutOfRangeException.

AddSpace(height). Moves the cursor down by height. Space that does not fit in what is left of the page is dropped: the next block starts at the top of the next page.

AddHorizontalLine(thickness, color). A line from the left margin to the right margin with 6 points of space above (skipped at the top of a page) and 6 below it. The thickness must be greater than zero. The default colour is a medium grey (0.6, 0.6, 0.6).

AddPageBreak(). Starts a new page like the current one. When the document has no page yet, it only adds the first page. Inside a keep-together group it throws InvalidOperationException.

Keeping blocks together

BeginKeepTogether() starts a group of blocks that must stay on one page. The blocks you add until EndKeepTogether() are held back, so CurrentPage and CursorY do not move while a group is open. When the group ends, its height is the sum of the space before, the height and the space after of every block (the space before the first block is not counted at the top of a page). If the group does not fit in what is left of the page and is no taller than a page, it starts a new page. Then the blocks are placed one after the other. A group that is no taller than a page stays on one page as a whole: inside it a heading does not ask for two lines of body text below itself, because the group was measured as a whole (so a heading can be the last block of a group, for example a caption under an image). A group that is taller than a page is placed by the normal rules and flows over several pages.

A group that is still open when you save is ended for you, and its blocks are placed. Calling BeginKeepTogether() while a group is open, or EndKeepTogether() without one, throws InvalidOperationException.

using System.IO;
using Luanrobs.PdfMaker;
using UnityEngine;

public class KeepTogetherExample : MonoBehaviour
{
    private void Start()
    {
        var document = new PdfDocument();
        for (int i = 1; i <= 24; i++)
        {
            document.BeginKeepTogether();
            document.AddHeading("Clause " + i, 3);
            document.AddParagraph("Each clause stays together with its heading, so a page never ends " +
                "with a heading on its own and the text on the next page.");
            document.EndKeepTogether();
        }

        document.Save(Path.Combine(Application.persistentDataPath, "clauses.pdf"));
    }
}

Mixing layout and drawing

Draw on CurrentPage.Canvas at the cursor and move the cursor past what you drew. Check first that your drawing fits, because the layout cannot know its height.

using System.IO;
using Luanrobs.PdfMaker;
using UnityEngine;

public class ChartExample : MonoBehaviour
{
    private void Start()
    {
        var document = new PdfDocument();
        document.AddHeading("Sales by region");

        float chartHeight = 160f;
        if (document.CursorY + chartHeight > document.CurrentPage.ContentRect.yMax)
        {
            document.AddPageBreak();
        }

        PdfPage page = document.CurrentPage;
        PdfCanvas canvas = page.Canvas;
        float left = page.ContentRect.x;
        float top = document.CursorY;
        float[] values = { 120f, 95f, 140f, 60f };

        canvas.FillColor = new Color32(30, 45, 69, 255);
        for (int i = 0; i < values.Length; i++)
        {
            float barHeight = values[i] / 140f * chartHeight;
            canvas.FillRect(new Rect(left + (i * 60f), top + chartHeight - barHeight, 40f, barHeight));
        }

        document.CursorY = top + chartHeight + 12f;
        document.AddParagraph("The chart above shows orders per region.");
        document.Save(Path.Combine(Application.persistentDataPath, "chart.pdf"));
    }
}

Text in a box

canvas.DrawTextBox(text, box, alignment, verticalAlignment) draws text wrapped to the width of a rectangle, with the canvas Font, FontSize, LineSpacing and FillColor. It returns the height of the drawn lines: the number of lines multiplied by the line height; an empty text draws nothing and returns 0.

  • The text is wrapped by the rules in Text breaking.
  • The block is placed at the top of the box (Top), centred between its top and bottom (Middle) or at its bottom (Bottom). Horizontally the lines are aligned like a paragraph inside the box, including Justify.
  • Text that needs more height than the box has is still drawn in full, past the bottom of the box (or past its top with Bottom). Nothing is clipped. Compare the returned height with the box to find out.
  • A box with a coordinate that is not a finite number, or a negative size, throws ArgumentOutOfRangeException.

canvas.MeasureTextBox(text, width) returns the height DrawTextBox would need for a width, with the current font settings, without drawing. A negative or non-finite width throws ArgumentOutOfRangeException.

using System.IO;
using Luanrobs.PdfMaker;
using UnityEngine;

public class TextBoxExample : MonoBehaviour
{
    private void Start()
    {
        var document = new PdfDocument();
        PdfCanvas canvas = document.AddPage(PdfPageSize.A4, PdfOrientation.Landscape).Canvas;

        string name = "Alexandra Maria de Souza Albuquerque";
        var box = new Rect(100f, 200f, 400f, 60f);

        // Make the name smaller until it fits the box.
        canvas.Font = PdfFont.HelveticaBold;
        float size = 40f;
        canvas.FontSize = size;
        while (size > 12f && canvas.MeasureTextBox(name, box.width) > box.height)
        {
            size -= 2f;
            canvas.FontSize = size;
        }

        canvas.StrokeRect(box);
        canvas.DrawTextBox(name, box, PdfTextAlign.Center, PdfVerticalAlign.Middle);
        document.Save(Path.Combine(Application.persistentDataPath, "name.pdf"));
    }
}

Tables

A PdfTable is a table of text cells. Fill it, then give it to document.AddTable(table). Columns share the table width by weight, cell text wraps, rows grow to fit their tallest cell, and header rows can repeat on every page the table reaches. A table belongs to no document: it is read when you add it, later changes do not affect that document, and the same table can be added again or to another document. A table without rows adds nothing.

using System.Globalization;
using System.IO;
using Luanrobs.PdfMaker;
using UnityEngine;

public class TableExample : MonoBehaviour
{
    private void Start()
    {
        var document = new PdfDocument();
        document.AddHeading("Items");

        var table = new PdfTable(4f, 1f, 1.5f, 1.5f);
        table.CellPadding = 5f;
        table.Borders = PdfTableBorders.Horizontal;
        table.HeaderBackground = new Color32(30, 45, 69, 255);
        table.HeaderStyle = new PdfTextStyle(PdfFont.HelveticaBold, 10f) { Color = new Color32(243, 238, 220, 255) };
        table.AlternateRowBackground = new Color32(243, 238, 220, 255);
        table.SetColumnAlignment(1, PdfTextAlign.Right);
        table.SetColumnAlignment(2, PdfTextAlign.Right);
        table.SetColumnAlignment(3, PdfTextAlign.Right);
        table.AddHeaderRow("Item", "Qty", "Unit price", "Amount");

        float total = 0f;
        for (int i = 1; i <= 60; i++)
        {
            float price = 4.5f + i;
            total += price * i;
            table.AddRow(
                "Item number " + i,
                i.ToString(CultureInfo.InvariantCulture),
                price.ToString("N2", CultureInfo.InvariantCulture),
                (price * i).ToString("N2", CultureInfo.InvariantCulture));
        }

        PdfTableRow last = table.AddRow("Total", "", "", total.ToString("N2", CultureInfo.InvariantCulture));
        last.Background = new Color(0.85f, 0.85f, 0.85f, 1f);
        last[3].Style = new PdfTextStyle(PdfFont.HelveticaBold, 10f);

        document.AddTable(table);
        document.Save(Path.Combine(Application.persistentDataPath, "items.pdf"));
    }
}

Creating a table

  • new PdfTable(columnCount) makes columns of equal width. columnCount is 1 to PdfTable.MaxColumns (64).
  • new PdfTable(weights) makes one column per weight. Weights are relative: (2, 1, 1) makes the first column twice as wide as each of the others. Each weight must be a finite number greater than zero, and there are 1 to 64 of them. An integer on its own is a column count, so new PdfTable(3) is three equal columns and new PdfTable(3f) is one column.
  • SetColumnWeights(weights) replaces the weights; it needs exactly ColumnCount values.
  • Width is the width of the whole table in points. 0 (the default) means the full width between the page margins. A table wider than that space is narrowed to it; a narrower table starts at the left margin. To give columns fixed widths in points, set Width to the sum of the weights.
  • AddHeaderRow(cells) and AddRow(cells) add a row and return it. Missing cells are empty and a null text is empty. More texts than columns throw ArgumentException. Header rows are always drawn above the body rows, in the order added, whenever they are added; you can have several.
  • HeaderRowCount and RowCount count header rows and body rows. GetHeaderRow(index) and GetRow(index) return a row by zero-based position among its kind.

A PdfTableRow has IsHeader, CellCount, Background and an indexer that returns a PdfTableCell. A cell has Text, Style, Alignment and Background.

Table options

Property Default Description
Width 0 Table width in points; 0 is the full content width.
HeaderStyle null Style of header cells; null uses Styles.TableHeader of the document.
CellStyle null Style of body cells; null uses Styles.TableCell of the document.
CellPadding 4 Space between the edge of a cell and its text, on all four sides.
MinRowHeight 0 The smallest height of a row.
Borders Grid Grid strokes every cell, Horizontal strokes a line above the first row, below the last row and between rows, None draws no lines.
BorderWidth 0.5 Thickness of border lines. Lines are centred on the cell edges and do not change cell sizes. Must be greater than zero.
BorderColor grey (0.6, 0.6, 0.6) The colour of border lines.
HeaderBackground light grey (0.9, 0.9, 0.9) Background of header rows; null for none.
AlternateRowBackground null Background of every second body row (the 2nd, 4th, 6th and so on of the whole table, whatever page they land on); null for no striping.
RepeatHeader true Draw the header rows again at the top of each further page the table reaches.
SpaceBefore 4 Empty space above the table; skipped at the top of a page.
SpaceAfter 8 Empty space below the table.

Width, CellPadding, MinRowHeight, SpaceBefore and SpaceAfter must be finite numbers, zero or more, and BorderWidth a finite number greater than zero; any other value throws ArgumentOutOfRangeException.

Cells, alignment and backgrounds

  • Style. A cell uses its own Style, otherwise the table's HeaderStyle or CellStyle, otherwise the document's Styles.TableHeader or Styles.TableCell. The space before and after and the Alignment of a style are not used inside cells.
  • Alignment. The alignment of a cell is its own Alignment if set, otherwise the alignment of its column (SetColumnAlignment(column, alignment), header cells included, every column starts left-aligned). Justify behaves as Left for a line that did not wrap. Text starts at the top of the cell, inside the padding.
  • Background. The background of a cell is its own Background if set, otherwise its row's Background, otherwise HeaderBackground for header rows or AlternateRowBackground for every second body row.
  • Row height. A row is as high as its tallest cell: the number of lines times the line height, plus twice the padding, but at least MinRowHeight. A cell's text wraps to the column width minus twice the padding (never less than 1 point).
  • Drawing order. For each row: backgrounds, then text, then borders.

Tables across pages

The table starts below SpaceBefore, which is skipped at the top of a page. The header rows and the first body row must fit together, otherwise (when the cursor is not at the top) the table starts on a new page. After that, a row that does not fit in what is left of the page, while something of the table is already on the page, goes to a new page, and the header rows are drawn again there when RepeatHeader is true. SpaceAfter is added after the last row.

Rows are never split between pages. A row that is taller than the content area of a page, less the repeated header rows, cannot fit anywhere: it is drawn at the top of a page, below the repeated header rows if there are any, and runs past the bottom of the content area. A row is placed once on a new page: it is not moved again to look for more room.

Not supported: cells that span several columns or rows, images inside cells and nested tables.

Headers, footers and page numbers

document.Header and document.Footer are callbacks of type Action<PdfPageContext>. When the document is saved, they are called once for every page whose ShowHeaderAndFooter is true, after all the content is placed and when the total number of pages is known. Pages are visited in order and the header of a page is called before its footer. This is what makes "Page 3 of 12" possible.

A PdfPageContext holds:

Member Description
Document The document being saved.
Page The page being decorated.
Canvas The canvas of the page. It is handed over in its default state (black, Helvetica 12, no transform, no clipping), and whatever the callback changes is discarded when it returns. What it draws lies on top of the page content.
PageNumber The number of this page, starting at 1.
PageCount The number of pages in the document.
HeaderRect The top margin strip between the left and right margins: x is the left margin, y is 0, width is the content width, height is the top margin.
FooterRect The bottom margin strip: x is the left margin, y is the bottom edge of the content area, width is the content width, height is the bottom margin.
ContentRect The area inside the margins.

The context is only valid during the callback. While the callbacks run, and only then, canvas methods and PdfPage.AddLink still work on a sealed document, but only on the page the callback was called for: drawing on another page throws InvalidOperationException, and so does saving the document from inside a callback. The callbacks run on the thread that saves.

using System.IO;
using Luanrobs.PdfMaker;
using UnityEngine;

public class HeaderFooterExample : MonoBehaviour
{
    private void Start()
    {
        var document = new PdfDocument();
        document.Metadata.Title = "Annual report";

        document.Header = context =>
        {
            PdfCanvas canvas = context.Canvas;
            Rect area = context.HeaderRect;
            canvas.FontSize = 9f;
            canvas.FillColor = Color.gray;
            canvas.StrokeColor = Color.gray;
            canvas.LineWidth = 0.5f;
            canvas.DrawText(context.Document.Metadata.Title, area.x, area.yMax - 24f);
            canvas.DrawLine(area.x, area.yMax - 8f, area.xMax, area.yMax - 8f);
        };

        document.Footer = context =>
        {
            PdfCanvas canvas = context.Canvas;
            Rect area = context.FooterRect;
            canvas.FontSize = 9f;
            canvas.FillColor = Color.gray;
            canvas.DrawText("Page " + context.PageNumber + " of " + context.PageCount, area.xMax, area.y + 18f, PdfTextAlign.Right);
        };

        // A cover page without header and footer. It still counts in the page numbers.
        PdfPage cover = document.AddPage();
        cover.ShowHeaderAndFooter = false;
        cover.Canvas.FontSize = 32f;
        cover.Canvas.DrawText("Annual report", 54f, 300f);

        // AddPage() starts the numbered pages with the default (header and footer shown).
        // AddPageBreak() would copy the setting of the cover and leave them out.
        document.AddPage();
        for (int i = 1; i <= 40; i++)
        {
            document.AddParagraph("Paragraph " + i + ". The numbers of the pages are known only when the file is saved.");
        }

        document.Save(Path.Combine(Application.persistentDataPath, "annual.pdf"));
    }
}
  • A page with ShowHeaderAndFooter set to false gets neither callback but still counts in PageNumber and PageCount. Pages that the layout adds, including those added by AddPageBreak(), copy the value from the page they continue. To start the numbered pages after a cover page, call document.AddPage(), which uses the default true, as the example above does.
  • A callback can draw anywhere on the page, not only in the header or footer area. Stay in HeaderRect and FooterRect to avoid the content.
  • An exception thrown by a callback leaves the save that triggered it. The document stays sealed without a file, and every later ToBytes or Save throws InvalidOperationException.
  • The text you draw is your own string, so context.PageNumber is turned into text by your code. Use ToString(CultureInfo.InvariantCulture) if the digits must not depend on the device's language.

There are two ways to make something clickable. Both open a web address.

  • document.AddLink(text, url, style) adds a paragraph in the link colour (Styles.LinkColor), underlined, in the flow. Every line of it is clickable. The colour of the style you pass is replaced by the link colour. A null text or address throws ArgumentNullException and an empty address throws ArgumentException.
  • page.AddLink(rect, url) makes an area of a page clickable. Nothing is drawn: draw the text or the button yourself. The rectangle is in page coordinates (origin top-left, points) and is not affected by canvas transforms. A null address throws ArgumentNullException, an empty one ArgumentException, and a rectangle with a coordinate that is not a finite number or with a negative size ArgumentOutOfRangeException. After the document is saved it throws InvalidOperationException, except inside header and footer callbacks.

Spaces, control characters and characters outside ASCII in an address are percent-encoded (as UTF-8 bytes). Use full addresses such as https://example.com/. What a viewer does when a link is clicked is up to the viewer. Links to other pages of the document and bookmarks are not supported.

using System.IO;
using Luanrobs.PdfMaker;
using UnityEngine;

public class LinkExample : MonoBehaviour
{
    private void Start()
    {
        var document = new PdfDocument();
        document.AddParagraph("Read the terms at:");
        document.AddLink("https://example.com/terms", "https://example.com/terms");

        // A button drawn on the canvas, made clickable with PdfPage.AddLink.
        PdfPage page = document.CurrentPage;
        var button = new Rect(54f, 200f, 180f, 36f);
        page.Canvas.FillColor = new Color32(30, 45, 69, 255);
        page.Canvas.FillRoundedRect(button, 8f);
        page.Canvas.FillColor = new Color32(243, 238, 220, 255);
        page.Canvas.DrawTextBox("Open the website", button, PdfTextAlign.Center, PdfVerticalAlign.Middle);
        page.AddLink(button, "https://example.com/");

        document.Save(Path.Combine(Application.persistentDataPath, "links.pdf"));
    }
}

Metadata

document.Metadata holds the properties that a PDF viewer shows under File > Properties.

Property Description
Title The document title.
Author The person or organisation that wrote the document.
Subject What the document is about.
Keywords Keywords, usually separated by commas.
Creator The application that created the content, for example your game's name.
Producer The software that wrote the file. Defaults to "luanrobs PDF Maker 1.0.0".
CreationDate When the document was created. Null (the default) means the moment it is saved, or no date at all when Deterministic is on. A DateTimeKind.Local value is converted to UTC; any other value is taken as UTC.

Every field is optional: a null or empty string is left out of the file. Any Unicode text is allowed; text that is not plain ASCII is stored as UTF-16 with a byte order mark, the standard form for PDF text strings. Values are read when the document is saved for the first time; changing them afterwards has no effect.

using System;
using Luanrobs.PdfMaker;
using UnityEngine;

public class MetadataExample : MonoBehaviour
{
    private void Start()
    {
        var document = new PdfDocument();
        document.Metadata.Title = "Invoice 2026-0001";
        document.Metadata.Author = "Example Studio";
        document.Metadata.Subject = "Invoice";
        document.Metadata.Keywords = "invoice, example";
        document.Metadata.Creator = "My Game";
        document.Metadata.CreationDate = new DateTime(2026, 10, 8, 12, 0, 0, DateTimeKind.Utc);

        document.AddHeading("Invoice 2026-0001");
        Debug.Log("File size: " + document.ToBytes().Length + " bytes");
    }
}

Compression and the file

document.Compression is a PdfCompression:

Value Description
None No compression. The page content is plain text that you can read in a text editor, which helps when debugging.
Fast Flate compression tuned for speed.
Optimal Flate compression tuned for size. This is the default.

The setting applies to page content and to embedded font programs. Images are compressed when the PdfImage is created, so the setting does not change them; a JPEG is stored as it is. Flate compression uses System.IO.Compression from the .NET class library. If a platform has no working implementation, the package falls back to writing the data in stored (uncompressed) blocks, so the file stays valid and only gets larger. The Platform support section lists the platforms that were run; on a platform that was not run, it is not known whether the fallback is used.

What the file looks like:

  • PDF version 1.7, with a classic cross-reference table. There are no object streams, no cross-reference streams and no incremental updates.
  • One content stream per page. A font, an image or an opacity setting that several pages use is stored once.
  • Line ends are line feeds. Numbers are formatted by one routine, with a dot as the decimal separator and at most four decimals, whatever language the device is set to.
  • A landscape page is written with its width and height swapped, not with a rotation.
  • The file has no tag structure and no document language, so it is not a tagged (accessible) PDF.

Deterministic output

With document.Deterministic = true and no Metadata.CreationDate, two documents created with the same calls and the same input are identical byte for byte, on the same runtime: the same platform, Unity version and scripting backend. Use it in tests and to compare files. Without a creation date, a deterministic file has no date at all; set Metadata.CreationDate to a fixed value if you want one.

The file also carries an identifier that is computed from the content of the file, so it changes only when the content changes.

Different platforms, Unity versions or scripting backends can compress the same data into different bytes, so compare files built in the same environment. In the test run, the invoice of the demo came out at 2901 bytes in a Windows player built with Mono and at 2906 bytes in one built with IL2CPP. The tests and checks of this package compare bytes only within one runtime.

using System.Linq;
using Luanrobs.PdfMaker;
using UnityEngine;

public class DeterministicExample : MonoBehaviour
{
    private static byte[] Build()
    {
        var document = new PdfDocument { Deterministic = true };
        document.Metadata.Title = "Repeatable";
        document.AddHeading("Same calls, same bytes");
        document.AddParagraph("Nothing here depends on the time or on chance.");
        return document.ToBytes();
    }

    private void Start()
    {
        bool same = Build().SequenceEqual(Build());
        Debug.Log("Identical: " + same);
    }
}

Threading

Nothing in PdfDocument and what you reach through it touches a Unity object. A document can therefore be built and saved on a worker thread, as long as your own code keeps to the same rule.

Call Thread
PdfImage.FromTexture Main thread only.
PdfCapture.Screenshot, PdfCapture.RenderCamera Main thread only.
PdfFont.FromTrueType(TextAsset), PdfFontAsset.Font Main thread only. They read a Unity object. The font they return can be used on any thread.
Unity objects and most Unity APIs, such as Application.persistentDataPath Main thread only. Color, Color32, Rect, Vector2 and Mathf are plain values and are fine anywhere.
PdfImage.FromPng, PdfImage.FromJpeg, PdfImage.FromPixels, PdfFont.FromTrueType(byte[]) Any thread.
PdfFont and PdfImage objects Immutable. Share them between threads and documents.
PdfDocument and everything reached through it (pages, canvases, tables being added) One thread at a time, not necessarily the main thread. Build a document once.
Header and footer callbacks The thread that saves.

The pattern: do everything that touches Unity on the main thread first, then hand plain data to a worker.

using System.IO;
using System.Threading.Tasks;
using Luanrobs.PdfMaker;
using UnityEngine;

public class BackgroundPdfExample : MonoBehaviour
{
    [SerializeField] private Texture2D logo;

    public async void Generate()
    {
        // Main thread: read Unity objects here.
        PdfImage logoImage = PdfImage.FromTexture(logo, 85);
        string path = Path.Combine(Application.persistentDataPath, "background.pdf");

        // Worker thread: nothing in this call touches a Unity object.
        await Task.Run(() => Build(logoImage, path));

        // Back on the main thread.
        Debug.Log("Saved " + path);
    }

    private static void Build(PdfImage logoImage, string path)
    {
        var document = new PdfDocument();
        document.AddImage(logoImage, 120f);
        for (int i = 1; i <= 200; i++)
        {
            document.AddParagraph("Line " + i + " was added on a worker thread.");
        }

        document.Save(path);
    }
}

WebGL. WebGL has no threads, so Task.Run and Thread are not available there. Build the document on the main thread. A large document can be built across frames: add a part of the content in each iteration of a coroutine and save at the end, so the game keeps drawing.

The package keeps no mutable static state. It does not need special handling when Domain Reload is turned off in the Enter Play Mode settings.

Saving

Method Description
ToBytes() Returns the file as a new byte[]. Each call returns a new array with the same content.
Save(Stream stream) Writes the file to a writable stream, starting at its current position. The stream is left open and is not flushed or rewound. A null stream throws ArgumentNullException; a stream that cannot be written to throws ArgumentException.
Save(string path) Writes the file to a path, replacing an existing file. Missing folders are created. Pass an absolute path, for example one under Application.persistentDataPath. A null path throws ArgumentNullException, an empty one ArgumentException.

On a worker thread, read Application.persistentDataPath on the main thread beforehand.

Errors from the file system are the framework's own exceptions and are not wrapped: IOException when the file or stream cannot be written (the document stays sealed and can be saved again) and UnauthorizedAccessException when the location is not writable.

Sealing. The first call of ToBytes or Save:

  1. places the blocks of a keep-together group that is still open;
  2. adds one empty page if the document has no page, because a PDF file needs at least one;
  3. seals the document: IsSealed becomes true, and every setter of the document and of its pages, every layout method, every canvas method that draws or changes the state, and PdfPage.AddLink throw InvalidOperationException from here on (changing Metadata, a style or a table does not throw, but has no effect on the file);
  4. visits the pages in order: restores canvas states that are still saved, then calls Header and Footer for pages that show them. During these callbacks, and only then, canvas methods and PdfPage.AddLink still work;
  5. writes the file into a byte array that the document keeps.

Later saves reuse that array. If a header or footer callback throws, or the file cannot be built (for example for lack of memory), the exception reaches your code, the document stays sealed without a file and every later ToBytes or Save throws InvalidOperationException with the first failure as its InnerException. A failed first save is final: the page content is handed over while the file is written, so the save cannot be repeated; build the document again.

Header and Footer are delegates. When you combine several methods in one of them with +=, each method is called on its own, with the canvas in its default state.

using System.IO;
using Luanrobs.PdfMaker;
using UnityEngine;

public class SavingExample : MonoBehaviour
{
    private void Start()
    {
        var document = new PdfDocument();
        document.AddHeading("Saved three ways");

        // 1. To a file.
        string path = Path.Combine(Application.persistentDataPath, "saved.pdf");
        document.Save(path);

        // 2. To a stream you control.
        using (var stream = new MemoryStream())
        {
            document.Save(stream);
            Debug.Log("Stream holds " + stream.Length + " bytes");
        }

        // 3. As bytes, for example to upload or to hand to another API.
        byte[] bytes = document.ToBytes();
        Debug.Log("Bytes: " + bytes.Length);
    }
}

Where files go. Application.persistentDataPath is the folder Unity provides for files that your game writes. Unity's own documentation lists where it is on each platform. On WebGL there is no folder that the player can open, and the package contains no code that starts a browser download: use ToBytes() with your own download code.

Error handling

Wrong arguments throw before anything is written, and a call that throws leaves the document as it was. Nothing in the package logs.

Save(path) checks what it can before it seals the document: a null or empty path, and a path the framework cannot resolve (for example one with a null character), throw ArgumentException (or NotSupportedException or PathTooLongException, depending on the path and the runtime) and leave the document unchanged. A path that only the file system refuses when the file is created (characters such as <, >, | or " in the name on Windows, a missing drive, no permission) throws the framework's exception after the document has been sealed; the document can then still be saved to another path, but no longer changed. Check a file name that a player typed, for example against Path.GetInvalidFileNameChars(), before you build the path.

Exception When
ArgumentNullException An argument that must not be null is null.
ArgumentOutOfRangeException A number is NaN or infinite, or outside its range: a negative length, a size or index out of range, a quality outside 0..100.
ArgumentException Any other wrong argument: an empty address, a wrong number of weights or cells, fewer than two polygon points, a pixel array of the wrong length, margins that leave no room, an unwritable stream.
PdfMakerException Data that cannot be used: a font file that is not a supported TrueType font or that forbids embedding, image bytes that are not a supported PNG or JPEG, a texture that cannot be read, a capture that fails, an empty font asset.
InvalidOperationException A call that does not fit the state: LineTo or CurveTo without a current point, RestoreState without SaveState, changing a sealed document, a nested BeginKeepTogether, AddPageBreak inside a group, drawing from a header or footer callback on a page other than its own, saving after a header or footer callback threw.
IOException, UnauthorizedAccessException The file system refused a save. These are the framework's exceptions.

Text never throws for its characters. A character the font cannot draw is replaced; see Characters a font can draw.

PdfMakerException is the one to catch when data comes from outside your game, such as a font or an image that a user supplies.

using System.IO;
using Luanrobs.PdfMaker;
using UnityEngine;

public class ErrorHandlingExample : MonoBehaviour
{
    public PdfFont TryLoadFont(byte[] fontBytes)
    {
        try
        {
            return PdfFont.FromTrueType(fontBytes);
        }
        catch (PdfMakerException exception)
        {
            Debug.LogWarning("The font was refused: " + exception.Message);
            return PdfFont.Helvetica;
        }
    }

    public bool TrySave(PdfDocument document, string path)
    {
        try
        {
            document.Save(path);
            return true;
        }
        catch (IOException exception)
        {
            Debug.LogWarning("Could not write " + path + ": " + exception.Message);
        }
        catch (System.UnauthorizedAccessException exception)
        {
            Debug.LogWarning("No permission to write " + path + ": " + exception.Message);
        }
        catch (System.ArgumentException exception)
        {
            Debug.LogWarning("Not a usable path: " + path + ": " + exception.Message);
        }
        catch (System.NotSupportedException exception)
        {
            Debug.LogWarning("Not a usable path: " + path + ": " + exception.Message);
        }

        return false;
    }
}

Opening the result with PDF Viewer

PDF Maker writes files. It has no viewer. To show a result inside your game, use PDF Viewer (com.luanrobs.pdfviewer), a separate luanrobs package, and call PdfViewer.OpenFile(absolutePath). The two packages do not depend on each other: PDF Maker never references the viewer.

The demo does it with a version define. Its assembly definition has a Version Defines entry that defines LUANROBS_PDFMAKER_DEMO_PDFVIEWER when the package com.luanrobs.pdfviewer is installed. With that define, the Open button calls Luanrobs.Pdf.PdfViewer.OpenFile(path). Without it, the button asks the system to open the file with a file:// address (Application.OpenURL), except on two platforms: on WebGL the status line says where the file is stored, and on Android it says that a file:// address cannot be handed to another app and suggests PDF Viewer. The button does this only when you click it; the demo never opens a file on its own.

To do the same in your project:

  1. Install PDF Viewer.
  2. In the assembly definition of your scripts, add Luanrobs.Pdf under Assembly Definition References.
  3. Under Version Defines, click + and set Resource to com.luanrobs.pdfviewer, Define to a name of your own, here MYGAME_PDFVIEWER, and Expression to 1.0.0.
  4. Open the file from a button.
using System;
using UnityEngine;

public static class ResultOpener
{
    public static void Open(string absolutePath)
    {
#if MYGAME_PDFVIEWER
        Luanrobs.Pdf.PdfViewer.OpenFile(absolutePath);
#else
        Application.OpenURL(new Uri(absolutePath).AbsoluteUri);
#endif
    }
}

Scripts that are not in an assembly definition have no Version Defines, so MYGAME_PDFVIEWER is never defined there and the sample as printed always takes the Application.OpenURL branch, also when PDF Viewer is installed. In such a project either delete the #if, #else and #endif lines together with the Application.OpenURL line and keep only Luanrobs.Pdf.PdfViewer.OpenFile(absolutePath);, or add MYGAME_PDFVIEWER yourself under Project Settings > Player > Scripting Define Symbols (and remove it again if you remove PDF Viewer).

PDF Viewer's OpenFile takes an absolute path and must be called on the main thread. On Android the file must be readable by the app without extra permissions, which a file under Application.persistentDataPath is. PDF Viewer's own manual lists the platforms it supports and what it does elsewhere.

Without PDF Viewer the file is handed to the system. Whether the system opens a file:// address in a PDF app depends on the platform; the demo does not try it on Android or WebGL, and it was not checked on the other platforms (see Platform support). On a platform where it does not work, give the file to the user with the sharing or download mechanism of that platform, using ToBytes() or the saved path.

Platform support

PDF Maker is managed C# only. It contains no native plugin and no platform-specific setup, and the package adds no permission to a build.

Tested on

This table lists what was run for version 1.0.0. A row that says "not run yet" was not run, and nothing is claimed for it.

Platform Status What was run
Windows Editor Run Unity 6000.3.12f1 on Windows 11, Mono, Built-in Render Pipeline, Input Manager. 768 EditMode tests passed on the final code (2026-10-15): file structure, text and layout, fonts, images, culture independence under six cultures, a 500-page document, building on a worker thread, texture copies and camera captures on a graphics device. Play mode was entered three times in a row with Domain Reload disabled, and the documents built in each session were byte for byte the ones built in Edit mode; this check was last run on 2026-10-15 on Unity 6000.3.12f1, on the final code, after the fixes of the second review. On 2026-10-15, after the fixes of the second review, the 768 tests passed again on Unity 6000.3.12f1 and on Unity 6000.0.84f1, each in a new project created with that version, with the package installed from a .tgz archive.
Windows player (Mono) Run Unity 6000.3.12f1 on Windows 11, Direct3D 12, a 1280x720 window, Input Manager only. The five demo scenes made their PDFs, and a driver built an 11-page document with shapes, text, images, tables, lists, links, headers and footers, then checked that the same document gives the same bytes under five cultures and on a worker thread. The PDFs were read with pypdf and drawn with the PDF engine of Windows. The driver calls the same methods as the buttons; the buttons and the Open button were not clicked, and the Input System was not used. On 2026-10-15, after the fixes of the second review, the driver passed again in Mono players built from the two clean projects: Unity 6000.3.12f1 (Direct3D 12) and Unity 6000.0.84f1 (Direct3D 11).
Windows player (IL2CPP) Run The same demo scenes and the same driver, built with the IL2CPP scripting backend and managed stripping at High (no build errors or warnings). They passed, and the PDFs were read with pypdf and drawn with the PDF engine of Windows. Last run on 2026-10-15 on Unity 6000.3.12f1, on the final code, after the fixes of the second review.
Android (IL2CPP) Run on emulators 2026-10-15, managed stripping at High, an APK with ARM64 and x86-64 code, x86-64 emulators only. A Unity 6000.3.12f1 build (lowest API level 25, which Unity 6000.3 sets) ran the driver on Android 16 (API 36, Vulkan) and Android 7.1.1 (API 25, OpenGL ES 3). A Unity 6000.0.84f1 build from the clean project (lowest API level 23) ran it on Android 7.0 (API 24) and Android 7.1.1 (API 25), OpenGL ES 3. The driver passed on each: the five demo scenes made their PDFs, the 11-page document was built, the bytes were equal under five cultures and on a worker thread, and PdfCapture.Screenshot and RenderCamera gave pictures that are not blank. The embedded font was Roboto from the device. The PDFs were read with pypdf. After the fixes of the second review, the Unity 6000.3.12f1 build was made again and passed again on Android 16 (API 36); the other three emulator runs were not repeated. No physical device was used and the ARM64 code was not run.
WebGL not run yet -
Other platforms (macOS, Linux, iOS and the rest) not run yet -

What each part needs

Feature Needs
Building and saving documents, text, shapes, tables, fonts from bytes, images from PNG, JPEG or pixels Managed code only. Any one thread at a time; on WebGL, the main thread.
PdfImage.FromPng A working System.IO.Compression to inflate the data.
Flate compression of the file System.IO.Compression. Without it the data is stored uncompressed.
PdfImage.FromTexture on a readable texture The main thread.
PdfImage.FromTexture on a texture that is not readable The main thread and a graphics device.
PdfCapture.Screenshot The main thread, a graphics device, Play mode or a player, and the end of a frame.
PdfCapture.RenderCamera The main thread and a graphics device. Edit mode or Play mode.
Both capture methods, and PdfImage.FromTexture for a texture that is not readable Without a graphics device they throw PdfMakerException.
Both capture methods, and PdfImage.FromTexture for a texture that is not readable or with a jpegQuality above 0 A call from Update, a coroutine or a UI event. Not from physics callbacks (such as OnTriggerEnter or OnCollisionEnter), animation events, rendering callbacks (such as OnPostRender, OnRenderObject or OnWillRenderObject) or OnValidate: these methods destroy their scratch textures with Object.DestroyImmediate, which Unity refuses there, so Unity logs an error and the scratch textures are left behind.
Save(string) A writable absolute path.
PdfFontAsset and the font asset menu The Editor for the menu; the asset itself works in builds.

What was tested and what was not

This section states what was run for version 1.0.0 and what was not. Everything below ran on one machine: Unity 6000.3.12f1 (and, where stated, Unity 6000.0.84f1) on Windows 11, with the Built-in Render Pipeline, gamma colour space and the legacy Input Manager, and on Android emulators on that machine. Tools used to check the results were the NUnit test runner of Unity, pypdf, a byte-level walk through the cross-reference table of each file, and the PDF engine of Windows.

What was tested

The EditMode tests and the Editor run of the demo builders were repeated after the fixes that followed the independent review. On 2026-10-09, also after those fixes, the two Windows players were built again and the driver was run in each again: the PDFs they wrote were read with pypdf in strict mode, their first pages were drawn with the PDF engine of Windows and inspected, and the screenshots of the demo scenes were inspected again. The byte-level check of the cross-reference table was not run on those files. The release QA of 2026-10-15, also after the fixes, repeated the Domain Reload check and the byte-level check of the cross-reference table and added the clean projects, Unity 6000.0.84f1 and Android (see below). After the fixes of the second review (also 2026-10-15) the following were run again on the final code: the 768 EditMode tests in the development project and in two new clean projects (Unity 6000.3.12f1 and 6000.0.84f1, package from a .tgz archive), the sample scene check and a Mono Windows player with the driver in each clean project, pypdf in strict mode and the byte-level cross-reference check on all of their PDFs, the Unity 6000.3.12f1 Android build on Android 16 (API 36), and, on Unity 6000.3.12f1 in the development project, the IL2CPP Windows player with the driver (its PDFs read with pypdf in strict mode and drawn with the PDF engine of Windows) and the Domain Reload check. Not repeated after those fixes: the Android runs on API 24 and 25.

  • EditMode tests. 768 tests in the assembly Luanrobs.PdfMaker.Tests.Editor passed, none skipped, in the Mono Editor. They cover the structure of the file (header, cross-reference table, offsets, trailer), the standard font widths, text breaking and layout, tables, headers and footers, links, embedded fonts and their subsets, images from textures (readable, not readable, and through the GPU), PNG, JPEG and raw pixels, damaged input, the capture helpers, the font asset and its Editor command, determinism, building on a worker thread, a 500-page document, and the rules of the package (no mutable static state, wording, allowed addresses, path lengths). The text and number tests run under six cultures (pt-BR, de-DE, ar-SA, fa-IR, tr-TR and one with hostile settings) and compare the bytes with the invariant build.
  • Domain Reload disabled. Play mode was entered three times in a row with Domain Reload disabled. In each session five documents (hello world, an invoice, a certificate with a logo, a Unicode page with Arial, and a document with readable, not readable and JPEG-stored textures) were byte for byte the ones built in Edit mode, and the static fields of the runtime assembly held the same content.
  • Windows players. A Windows 64-bit player built with Mono and one built with IL2CPP and managed stripping at High were started in a 1280x720 window with Direct3D 12. In each, the five demo scenes made their PDFs and a driver built an 11-page document. The driver also built one document under five cultures (pt-BR, de-DE, fr-FR, ar-SA, fa-IR) and on a worker thread, and each time the bytes were equal to the build on the main thread with the invariant culture. No error, exception or warning appeared in the player log.
  • The files. The PDFs of the tests, of the Editor run of the demo and of both players were read with pypdf (page count, title, fonts, images and text), also in strict mode with warnings treated as errors, and with a byte-level check of the cross-reference table. The pages were drawn with the PDF engine of Windows and inspected as images. Shapes, dashes, clipping, opacity and rotation, the twelve standard fonts and the embedded Arial, images (PNG, JPEG, raw pixels, GPU copies and alpha) upright and not mirrored, justified, centred and right-aligned text, list indents, table borders, repeated headers, striped and wrapped cells, "Page X of Y" footers, the report with its charts, a camera render and a screenshot, the certificate and the invoice were drawn as expected. Pages 1, 250 and 500 of the 500-page file were drawn.
  • Unicode text. The sample sentence of the Unicode scene (accented Latin, Greek, Cyrillic and the euro sign), set in an embedded subset of Arial, was found exactly by pypdf in the files produced in the Editor, in the Mono player and in the IL2CPP player. Metadata with non-ASCII text (title, author, keywords) read back correctly.
  • The demo scenes. The scene builder produced the six scenes. Screenshots of the menu and of the five scenes taken by the player were inspected: cream text on navy, logo, readable text, no clipping or overlap, the status card filled after Generate and the Open button brighter after a save.
  • Builds. The Mono player and the IL2CPP player built without errors or warnings.
  • Clean projects (2026-10-15). A new, empty project was made with Unity 6000.3.12f1 and another with Unity 6000.0.84f1, each with the packages that version adds to a new project, plus uGUI 2.0.0 and the Test Framework. The package was installed into each from a .tgz archive packed from the package folder, and the Demo sample was imported as the Package Manager imports it. In both projects: the 760 EditMode tests passed, none skipped; the six sample scenes opened with no missing scripts; a Windows player (Mono) with the six scenes built with no errors or warnings, and the driver passed in it. The PDFs of the players and of the tests were read with pypdf in strict mode and checked byte by byte against their cross-reference tables. Nothing in the manifest of either project had to be removed.
  • Domain Reload disabled, again (2026-10-15). The check described above was run again in Unity 6000.3.12f1 on the code with the fixes of the first review and passed in all three sessions. It was run again on 2026-10-15 on the final code, after the fixes of the second review, and passed in all three sessions.
  • Android (2026-10-15). Android players built with IL2CPP and managed stripping at High, with ARM64 and x86-64 code, ran the driver on x86-64 emulators: a Unity 6000.3.12f1 build on Android 16 (API 36) and Android 7.1.1 (API 25), and a Unity 6000.0.84f1 build from the clean project on Android 7.0 (API 24) and Android 7.1.1 (API 25). It passed on each. The PDFs were taken off the emulators and read with pypdf in strict mode, checked byte by byte against their cross-reference tables and drawn with the PDF engine of Windows; the sample sentence of the Unicode scene was found in the files made with the Roboto font of the device. The screenshots of the demo scenes taken by the players were inspected, and so were the camera render and the screenshot in the report made on API 36 and API 24.

What was not tested

  • Platforms. WebGL, macOS, Linux, iOS, consoles and Windows 10 were not built or run. IL2CPP was run on Windows and on Android emulators only. On Android nothing ran on a physical device, the ARM64 code was not run (every emulator was x86-64), and API levels 23 and 26 to 35 were not run. The fallback to stored blocks when System.IO.Compression is missing was not exercised on a platform that lacks it.
  • Unity versions. Only Unity 6000.3.12f1 and Unity 6000.0.84f1 were run. On 6000.0.84f1 the EditMode tests, a Mono Windows player and an Android player ran; the IL2CPP Windows player and the Domain Reload check ran on 6000.3.12f1 only (last on 2026-10-15, on the final code).
  • Clean project. The package was installed from a .tgz archive into new Built-in projects only. It was not installed from the Asset Store, and was not tried with URP, HDRP, the Input System as the only input, or under Assets/.
  • Independent review. Ten independent review passes read the code and the documents for 1.0.0 and reported 8 major and about 50 minor findings. Version 1.0.0 as shipped includes the fixes for the major findings that could be fixed and tested in the Built-in pipeline, and a number of the minor ones. A second review on 2026-10-15 checked those fixes and the documents; its two must-fix minor findings (a line break after the hyphen of a negative number or a date, and the Open button of the demo on iOS) and its documentation findings are fixed in 1.0.0, and the PNG decoder no longer allocates the declared image size before the data proves valid. Still open: saving a file streams nothing (see Memory notes), RenderCamera cannot detect the two URP cases described under Screenshots and camera renders, the scratch textures cannot be destroyed from the callbacks listed under Limitations, and the minor findings on text breaking (soft hyphens, Unicode line separators) are unchanged.
  • Clicks and keys. No button was clicked and no key was pressed in a running demo: the drivers call Generate() directly. The Open button, the menu buttons that load scenes and the product page link in the menu were never used in a running player. The Input System branch of the demo was compiled but not run.
  • PDF Viewer. The code that opens a file with PDF Viewer (LUANROBS_PDFMAKER_DEMO_PDFVIEWER) was compiled but not run: PDF Viewer is not installed in the test project and no PDF Maker file was opened in it. Handing a file:// address to the system with Application.OpenURL was not exercised.
  • Other PDF viewers. The files were drawn by the PDF engine of Windows only, besides pypdf and the byte-level checks. Adobe Acrobat, Chrome, macOS Preview and Android viewers were not used. A headless Edge was tried and showed an empty page for every PDF, so it gave no result. Only pages 1, 250 and 500 of the 500-page file were drawn.
  • Fonts. In the Windows runs only Arial was embedded, and in the Android runs only the device's Roboto. Twelve Windows fonts were checked outside Unity with fontTools and FreeType. Fonts with CFF outlines, collections and WOFF files are refused on purpose, and that was tested with altered font bytes only. The font asset command was exercised through the code the menu calls, not by clicking the menu.
  • Capture and colour. PdfCapture and PdfImage.FromTexture were tested in the Built-in pipeline with gamma colour space. Linear colour space, URP, HDRP and high-DPI screens were not tried.
  • Limits. Memory use under pressure and files near 2 GB were not tried.
  • Equal output across runtimes. Equal bytes for the same document were checked within one runtime only. The Mono and IL2CPP players gave files that differ by a few bytes (see Deterministic output).

A row marked "not run yet" in Tested on was not run. Nothing is claimed for it.

Memory notes

  • A document keeps the content of all its pages in managed memory until it is saved, and keeps the finished file after the first save. ToBytes() returns a copy. Let go of the document when you are done; there is nothing to dispose. Memory use under pressure was not measured.
  • Every save goes through memory: Save(path) and Save(stream) do not stream. While the file is written, the document holds its images (their compressed data is most of a large file) and the buffer the file is written into, so plan for about twice the size of the file in managed memory during the first save, in a few large arrays, plus one more copy for each ToBytes() call. After the save the document lets go of its fonts and images and keeps only the file. For a file of hundreds of megabytes on a phone or in a WebGL heap that can fail with OutOfMemoryException, and a failed first save is final. Prefer JPEG storage and smaller pictures, or split the output into several documents. Use Save(path) rather than ToBytes() plus File.WriteAllBytes, which needs one copy more.
  • The finished file is built in memory as one byte array, so a file cannot be larger than the .NET array limit of about 2 GB. Files near that size were not tried. The largest document in the tests has 500 pages, with a heading and a short paragraph on each page and a "Page X of 500" footer.
  • A PdfImage holds its compressed pixel data, or the JPEG bytes, in managed memory. The source texture or array is not referenced afterwards. One image used on many pages is stored once per document.
  • Lossless images of photos, screenshots and renders are large. Pass a jpegQuality for those (the capture helpers use 90 by default).
  • An embedded font keeps a copy of the font file in memory for as long as the PdfFont lives. A PdfFontAsset holds the file as its data.
  • For a long document, build it in parts across frames, or on a worker thread where threads exist, so the game keeps running.

Limitations

These are known and stated up front.

  • PDF Maker only writes PDF files. It does not read, edit or merge existing PDF files, and it does not show them.
  • No forms, no digital signatures, no encryption, no PDF/A. The file has no tag structure, so it is not a tagged (accessible) PDF.
  • No complex scripts. Arabic and Indic shaping are not done, and right-to-left and vertical text are not supported. Each character is drawn with its own glyph, left to right.
  • No kerning and no ligatures.
  • No mixed fonts or styles inside one paragraph. A paragraph has one style; to set a word in bold, draw the pieces yourself on the canvas.
  • No HTML or rich-text import.
  • Fonts: TrueType outlines only. OpenType fonts with CFF outlines, font collections (.ttc) and WOFF files are rejected with PdfMakerException. So are fonts whose license flags forbid embedding. A font flagged "No subsetting" is embedded whole.
  • A font subset does not carry the name table of the font. In the PDF engine of Windows a subset of Courier New was drawn slightly lighter than the whole font. Set SubsetFonts to false to embed whole fonts. See Subsetting.
  • The Symbol and ZapfDingbats standard fonts are not offered.
  • Standard fonts cover Windows-1252 Latin text only. Other characters are drawn as ?. They are not embedded, and some viewers do not draw fonts that are not embedded. Embed a font when the file must look the same everywhere.
  • You are responsible for the license of every font you embed.
  • Images: interlaced PNG files are not supported. The EXIF orientation of a JPEG file is not applied. The largest side is 16384 pixels.
  • Tables: no cells that span columns or rows, no images in cells, no nested tables. A table has at most 64 columns. Rows are never split between pages.
  • No internal links, no bookmarks or outlines. Links open web addresses. There is no clickable table of contents.
  • No gradients or patterns, and no even-odd fill. Fills use the non-zero winding rule. Colours are RGB.
  • The layout is immediate. Each block is measured and drawn when you add it, and nothing is reflowed afterwards. A document is built once.
  • A heading is not tied to the block after it. It only checks that there is room for itself and two lines of body text. See Headings and paragraphs.
  • Files are limited to about 2 GB, because the file is built as one byte array. Files near that size were not tried.
  • Page numbers only in headers and footers. They are drawn when the document is saved; the flow itself does not know how many pages there will be.
  • No automatic hyphenation. A word wider than the line is split between characters.
  • Soft hyphens are not break points. A soft hyphen (U+00AD) is drawn where it stands (as a hyphen in the standard fonts), and a line never breaks at it. Remove soft hyphens from text that comes from web pages or translation tables, or use a zero width space (U+200B) where a word may break.
  • Variable fonts are drawn in their default instance. A variable TrueType font is accepted like any other, and only its default instance (usually the regular weight) is drawn; other weights or widths of the same file cannot be chosen. Use a static font file for each weight.
  • Pages are 3 to 14400 points on a side.
  • Screenshots and camera renders need a graphics device, as does PdfImage.FromTexture for a texture that is not readable. Neither works in a batchmode run started with -nographics. A camera render does not include Screen Space - Overlay canvases.
  • Not from physics, animation-event or rendering callbacks, or from OnValidate. PdfCapture.Screenshot, PdfCapture.RenderCamera, and PdfImage.FromTexture for a texture that is not readable or with a jpegQuality above 0, destroy their scratch textures at once with Object.DestroyImmediate. Unity refuses that call inside physics callbacks (such as OnTriggerEnter or OnCollisionEnter), animation events, rendering callbacks (such as OnPostRender, OnRenderObject or OnWillRenderObject) and OnValidate: it logs an error, throws nothing, and the scratch textures are left behind. Call these methods from Update, a coroutine or a UI event. This follows Unity's documented behaviour and was not reproduced for this version.
  • WebGL has no threads, and the package has no browser download code.
  • How a viewer draws the file is up to the viewer. Fonts that are not embedded, links and transparency are drawn the way each viewer does it.

API reference

Namespace: Luanrobs.PdfMaker. Assembly: Luanrobs.PdfMaker.

If your scripts live in an assembly definition, add a reference to Luanrobs.PdfMaker.

PdfDocument

public sealed partial class PdfDocument

A PDF file being built. See Documents and pages, Layout and Saving.

Member Description
PdfDocument() Creates an empty document: A4 portrait pages, 54-point margins, optimal compression.
PdfMetadata Metadata { get; } The document properties. Never null.
PdfPageSize DefaultPageSize { get; set; } Size of pages added without an explicit size. Default A4.
PdfOrientation DefaultOrientation { get; set; } Orientation of pages added without an explicit size. Default Portrait.
PdfMargins DefaultMargins { get; set; } Margins of pages added with AddPage. Default 54 points.
PdfCompression Compression { get; set; } Compression of page content and embedded font programs. Default Optimal.
bool Deterministic { get; set; } The same calls give the same bytes. Default false.
bool SubsetFonts { get; set; } Embed only the glyphs used. Default true.
Action<PdfPageContext> Header { get; set; } Called for each page when the document is saved. Default null.
Action<PdfPageContext> Footer { get; set; } The same, for the footer. Default null.
PdfStyleSheet Styles { get; } The styles used by the layout methods.
PdfPage CurrentPage { get; } The last page. Reading it adds the first page when there is none.
float CursorY { get; set; } Where the next block starts on CurrentPage.
int PageCount { get; } The number of pages added so far.
bool IsSealed { get; } True once the first save has started.
PdfPage GetPage(int index) A page by zero-based position.
PdfPage AddPage() Adds a page with the default size, orientation and margins.
PdfPage AddPage(PdfPageSize size, PdfOrientation orientation = PdfOrientation.Portrait) Adds a page of a given size and orientation.
void AddHeading(string text, int level = 1) A heading of level 1 to 3.
void AddParagraph(string text, PdfTextStyle style = null) A paragraph.
void AddLink(string text, string url, PdfTextStyle style = null) A paragraph that opens a web address.
void AddBulletList(IEnumerable<string> items, PdfTextStyle style = null) A bullet list.
void AddNumberedList(IEnumerable<string> items, PdfTextStyle style = null) A numbered list.
void AddTable(PdfTable table) A table.
void AddImage(PdfImage image, float width = 0f, PdfTextAlign alignment = PdfTextAlign.Left) An image block.
void AddSpace(float height) Empty vertical space.
void AddHorizontalLine(float thickness = 0.5f, Color? color = null) A horizontal rule.
void AddPageBreak() Starts a new page.
void BeginKeepTogether() Starts a group of blocks that stay on one page.
void EndKeepTogether() Ends the group and places its blocks.
byte[] ToBytes() Seals the document and returns the file as a new array.
void Save(Stream stream) Seals the document and writes the file to a stream.
void Save(string path) Seals the document and writes the file to a path.

PdfPage

public sealed class PdfPage

One page of a document. Created by AddPage or by the layout methods.

Member Description
PdfDocument Document { get; } The document the page belongs to.
int Index { get; } Zero-based position of the page.
float Width { get; }, float Height { get; } The page size in points, orientation applied.
PdfMargins Margins { get; set; } The margins of this page.
Rect ContentRect { get; } The area inside the margins.
bool ShowHeaderAndFooter { get; set; } Whether the header and footer callbacks are called for this page. Default true.
PdfCanvas Canvas { get; } The drawing surface of the page.
void AddLink(Rect rect, string url) Makes an area of the page open a web address.

PdfCanvas

public sealed partial class PdfCanvas

The drawing surface of one page. See The canvas.

Member Description
float Width { get; }, float Height { get; } The page size in points.
Color FillColor { get; set; }, Color StrokeColor { get; set; } The colours of fills and text, and of strokes. Alpha is opacity.
float LineWidth { get; set; } Stroke thickness in points.
PdfLineCap LineCap { get; set; }, PdfLineJoin LineJoin { get; set; } The shape of line ends and corners.
PdfFont Font { get; set; } The font of DrawText and DrawTextBox.
float FontSize { get; set; } The font size in points.
float LineSpacing { get; set; } The line height of DrawTextBox as a multiple of FontSize.
void SaveState(), void RestoreState() Remember and bring back the state.
void SetDash(float[] pattern, float phase = 0f) Dashed strokes; null or empty is solid.
void Translate(float dx, float dy) Moves the origin.
void Rotate(float degrees), void Rotate(float degrees, float pivotX, float pivotY) Rotates around the origin or a point.
void Scale(float sx, float sy) Scales; a factor must not be zero.
void MoveTo(float x, float y), void LineTo(float x, float y) Path segments.
void CurveTo(float control1X, float control1Y, float control2X, float control2Y, float x, float y) A cubic bezier curve.
void AddArc(float centerX, float centerY, float radius, float startDegrees, float sweepDegrees) A circular arc.
void ClosePath() Closes the current part of the path.
void AddRect(Rect rect), void AddRoundedRect(Rect rect, float radius) Rectangles.
void AddEllipse(Rect bounds), void AddPolygon(params Vector2[] points) An ellipse and a closed polygon.
void Fill(), void Stroke(), void FillAndStroke(), void Clip() Paint or clip with the current path, then clear it.
void DrawLine(float x1, float y1, float x2, float y2) Strokes a line.
void FillRect(Rect rect), void StrokeRect(Rect rect) Fills or strokes a rectangle.
void FillRoundedRect(Rect rect, float radius), void StrokeRoundedRect(Rect rect, float radius) Rounded rectangles.
void FillEllipse(Rect bounds), void StrokeEllipse(Rect bounds) Ellipses.
void FillCircle(float centerX, float centerY, float radius), void StrokeCircle(float centerX, float centerY, float radius) Circles.
void FillPolygon(params Vector2[] points), void StrokePolygon(params Vector2[] points) Closed polygons.
void DrawText(string text, float x, float y) One line of text; (x, y) is its top-left corner.
void DrawText(string text, float x, float y, PdfTextAlign alignment) One line of text placed relative to x.
void DrawImage(PdfImage image, Rect rect) Draws an image stretched to a rectangle.
Rect DrawImage(PdfImage image, float x, float y, float width) Draws an image at a width and returns the rectangle it covers.
float DrawTextBox(string text, Rect box, PdfTextAlign alignment = PdfTextAlign.Left, PdfVerticalAlign verticalAlignment = PdfVerticalAlign.Top) Draws wrapped text in a box and returns its height.
float MeasureTextBox(string text, float width) The height DrawTextBox would need for a width.

PdfPageContext

public sealed class PdfPageContext

What a header or footer callback receives. See Headers, footers and page numbers.

Member Description
PdfDocument Document { get; } The document being saved.
PdfPage Page { get; } The page being decorated.
PdfCanvas Canvas { get; } The canvas of the page, in its default state.
int PageNumber { get; } The number of this page, starting at 1.
int PageCount { get; } The number of pages in the document.
Rect HeaderRect { get; }, Rect FooterRect { get; }, Rect ContentRect { get; } The top margin strip, the bottom margin strip and the area inside the margins.

PdfTextStyle and PdfStyleSheet

public sealed class PdfTextStyle, public sealed class PdfStyleSheet

See Styles for the properties, defaults and the members of the style sheet.

Member Description
PdfTextStyle() The default style: Helvetica 11, black, left-aligned, line spacing 1.2, 6 points after.
PdfTextStyle(PdfFont font, float fontSize) A style with a font and a size.
PdfTextStyle Clone() An independent copy.
PdfFont Font, float FontSize, Color Color, PdfTextAlign Alignment, float LineSpacing, float SpaceBefore, float SpaceAfter, bool KeepTogether The settings of the style.
float LineHeight { get; } FontSize multiplied by LineSpacing.
PdfStyleSheet.Body, Heading1, Heading2, Heading3, TableHeader, TableCell The document styles. Each can be changed or replaced with a new PdfTextStyle; a null value throws ArgumentNullException.
PdfStyleSheet.LinkColor The colour of link text.
PdfStyleSheet.SetFont(PdfFont regular, PdfFont bold = null) Switches every style to your fonts.

PdfTable, PdfTableRow and PdfTableCell

public sealed class PdfTable, public sealed class PdfTableRow, public sealed class PdfTableCell

See Tables.

Member Description
const int PdfTable.MaxColumns The largest number of columns: 64.
PdfTable(int columnCount), PdfTable(params float[] columnWeights) Equal columns, or one column per weight.
int ColumnCount { get; }, int HeaderRowCount { get; }, int RowCount { get; } The number of columns, header rows and body rows.
float Width, float CellPadding, float MinRowHeight, float BorderWidth, float SpaceBefore, float SpaceAfter Sizes and spacing in points.
PdfTextStyle HeaderStyle, PdfTextStyle CellStyle Styles of header and body cells; null uses the document styles.
PdfTableBorders Borders, Color BorderColor Which border lines are drawn, and their colour.
Color? HeaderBackground, Color? AlternateRowBackground Backgrounds of header rows and of every second body row.
bool RepeatHeader Draw the header rows again on each further page.
void SetColumnWeights(params float[] weights) Replaces the column weights.
void SetColumnAlignment(int column, PdfTextAlign alignment) Aligns the text of a column.
PdfTableRow AddHeaderRow(params string[] cells), PdfTableRow AddRow(params string[] cells) Add a header row or a body row.
PdfTableRow GetHeaderRow(int index), PdfTableRow GetRow(int index) A row by position.
PdfTableRow.IsHeader, CellCount, Background, this[int column] Row properties and its cells.
PdfTableCell.Text, Style, Alignment, Background Cell properties. Alignment and Background are nullable.

PdfFont

public sealed class PdfFont

A font to draw and measure text with. See Fonts.

Member Description
static PdfFont Helvetica, HelveticaBold, HelveticaOblique, HelveticaBoldOblique The Helvetica standard fonts.
static PdfFont TimesRoman, TimesBold, TimesItalic, TimesBoldItalic The Times standard fonts.
static PdfFont Courier, CourierBold, CourierOblique, CourierBoldOblique The Courier standard fonts.
string Name { get; } The PostScript name.
string FamilyName { get; } The family name.
bool IsEmbedded { get; } True for a TrueType font you supplied; false for the standard fonts.
static PdfFont FromTrueType(byte[] fontData) A font from the bytes of a TrueType file. Any thread.
static PdfFont FromTrueType(TextAsset fontFile) A font from a TextAsset. Main thread only.
bool HasGlyph(int codePoint) Whether the font has a glyph for a code point.
bool CanDraw(string text) Whether the font has a glyph for every character of a text.
float MeasureWidth(string text, float fontSize) The width of a text on one line.
float MeasureWidth(string text, int startIndex, int length, float fontSize) The width of part of a text.
float GetAscent(float fontSize), float GetDescent(float fontSize) Ascent (positive) and descent (zero or negative) in points.

PdfFontAsset

public sealed class PdfFontAsset : ScriptableObject

A TrueType font stored as an asset. Create it with Assets > Create > luanrobs > PDF Maker > PDF Font Asset.

Member Description
PdfFont Font { get; } The font, created on first use and cached. Main thread only.
int DataSize { get; } The size of the stored font file in bytes; 0 for an empty asset.
string SourceFileName { get; } The name of the font file the asset was created from.

PdfImage

public sealed class PdfImage

A picture ready to be placed in a PDF. See Images and captures.

Member Description
const int MaxSide The largest width or height: 16384 pixels.
int Width { get; }, int Height { get; } The size in pixels.
bool HasAlpha { get; } True when at least one pixel is not fully opaque.
static PdfImage FromTexture(Texture2D texture, int jpegQuality = 0) An image from a texture. Main thread only.
static PdfImage FromPng(byte[] pngData) An image from PNG bytes. Any thread.
static PdfImage FromJpeg(byte[] jpegData) An image from JPEG bytes, stored unchanged. Any thread.
static PdfImage FromPixels(Color32[] pixels, int width, int height) An image from raw pixels, bottom row first. Any thread.

PdfCapture

public static class PdfCapture

Member Description
static PdfImage Screenshot(int jpegQuality = 90) The screen as shown, user interface included. Main thread, end of frame.
static PdfImage RenderCamera(Camera camera, int width, int height, int jpegQuality = 90) One camera rendered at a size you choose. Main thread.

PdfPageSize, PdfMargins, PdfUnit and PdfMetadata

Member Description
PdfPageSize.A3, A4, A5, Letter, Legal The page size presets, portrait.
PdfPageSize(float width, float height) A custom size in points, 3 to 14400 on each side.
PdfPageSize.Width, Height The size in points.
PdfPageSize.FromMillimeters(float widthMm, float heightMm) A custom size from millimetres.
PdfPageSize.Oriented(PdfOrientation orientation) The size turned to an orientation.
PdfMargins(float all), PdfMargins(float horizontal, float vertical), PdfMargins(float left, float top, float right, float bottom) Margins in points, each zero or more.
PdfMargins.Left, Top, Right, Bottom The margins.
PdfUnit.PointsPerInch, PdfUnit.PointsPerMillimeter 72, and 72 / 25.4.
PdfUnit.Mm(float), PdfUnit.Cm(float), PdfUnit.Inch(float), PdfUnit.Px(float) Convert millimetres, centimetres, inches and pixels (96 per inch) to points.
PdfMetadata.Title, Author, Subject, Keywords, Creator, Producer, CreationDate The document properties.

Enums and exception

Type Values
PdfOrientation Portrait, Landscape
PdfTextAlign Left, Center, Right, Justify
PdfVerticalAlign Top, Middle, Bottom
PdfCompression None, Fast, Optimal
PdfLineCap Butt, Round, Square
PdfLineJoin Miter, Round, Bevel
PdfTableBorders None, Horizontal, Grid
PdfMakerException Thrown when data handed to the package cannot be used. It has a message, and an inner exception in one constructor.

Troubleshooting and FAQ

InvalidOperationException when I add content or draw after saving

A document is sealed by its first ToBytes or Save. After that, setters, layout methods, canvas methods and PdfPage.AddLink throw InvalidOperationException. Build the whole document first and save last. To make a variation, build a new document.

My text shows question marks, or empty boxes

The font has no glyph for those characters. A standard font draws ? for anything outside the Windows-1252 character set, and an embedded font draws its missing-glyph shape. Check with font.CanDraw(text), and embed a TrueType font that has the characters. See Characters a font can draw.

Text is missing in one PDF viewer but fine in another

Some viewers do not draw fonts that are not embedded, and the twelve standard fonts are not embedded. Embed a TrueType font and use it for all text: call document.Styles.SetFont(font), pass the font to every PdfTextStyle you create yourself (a new style starts in Helvetica), set canvas.Font = font on each page you draw on (the canvas of every page starts in Helvetica), and set context.Canvas.Font = font at the start of your header and footer callbacks (their canvas is reset to Helvetica for every page).

PdfFont.FromTrueType throws PdfMakerException

Read the message. The font is not a TrueType font, is damaged, has CFF outlines (OpenType OTTO), is a collection (.ttc), is a WOFF file, or its license flags forbid embedding. Use a .ttf file whose license allows embedding.

PdfImage.FromTexture or PdfCapture throws PdfMakerException about a graphics device

A texture that is not readable, PdfCapture.Screenshot and PdfCapture.RenderCamera need a graphics device. They throw PdfMakerException in a batchmode run started with -nographics. Make the texture readable (Read/Write enabled in its import settings) to avoid the GPU copy.

PdfCapture.Screenshot throws, or the picture is incomplete

A screenshot can be taken in Play mode and in a player only; in Edit mode it throws PdfMakerException. Call it after yield return new WaitForEndOfFrame() in a coroutine, otherwise the picture may be incomplete. See Screenshots and camera renders.

The camera render does not show my UI

Screen Space - Overlay canvases are not part of a camera's view. Use PdfCapture.Screenshot to capture the UI, or set the canvas to Screen Space - Camera so that the camera draws it.

Check that document.Footer is set, that the page's ShowHeaderAndFooter is true, that you draw inside FooterRect or HeaderRect, and that the page margin is tall enough for what you draw. The callbacks run when the document is saved, not when you set them.

An exception in a callback leaves the save, and the document cannot be saved again: every later ToBytes or Save throws InvalidOperationException. Fix the callback and build a new document. A common cause is DrawText with a null text, such as an unset Metadata.Title.

A table row runs off the bottom of the page

Rows are never split. A row that is taller than the content area of a page, less the repeated header rows, cannot fit anywhere and is drawn at the top of a page, below the repeated header rows if there are any, past the bottom of the content area. Shorten the text, widen the columns, reduce the padding, or set RepeatHeader to false when the header rows are what take the room.

There is empty space at the bottom of a page

A heading needs room for itself and two lines of body text, otherwise it starts the next page. A paragraph whose style has KeepTogether, a keep-together group, an image and the first rows of a table also move to the next page instead of being split. The empty space is by design.

The opposite can happen too: a heading is not tied to the block after it, so when that block is a table, an image or a KeepTogether paragraph that moves to the next page, the heading stays at the bottom of the page. Put the heading and that block between BeginKeepTogether() and EndKeepTogether(), or call AddPageBreak() before the heading.

The last line of my justified paragraph is not stretched

The last line of a paragraph, a line that ends with a line break and a line with a single word stay left-aligned.

The file is large

  • Photos and screenshots stored without loss are large. Pass a jpegQuality to PdfImage.FromTexture and use the capture helpers, which default to 90.
  • Keep SubsetFonts on so that an embedded font carries only the glyphs used.
  • Keep Compression on Optimal. None writes readable content and is for debugging.
  • An image that you use on many pages is stored once; create one PdfImage and reuse it.

Two builds of the same document are not identical

Set document.Deterministic = true. Without it the creation date is the time of the save. Compare files built on the same platform, Unity version and scripting backend.

Task.Run does not work on WebGL

WebGL has no threads. Build the document on the main thread, in steps across frames if it is large. See Threading.

Can I read, edit, merge, fill in or sign a PDF?

No. PDF Maker only writes PDF files. Forms, signatures, encryption and PDF/A are not included.

Can I write Arabic, Hebrew or Hindi?

No. Arabic and Indic text needs shaping, and right-to-left text needs bidirectional layout; neither is done. Each character is drawn with its own glyph from left to right.

Does it work on iOS, WebGL, consoles?

The package is managed C# with no native code, but it was run only on Windows and on Android emulators. iOS, WebGL and consoles were not run; see Platform support.

Does the package add permissions or SDKs to my build?

No. It adds no permission, no native plugin and no SDK. It uses the Image Conversion and Screen Capture built-in modules.

Does it use third-party code?

No. The width tables of the twelve standard fonts are data derived from Adobe's Core 14 AFM files; the notice is in the Third-Party Notices.txt file in the root folder of the package. The package contains no font file.

Support

Product page: https://luanrobs.com/pdf-maker/

Manual online: https://luanrobs.com/pdf-maker/docs/

Changelog: https://luanrobs.com/pdf-maker/changelog/

Email: luanrobs@gmail.com

When reporting a problem, please include your Unity version, the platform and scripting backend, and the Console or Player log output. If the problem is specific to one document, a short script that reproduces it helps most.

I maintain and support this package myself. If it saves you time, a review on the Asset Store helps a lot. Thank you.