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.
This manual ships in the Documentation~ folder of the package in two forms with the same content: index.md and PDF Viewer Manual.pdf.
Overview
PDF Viewer turns every .pdf file in your project into a PdfAsset. You reference that asset in the Inspector, like a texture or an audio clip, and open it: from a Button's On Click () list, with the PDF Open Button component, or with one line of code.
What happens next depends on the platform:
- Android. The PDF is shown in a native full-screen viewer with zoom, a page indicator, night mode and a toolbar.
- Windows 10/11 (x64). The PDF is shown in an in-game full-screen viewer with the same options. This applies to a Standalone player and to the Editor's Play mode.
- macOS, Linux and the Editor outside Play mode. The PDF is handed to the system PDF app (the fallback).
- iOS. Not supported in this version.
The package can also render any page of a PDF into a texture, without showing the viewer, for your own UI, thumbnails or a 3D surface. That works on Android and Windows; see Rendering pages to textures.
The package has no third-party dependencies, and you don't add Gradle templates or edit the manifest. The Android library declares no permissions, and the Windows viewer needs no Canvas, EventSystem or other scene setup.
Requirements
- Unity 6000.0.84f1 or newer. Tested with Unity 6000.0.84f1 and 6000.3.12f1 only.
- Unity built-in modules: Android JNI, IMGUI, JSON Serialize and Unity Web Request. They are declared in the package manifest, so Unity enables them with the package. No other package is required.
- Android API 23 or newer for the native Android viewer. The lowest Android version an app can run on is set by Unity: API 23 with Unity 6000.0, and API 25 with Unity 6000.3, which raises the minimum on its own. With Unity 6000.3 the viewer therefore runs on API 25 and newer.
- Windows 10 or 11, 64-bit, for the in-game Windows viewer. It was tested on Windows 11 only.
- macOS, Linux and the Editor outside Play mode: a PDF app installed and associated with
.pdffiles. - iOS is not supported in this version. A native iOS viewer is planned.
- Rendering pages to textures (
PdfDocumentand PDF Page Image) is supported in Android player builds, with the same Android versions as the viewer, and on Windows 10 or 11, 64-bit, in the player and in the Editor. It is not available on macOS, Linux, iOS or WebGL, wherePdfDocument.IsSupportedisfalse. It was run on Windows 11, on Android emulators and on a Samsung Galaxy S23 (Android 16); see What was tested. - The PDF Open Button component hooks a uGUI Button and the PDF Page Image component draws into a uGUI RawImage, so each needs the
com.unity.uguipackage; PDF Page Image is only available when that package is installed. The sample scenes also use uGUI. Nothing else in the package requires uGUI. A project without that package was only checked for compiling and with the EditMode tests; see What was tested.
See What was tested for the exact Unity versions, Android versions and devices.
Installation
From the Asset Store
- Open the Package Manager: Window > Package Manager in Unity 6.0, Window > Package Management > Package Manager in Unity 6.3.
- Select My Assets and find PDF Viewer.
- Click Install.
Unity installs PDF Viewer as a package. It appears in the Project window under Packages > PDF Viewer, not under Assets/, and its files are read-only. Your own PDFs, scenes and scripts go under Assets/ as usual.
Folders of the package whose name ends in ~ are not shown in the Project window: Documentation~ (this manual), Samples~ (the demo, imported as described below) and Native~ (the C++ source of the Windows DLL). To reach them, right-click Packages > PDF Viewer in the Project window and choose Show in Explorer (Reveal in Finder on macOS).
Demo scenes
- In the Package Manager, select PDF Viewer.
- Open the Samples tab.
- 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 eight small scenes in its Scenes folder. Each one shows one way of using the package. Open 00 Menu and press Play, or open any scene directly.
| Scene | What it shows |
|---|---|
00 Menu |
Launcher with one button per scene. |
01 Button On Click |
The simplest way. Each Button's On Click () list holds a PDF asset with the function PdfAsset > Open (). No component and no script. "Open Manual" opens "Getting Started". "Open Slides" opens "Landscape Slides" in horizontal mode with the title "Slides", because that PDF has its own default options. |
02 No Code Button |
A UI Button with the PDF Open Button component and a PDF assigned, and no On Click () entry. The component adds options per button and a warning when no PDF is assigned. |
03 One Line Of Code |
ManualButton.cs has a PdfAsset field and calls manual.Open() from the button's On Click (). |
04 Viewer Options |
Toggles and a start page stepper fill a PdfViewerOptions object that is passed to Open(options). |
05 Events And Resume |
Subscribes to the four PdfViewer events and shows them in a log. The page reported by Closed is remembered, and "Continue from page N" reopens the document there. |
06 Other Sources |
PDFs that are not PdfAssets: OpenStreamingAsset, OpenUrl, Open(bytes) and OpenFile. |
07 Page To Texture |
Renders pages into textures with PdfDocument, without opening the viewer: the current page in a RawImage, one thumbnail per page, Previous and Next buttons, clickable thumbnails and a night mode toggle. PageToTextureDemo.cs uses only the public API, so it is a starting point for your own code. On a platform without page rendering the scene shows a message instead. |
Three sample PDFs are included: "Getting Started" (4 pages), "Long Document" (32 pages) and "Landscape Slides" (6 pages of mixed sizes, with its own default options: horizontal paging and the title "Slides"). Their fonts are embedded in the files.
Things to know:
- The sample scenes use uGUI with the built-in font, so the sample needs the uGUI package (
com.unity.ugui). In a project without that package the sample scripts are not compiled: the project keeps compiling, and the scenes show missing scripts until the package is installed. They do not need TextMeshPro, and the sample contains no font files. The package itself does not need uGUI. - The sample uses the luanrobs palette: cream text and outlines on navy in the scenes, cream paper and navy ink in the sample PDFs. The colors of the scenes are stored in the scenes themselves; select a Button or an Image to change them.
00 Menuhas a smallluanrobs.com/pdf-viewerline in its footer. It opens the product page, and only when it is clicked. To remove it, delete theSite Linkobject of that scene.- The EventSystem is created at runtime with the input module that matches your project (Input System package or legacy Input Manager).
- The menu loads the other scenes by name. To run it in a build, add all eight scenes to the Scene List in File > Build Profiles, with
00 Menufirst. The same rule applies in Play mode. - The line at the bottom of every scene tells you what happens on the current platform.
- The StreamingAssets button in scene 06 needs one sample PDF copied to
Assets/StreamingAssets/PdfViewerDemo/, because a sample cannot install files into StreamingAssets. The README inside the sample explains how. Until the file is there, the button explains what is missing. - The URL example in scene 06 has no address. Type one in the field, or copy a link to a PDF and press Paste.
Quick start
Drop a .pdf file anywhere under Assets/. Unity imports it as a PdfAsset. Then open it in one of three ways, from the simplest to the most flexible.
Way 1: a Button's On Click (), with no component and no script
PdfAsset.Open() is public, takes no arguments and returns nothing, so the asset itself can be the target of a UnityEvent.
- Select a uGUI Button and press + under On Click ().
- Drag the PDF from the Project window into the object slot of the new entry.
- Open the function list and pick PdfAsset > Open ().
The same works with any other UnityEvent: a Toggle, a Timeline Signal Receiver, your own UnityEvent fields. An Animation Event cannot target an asset; give it a small script method that calls Open(). The PDF opens with its own default options if it has any (see Default options per PDF), otherwise with the built-in defaults.
Way 2: the PDF Open Button component
Add the PDF Open Button component to a Button and assign the PDF. Compared with way 1 it adds viewer options per button and a warning when no PDF is assigned. See PDF Open Button (no code).
Way 3: one line of code
Add a PdfAsset field to a script, assign the file in the Inspector and call Open().
using Luanrobs.Pdf;
using UnityEngine;
public class ManualButton : MonoBehaviour
{
[SerializeField] private PdfAsset manual;
public void ShowManual()
{
manual.Open();
}
}
Use one way per Button. If a Button opens the PDF twice, for example through On Click () and through a PDF Open Button on the same GameObject, the second call is rejected with PdfViewer.Error on Android and Windows.
On Windows, press Play and try it: the viewer opens inside the Game view. Build to an Android device to see the native Android viewer. Outside Play mode, and on macOS and Linux, the same call opens the PDF in your system PDF app.
The PdfAsset
A PdfAsset is a ScriptableObject created by the importer for each .pdf file. It holds the raw bytes of the file and the page count detected at import time.
The importer handles every .pdf file in the project, including documentation PDFs that come with other assets. Each one becomes a PdfAsset. A PdfAsset is included in a build only when a scene, a prefab or another asset references it, so those files do not add to your build. To choose the importer per file instead, add the scripting define LUANROBS_PDF_IMPORTER_OPT_IN; see the first entry of Troubleshooting and FAQ.
Select a PDF in the Project window to see its details in the Inspector: file size, page count, an Open PDF button and the import settings with the PDF's default viewer options (see Default options per PDF). In the Windows Editor the Inspector also shows a preview of the pages at the bottom, with previous and next buttons.
PdfAsset.Open() can be called from code or picked directly in a UnityEvent such as a Button's On Click () list.
The importer reads the page count without a full PDF parser. This works for most files, including those that use compressed object streams. For encrypted files, or files with unusual compression settings, the page count is shown as Unknown and PdfAsset.PageCount returns 0. The viewer still opens files it can read, and PdfViewer.Opened reports the real page count on Android and Windows.
using Luanrobs.Pdf;
using UnityEngine;
public class PdfInfo : MonoBehaviour
{
[SerializeField] private PdfAsset document;
private void Start()
{
string pages = document.PageCount > 0 ? document.PageCount.ToString() : "unknown";
Debug.Log($"{document.name}: {pages} pages, {document.SizeInBytes} bytes.");
}
}
PDF Open Button (no code)
PdfOpenButton is a component for opening a PDF without writing a script. The plain On Click () entry described in the Quick start is simpler; use the component when you want:
- viewer options that belong to one button, for example the same PDF opened in night mode from one button and in normal colors from another,
- a warning in the Console when no PDF is assigned.
- Select a GameObject that has a uGUI Button.
- Click Add Component > luanrobs > PDF Open Button.
- Assign a
PdfAssetto the Pdf field.
The component hooks the Button on the same GameObject. A click opens the PDF. Leave the Button's own On Click () list without an entry for the PDF.
| Inspector field | Property in code | Type | Purpose |
|---|---|---|---|
Pdf |
PdfAsset |
The PDF to open. | |
| Override Options | OverrideOptions |
bool |
When on, the button's Options are used. When off, the PDF's own default options apply, or the built-in defaults if it has none. |
| Options | Options |
PdfViewerOptions |
Viewer options used when OverrideOptions is on. |
Which options the button uses, in order:
- The button's Options, when Override Options is on. They replace the PDF's own defaults completely.
- Otherwise the PDF's own default options, when it has any.
- Otherwise the built-in defaults.
An empty title is filled with the asset name in every case.
The component also has a public Open() method. If the GameObject has no Button, wire PdfOpenButton.Open to any UnityEvent in the Inspector, for example a Toggle's On Value Changed or a Timeline signal. Do not also wire Open to the On Click of the hooked Button, or the PDF is opened twice (on Android and Windows the second call raises PdfViewer.Error).
If no PDF is assigned, Open() logs one warning and does nothing.
You can also call it from code:
using Luanrobs.Pdf;
using UnityEngine;
public class OpenOnStart : MonoBehaviour
{
[SerializeField] private PdfOpenButton openButton;
private void Start()
{
openButton.Open();
}
}
Viewer options
PdfViewerOptions holds the settings for one viewer session. Every field has a default; new PdfViewerOptions() gives the built-in defaults.
Options can be passed in the call, stored on a PDF Open Button, or stored on the PDF itself. See Default options per PDF for the last one and for which source wins.
| Field | Type | Default | Description |
|---|---|---|---|
title |
string |
"" |
Text shown in the toolbar. Empty uses the asset or file name. |
startPage |
int |
0 |
Zero-based index of the page shown when the viewer opens. Out-of-range values are clamped. |
scrollDirection |
PdfScrollDirection |
Vertical |
Vertical scrolls continuously. Horizontal shows one page at a time. |
nightMode |
bool |
false |
Inverts all page colors, including images and photos, for reading in the dark. |
showToolbar |
bool |
true |
Shows the top bar with the close button and title. |
showPageIndicator |
bool |
true |
Shows a permanent "page / count" badge at the bottom of the viewer. |
enableZoom |
bool |
true |
Allows zoom: pinch and double-tap on Android; Ctrl + wheel, double-click, + / - and pinch on Windows. |
maxZoom |
float |
5 |
Maximum zoom factor relative to the fitted page. Clamped to 1-10. A value of 1 or less disables zoom. |
Options apply to the Android and Windows viewers, with the same meaning on both. The system PDF app used by the fallback ignores them.
Notes that apply to both viewers:
- Start page. A negative
startPagebecomes0. A value past the end opens the last page. - Zoom 1. In
Verticalmode zoom 1 fits the page to the width. InHorizontalmode zoom 1 fits the whole page on screen. On Windows the page column inVerticalmode stops growing on very wide windows; see Windows viewer. - Rotation and resizing. Zoom resets when the device rotates (Android) or the window size changes (Windows). The position in the document is kept. On Android the current page is then the one that takes up the screen after the rotation, so
PageChangedcan fire once when the device rotates. - Horizontal mode while zoomed. A zoomed page pans within itself. Zoom out to move to another page.
- Options are copied. The viewer uses a copy of the object you pass, so changing it later does not affect an open viewer.
- Hidden toolbar. With
showToolbar = falsethe user closes the viewer with the back button on Android. On Windows a small round close button stays in the top-left corner, and Esc also closes.
Options in code
using Luanrobs.Pdf;
using UnityEngine;
public class ComicReader : MonoBehaviour
{
[SerializeField] private PdfAsset comic;
public void Read()
{
var options = new PdfViewerOptions
{
title = "Issue 1",
scrollDirection = PdfScrollDirection.Horizontal,
showPageIndicator = true,
maxZoom = 8f
};
comic.Open(options);
}
}
Options in the Inspector
PdfViewerOptions is serializable. Expose it as a field and edit it in the Inspector.
using Luanrobs.Pdf;
using UnityEngine;
public class Bookshelf : MonoBehaviour
{
[SerializeField] private PdfAsset book;
[SerializeField] private PdfViewerOptions options = new PdfViewerOptions();
public void OpenBook()
{
book.Open(options);
}
}
Reusing options
Use Clone() to derive a variation without changing the original.
using Luanrobs.Pdf;
using UnityEngine;
public class ResumeReading : MonoBehaviour
{
[SerializeField] private PdfAsset book;
[SerializeField] private PdfViewerOptions baseOptions = new PdfViewerOptions();
private int lastPage;
private void OnEnable()
{
PdfViewer.Closed += OnClosed;
}
private void OnDisable()
{
PdfViewer.Closed -= OnClosed;
}
public void Continue()
{
PdfViewerOptions options = baseOptions.Clone();
options.startPage = lastPage;
book.Open(options);
}
private void OnClosed(int lastPageIndex)
{
lastPage = lastPageIndex;
}
}
Default options per PDF
Each PDF can carry its own default viewer options. They are set once in the Inspector and are used every time that PDF is opened without explicit options, whichever way it is opened: On Click (), a PDF Open Button with Override Options off, or asset.Open() in code.
Setting them
- Select the
.pdffile in the Project window. - In the Inspector, tick Override Default Options.
- Set the fields that appear. They are the fields of
PdfViewerOptions: title, start page, scroll direction, night mode and so on. - Press Apply.
Things to know:
- Apply is required. These are import settings. Nothing changes until you press Apply; Revert discards the edits. Applying reimports the PDF.
- They travel with the asset. The settings are stored in the PDF's
.metafile and baked into thePdfAssetat import, so they are under version control with the file and they work in builds. Nothing is read from the Editor at run time. - Several PDFs at once. Select several PDFs to edit the options of all of them together.
- Open PDF uses the applied settings. The Open PDF button in the Inspector opens the asset as it was last imported, so press Apply first to try a change.
- Unticking the box makes the PDF use the built-in defaults again. The field values are kept in case you tick it again.
Which options are used
When a PdfAsset is opened, the first source in this table that exists is used.
| Order | Source | Used when |
|---|---|---|
| 1 | Options passed in the call | asset.Open(options) or PdfViewer.Open(asset, options) with options that are not null; a PDF Open Button with Override Options on. |
| 2 | The PDF's own default options | Override Default Options is on for that PDF and no options were passed (asset.Open(), On Click (), options is null, PDF Open Button with Override Options off). |
| 3 | The built-in defaults | Neither of the above. Same as new PdfViewerOptions(). |
The sources are not merged field by field. Explicit options replace the PDF's own defaults completely: if the PDF is set to night mode and you pass new PdfViewerOptions { startPage = 4 }, the viewer opens on page 5 in normal colors.
An empty title is filled with the asset name whichever source is used.
Per-PDF options apply to PdfAssets only. OpenFile, OpenStreamingAsset, OpenUrl and Open(bytes) use the options passed in the call, or the built-in defaults.
On each platform
The options are part of the asset, so they are available on every platform. The Android and Windows viewers honor them. The fallback (macOS, Linux, the Editor outside Play mode) hands the file to the system PDF app, which ignores viewer options, the title included; only the start page comes back, as the argument of Closed.
Reading them from code
| Member | Description |
|---|---|
bool HasDefaultOptions |
true when Override Default Options is on for this PDF. |
PdfViewerOptions DefaultOptions |
A copy of the PDF's default options, or null when it has none. Every call returns a new copy, so changing it does not change the asset. |
Because explicit options replace the PDF's defaults, start from DefaultOptions when you want the PDF's own settings with one change:
using Luanrobs.Pdf;
using UnityEngine;
public class OpenAtChapter : MonoBehaviour
{
[SerializeField] private PdfAsset manual;
public void OpenChapterTwo()
{
PdfViewerOptions options = manual.DefaultOptions ?? new PdfViewerOptions();
options.startPage = 4;
manual.Open(options);
}
}
Events
PdfViewer exposes four static events. All of them are raised on the Unity main thread, so handlers can touch Unity objects directly.
| Event | Arguments | Raised when |
|---|---|---|
Opened |
int pageCount |
The document was opened. |
PageChanged |
int pageIndex, int pageCount |
The current page changed. pageIndex is zero-based. |
Closed |
int lastPageIndex |
The viewer was closed. lastPageIndex is zero-based. |
Error |
string message |
A document could not be opened or shown, or an open request was rejected. The message is short English text. |
using Luanrobs.Pdf;
using UnityEngine;
public class PdfEventLogger : MonoBehaviour
{
private void OnEnable()
{
PdfViewer.Opened += OnOpened;
PdfViewer.PageChanged += OnPageChanged;
PdfViewer.Closed += OnClosed;
PdfViewer.Error += OnError;
}
private void OnDisable()
{
PdfViewer.Opened -= OnOpened;
PdfViewer.PageChanged -= OnPageChanged;
PdfViewer.Closed -= OnClosed;
PdfViewer.Error -= OnError;
}
private void OnOpened(int pageCount)
{
Debug.Log($"PDF opened with {pageCount} pages.");
}
private void OnPageChanged(int pageIndex, int pageCount)
{
Debug.Log($"Page {pageIndex + 1} of {pageCount}.");
}
private void OnClosed(int lastPageIndex)
{
Debug.Log($"PDF closed on page {lastPageIndex + 1}.");
}
private void OnError(string message)
{
Debug.LogWarning($"PDF error: {message}");
}
}
The events are static. Always unsubscribe (for example in OnDisable) so destroyed objects are not kept alive by a subscription.
Subscribe in Awake, OnEnable, Start or later. All subscribers are cleared when the player starts, every time Play mode starts and when the Editor returns to Edit mode, so the package works with domain reload disabled. A subscription made earlier than that, for example from a SubsystemRegistration initializer, is lost. Editor tools must subscribe again after a Play mode change.
Each subscriber is invoked on its own. If one handler throws, the exception is logged and the other handlers still run.
Event behavior per platform
The order of events is the same on Android and Windows. Opened fires once the document is loaded. It is followed right away by one PageChanged for the start page, and then by PageChanged every time the current page changes. Each accepted open ends with exactly one Closed or one Error. Closed can arrive without Opened if the viewer is closed while the document is still loading. If the viewer fails after it opened (for example it runs out of memory), Error fires and Closed does not.
What differs is when the events reach your code:
- Android. Unity is paused while the viewer is on screen. The events are queued and arrive together, in order, when the player returns to the game.
Closedfires when the user presses back or taps the toolbar close button. Pages that go by while the document scrolls are reported one by one, in order, also when the screen stalls for a moment during a fast fling, so a fling over several pages reports each page number. Rotating the device does not fireClosed; it fires at most onePageChanged, for the page that then takes up the screen, and none when that is still the same page. When Android recreates the viewer while it is open, for example because the font size or the display size was changed in the system settings, the current page is not reported again. This page reporting was checked on Android emulators, with a synthetic stall for the fling; see What was tested. TreatPageChangedas "the current page is N", not as a counter: one repeated report of the same page was seen once in testing, and the cause is not known. Pressing HOME and then starting the game again from its launcher icon closes the viewer and firesClosedwith the page that was on screen; see How it works on Android. - Windows. Unity keeps running under the viewer. The events arrive live:
Openedon the viewer's first frame after the open call,PageChangedat the moment the page changes,Closedwhen the user presses Esc or clicks the toolbar close button, or when your code callsPdfViewer.Close(). Resizing the window does not fireClosed. Loading another scene does not close the viewer. - macOS, Linux and the Editor outside Play mode (fallback). The system PDF app cannot report back.
Openedfires with the asset's page count (or0if it is not known), followed byClosedwith the start page. Both fire before the open call returns.PageChangeddoes not fire.
On Windows, Closed is also raised when the application quits or Play mode ends while the viewer is open, so a handler can still save the last page. On Android, do not count on it if the app is killed while the viewer is on screen.
One viewer at a time
Only one viewer can be open at a time. On Android and Windows, calling any open method while PdfViewer.IsOpen is true leaves the current viewer untouched and raises Error. Wait for Closed before opening another document. This also covers a double tap on a button: the second call is rejected. Opening another document from inside a Closed handler is fine.
Events belong to one viewer session. Events from a previous session are dropped rather than delivered late, so a handler never receives a Closed that belongs to a document opened earlier.
See also Events and Unity pausing while the viewer is open for Android, and Your game keeps running under the viewer for Windows.
Opening PDFs from other sources
A PdfAsset is the simplest path. PdfViewer can also open PDFs that are not imported assets. Every method takes an optional PdfViewerOptions as the last argument; without it the built-in defaults are used.
From a file path
Pass an absolute path to a file your app can read, for example under Application.persistentDataPath. A relative path throws ArgumentException. content:// URIs are not supported. The file is opened in place. On Windows the file stays open while the viewer shows it, so do not replace or rewrite it until the viewer is closed.
using System.IO;
using Luanrobs.Pdf;
using UnityEngine;
public class OpenSavedReport : MonoBehaviour
{
public void Open()
{
string path = Path.Combine(Application.persistentDataPath, "report.pdf");
PdfViewer.OpenFile(path);
}
}
From StreamingAssets
Pass the path relative to the Assets/StreamingAssets folder.
using Luanrobs.Pdf;
using UnityEngine;
public class OpenCatalog : MonoBehaviour
{
public void Open()
{
// File located at Assets/StreamingAssets/Docs/catalog.pdf
PdfViewer.OpenStreamingAsset("Docs/catalog.pdf");
}
}
On Android, StreamingAssets files live inside the APK or AAB. The viewer copies the file to the app cache on a background thread before opening it. This is the recommended path for very large PDFs. See Memory notes.
The legacy Split Application Binary (OBB) layout is not supported: with it, StreamingAssets are stored outside the APK and OpenStreamingAsset reports that the file was not found.
If the viewer screen cannot be shown within about 10 seconds, for example because the app was sent to the background during the copy, PdfViewer.Error is raised with "The PDF viewer could not be started."
On Windows, macOS and Linux, StreamingAssets is a plain folder and the file is opened directly from Application.streamingAssetsPath. A missing file raises PdfViewer.Error.
From a URL
The file is downloaded to the cache and then opened. The call returns right away; the viewer appears when the download finishes. If the download fails, or the downloaded file is not a PDF, PdfViewer.Error is raised. The file is downloaded again on every call.
using Luanrobs.Pdf;
using UnityEngine;
public class OpenTerms : MonoBehaviour
{
public void Open()
{
var options = new PdfViewerOptions { title = "Terms of service" };
PdfViewer.OpenUrl("https://example.com/files/terms.pdf", options);
}
}
Only one download runs at a time. Any other open call, or PdfViewer.Close(), cancels a download that is still running without raising an event. PdfViewer.IsOpen stays false during the download.
Your app needs network access for this call. Unity adds the Android INTERNET permission to the build when the project uses networking. Plain http:// URLs fail unless Allow downloads over HTTP permits them in Player Settings and, on Android, the app allows cleartext traffic. Use https:// when you can.
From raw bytes
Use this for PDFs you generate, decrypt or receive at runtime. The optional name is used for the temporary file and as the default title.
using Luanrobs.Pdf;
using UnityEngine;
public class OpenGeneratedInvoice : MonoBehaviour
{
public void Open(byte[] pdfBytes)
{
PdfViewer.Open(pdfBytes, "invoice-2026-10");
}
}
Where temporary files go
Opens that start from bytes (a PdfAsset or a byte[]) write the data to Application.temporaryCachePath/LuanrobsPdf/<name>.pdf and then open that file. URL downloads are stored in the same folder. Characters that are not valid in a file name are replaced, and a number may be added to the name if the file is in use.
Files from earlier opens are deleted when a later PDF is opened from an asset, bytes or a URL. At most the current and the previous file are kept, so the folder does not grow over time.
On Android, copies made by OpenStreamingAsset go to a LuanrobsPdf folder in the app's internal cache and are replaced on the next StreamingAssets open.
A PdfDocument (see Rendering pages to textures) keeps its own copies in a Documents sub-folder of a LuanrobsPdf folder: under Application.temporaryCachePath for a PdfAsset or bytes, and in the app's internal cache for LoadStreamingAsset on Android. There is one copy for each document, and the viewer's clean-up described above never touches it. A copy is deleted when its document is disposed, and copies that an earlier run left behind are removed when the first document of a session is loaded.
Closing the viewer
The user closes the viewer with the toolbar close button, with the back button on Android, or with Esc on Windows. If you hide the toolbar with showToolbar = false, the back button still works on Android, and on Windows a small corner close button remains.
What PdfViewer.Close() can do depends on the platform.
Windows. Unity keeps running under the viewer, so PdfViewer.Close() closes a visible viewer at any time. Closed may be raised inside the call or shortly after it; do not rely on either.
using Luanrobs.Pdf;
using UnityEngine;
public class SessionGuard : MonoBehaviour
{
// Call this from your own code, for example when a match is about to start.
public void CloseDocument()
{
if (PdfViewer.IsOpen)
{
PdfViewer.Close();
}
}
}
Android. Unity is paused while the viewer is on screen, so game code cannot run and cannot close a visible viewer. There, PdfViewer.Close() only closes a viewer that is still starting, for example during a StreamingAssets copy. Closed is then raised shortly after the call.
Every platform. PdfViewer.Close() cancels an OpenUrl download that is still running, without raising an event:
using Luanrobs.Pdf;
using UnityEngine;
public class TermsDownload : MonoBehaviour
{
[SerializeField] private GameObject loadingPanel;
private void OnEnable()
{
PdfViewer.Opened += OnFinished;
PdfViewer.Closed += OnFinished;
PdfViewer.Error += OnFailed;
}
private void OnDisable()
{
PdfViewer.Opened -= OnFinished;
PdfViewer.Closed -= OnFinished;
PdfViewer.Error -= OnFailed;
}
public void OpenTerms()
{
loadingPanel.SetActive(true);
PdfViewer.OpenUrl("https://example.com/files/terms.pdf");
}
// Wire this to a Cancel button on the loading panel.
public void Cancel()
{
PdfViewer.Close();
loadingPanel.SetActive(false);
}
private void OnFinished(int value)
{
loadingPanel.SetActive(false);
}
private void OnFailed(string message)
{
loadingPanel.SetActive(false);
}
}
When the fallback is used the PDF is shown by another app, so Close() has nothing to close there. It still cancels a pending download.
Error handling
There are two kinds of failure.
Invalid arguments throw. Passing null or an empty value throws ArgumentNullException or ArgumentException. This covers a null PdfAsset, a null or empty byte array, and a null or empty path or URL. A relative file path or a relative URL also throws ArgumentException. Calling PdfViewer from a thread other than the Unity main thread throws InvalidOperationException. These are programming errors and are reported at the call site.
Everything else does not throw. It raises PdfViewer.Error with a readable message and logs one Debug.LogError. This covers:
- a missing file,
- a
PdfAssetthat contains no data (reimport the file), - a failed download, or a downloaded file that is not a PDF,
- a corrupt or unsupported PDF,
- a password-protected PDF (on Windows this includes every PDF encrypted with AES-256),
- running out of memory while opening or showing the document,
- an open call made while a viewer is already open on Android or Windows,
- an Android viewer screen that could not be shown within about 10 seconds ("The PDF viewer could not be started."), for example because the app was sent to the background during a StreamingAssets copy.
When a viewer reports an error it also closes itself, so your app is back in front.
A missing or unusable Windows renderer is not an error: the PDF opens in the system PDF app instead. See Windows viewer.
using Luanrobs.Pdf;
using TMPro;
using UnityEngine;
public class PdfErrorLabel : MonoBehaviour
{
[SerializeField] private TMP_Text label;
private void OnEnable()
{
PdfViewer.Error += ShowError;
}
private void OnDisable()
{
PdfViewer.Error -= ShowError;
}
private void ShowError(string message)
{
label.text = "Could not open the document: " + message;
}
}
The sample above uses TextMeshPro for the label, which needs the com.unity.ugui package. Any UI works.
PdfDocument follows the same two rules, but reports through Error properties instead of the PdfViewer.Error event. See Page rendering errors.
Rendering pages to textures
The viewer shows a PDF on the whole screen. PdfDocument covers the other cases: a page inside your own UI, thumbnails of every page, a page on a 3D surface such as a book, a poster or a screen in the game world. It opens a PDF without showing the viewer, tells you how many pages it has and how large they are, and renders any page into a Texture2D in the background. It works on Android and Windows. It was run on Windows 11, on Android emulators and on a Samsung Galaxy S23 (Android 16); see What was tested. For one page in a RawImage without writing code, see PDF Page Image (no code).
When to use it
- Use the viewer when the player should read the document. It brings scrolling, zoom, a page indicator and a toolbar, and takes a few options.
- Use
PdfDocumentwhen a page should be part of your own scene or UI, at a size you choose: a document panel, a grid of thumbnails, a poster, an in-world book. - Use PDF Page Image when one page in a RawImage is all you need and you want no code.
- They work together: show thumbnails with
PdfDocumentand open the viewer on the page the player picks. See Page rendering together with the viewer.
Check PdfDocument.IsSupported before loading when your game also runs on a platform without page rendering. It is true in an Android player, and on Windows (player and Editor) when the PDF engine of Windows can be loaded. It is false everywhere else, and it never throws.
Loading a document
There is one Load method for each source, the same sources the viewer opens:
| Method | Source | Notes |
|---|---|---|
Load(PdfAsset asset, onLoaded) |
A PDF imported into the project. | The bytes are written to a temporary copy that the document reads and deletes when it is disposed. Name is the asset name. |
Load(byte[] pdfBytes, string name, onLoaded) |
A PDF in memory, for example one that was downloaded or generated at run time. | The bytes are written to a temporary copy before the call returns, and the array is not kept. Name is name, or "Document" when it is null or empty. |
LoadFile(string absolutePath, onLoaded) |
A file on the device. | Read in place, never modified or deleted. Leave it where it is until the document is disposed. On Android it must be readable without extra permissions, for example under Application.persistentDataPath; content:// URIs are not supported. Name is the file name without .pdf. |
LoadStreamingAsset(string relativePath, onLoaded) |
A file in Assets/StreamingAssets, with the path relative to that folder. |
On Android the file lives inside the APK or AAB, so it is copied to the app cache on a background thread first, and the copy is deleted when the document is disposed. The legacy Split Application Binary (OBB) layout is not supported. On other platforms the file is read directly. Name is the file name without .pdf. |
onLoaded is optional. Where temporary files go says where the copies are kept.
using System.Collections.Generic;
using System.IO;
using Luanrobs.Pdf;
using UnityEngine;
public class LoadSources : MonoBehaviour
{
[SerializeField] private PdfAsset manual;
private readonly List<PdfDocument> documents = new List<PdfDocument>();
private void Start()
{
if (!PdfDocument.IsSupported)
{
return;
}
documents.Add(PdfDocument.Load(manual));
documents.Add(PdfDocument.Load(manual.Bytes, "copy"));
documents.Add(PdfDocument.LoadFile(Path.Combine(Application.persistentDataPath, "report.pdf")));
documents.Add(PdfDocument.LoadStreamingAsset("Docs/catalog.pdf"));
}
private void OnDestroy()
{
foreach (PdfDocument document in documents)
{
document.Dispose();
}
}
}
All four methods return at once and never return null. The document they return is still loading. IsLoading is true from the call until loading has ended. Then IsReady is true when the PDF was opened, or Error holds a short message when it was not. After Dispose(), IsDisposed is true. There are three ways to find out:
- Pass
onLoaded. It is invoked once, on the main thread, afterLoadhas returned, from the package's update: later in the same frame or in a later frame, never inside the call. This holds for success and for failure. It is not invoked when the document is disposed first. - In a coroutine,
yield return document;continues when loading has ended. CheckIsReadynext. - Do not wait.
RenderPagecan be called while the document is still loading; the request waits and starts when the document is ready.
using Luanrobs.Pdf;
using UnityEngine;
public class DocumentStatus : MonoBehaviour
{
[SerializeField] private PdfAsset manual;
private PdfDocument document;
private void Start()
{
document = PdfDocument.Load(manual, OnLoaded);
}
private void OnLoaded(PdfDocument loaded)
{
if (!loaded.IsReady)
{
// loaded.Error says why. The package has already logged it.
return;
}
Debug.Log(loaded.Name + " has " + loaded.PageCount + " pages.");
}
private void OnDestroy()
{
document.Dispose();
}
}
Null and malformed arguments throw at once; see Page rendering errors.
Page count and page size
PageCount is the number of pages, and 0 until IsReady is true.
GetPageSize(pageIndex) returns the size of a page in PDF points (1/72 inch), with the rotation stored in the page applied. US Letter is 612 x 792. It returns Vector2.zero when there is no such page, which includes every index while the document is not ready. Android reports whole points.
GetRenderSize(pageIndex, maxWidth, maxHeight) returns the size in pixels of the texture that RenderPage produces for the same page and box, without rendering anything. Use it to lay out a placeholder before the texture arrives. It returns Vector2Int.zero when there is no such page.
Rendering a page
RenderPage(pageIndex, maxWidth, maxHeight, onCompleted) renders one page into a new texture and returns a PdfPageRequest at once. pageIndex is zero-based. The box maxWidth x maxHeight is in pixels, at least 1 in each direction; a larger value counts as PdfDocument.MaxTextureSize.
The whole page is drawn on white paper and scaled to the largest size that fits the box without changing its aspect ratio. The texture is therefore never distorted, and it is as large as the box in at least one direction. Each side is rounded to the nearest pixel. A US Letter page (612 x 792 points) in a 1024 x 1024 box gives a 791 x 1024 texture, and in a 256 x 256 box a 198 x 256 texture. GetRenderSize returns that size in advance, and the texture has exactly that size.
A request ends in exactly one of three ways, and IsDone is true in all of them:
- Success.
Textureis set andErrorisnull. - Failure.
TextureisnullandErrorsays why. - Cancelled, by
Cancel()or by disposing the document.IsCancelledistrue,TextureisnullandonCompletedis not invoked.
onCompleted is optional. When you pass it, it is invoked once, on the main thread, after RenderPage has returned, from the package's update: later in the same frame or in a later frame, never inside the call. This holds for success and for failure. A callback may call any method of the package, including Dispose on its own document. An exception thrown by a callback is logged and does not stop anything else.
In a coroutine, yield return request; continues when the request is done.
using System.Collections;
using Luanrobs.Pdf;
using UnityEngine;
using UnityEngine.UI;
public class RenderFirstPage : MonoBehaviour
{
[SerializeField] private PdfAsset manual;
[SerializeField] private RawImage image;
private PdfDocument document;
private Texture2D texture;
private IEnumerator Start()
{
if (!PdfDocument.IsSupported)
{
yield break;
}
document = PdfDocument.Load(manual);
yield return document;
if (!document.IsReady)
{
yield break;
}
Vector2 points = document.GetPageSize(0);
Vector2Int pixels = document.GetRenderSize(0, 512, 512);
Debug.Log("Page 1 is " + points + " points and renders at " + pixels + " pixels.");
PdfPageRequest request = document.RenderPage(0, 512, 512);
yield return request;
if (request.Texture != null)
{
texture = request.Texture;
image.texture = texture;
}
}
private void OnDestroy()
{
if (document != null)
{
document.Dispose();
}
Destroy(texture);
}
}
The texture:
- has exactly the size
GetRenderSizereturned, with the page upright: the top of the page is at the top of a RawImage that has its default UV Rect; - is an uncompressed 32-bit color texture:
BGRA32on Windows,RGBA32on Android; - has no mipmaps, clamp wrapping and bilinear filtering;
- is not readable. Its pixels live on the graphics device only, so
GetPixelsdoes not work on it; - is named after the document and the page, for example "Manual (page 3)", with the page number counted from 1;
- belongs to you. Destroy it with
Object.Destroywhen it is no longer needed. See Lifetime and ownership.
You can request pages before the document has finished loading. Requests of one document are started in the order they were made, at most two at a time, and there are no priorities. They can finish in a different order, so use request.PageIndex to know which page arrived.
Cancel() gives up a request you no longer need, for example the thumbnail of a page that scrolled out of view. It does nothing when the request is already done. Otherwise IsDone and IsCancelled are true when it returns, no texture is delivered and onCompleted is not invoked. If the renderer finishes the page anyway, the package destroys that texture, so a cancelled request never leaves one behind.
Night mode for rendered pages
RenderPage(pageIndex, maxWidth, maxHeight, nightMode, onCompleted) renders the page with all colors inverted, images included, exactly like the nightMode option of the viewer. request.NightMode holds the value that was asked for. To switch a page that is already on screen, render it again with the other value and destroy the old texture when the new one arrives.
A page on a RawImage
Render the page for the size it has on screen, and keep the previous page visible until the next one has arrived. A RawImage stretches its texture to its rectangle, so give the RawImage the aspect ratio of the page; this sample uses an Aspect Ratio Fitter with the Aspect Mode Fit In Parent. The RawImage's parent is the area the page is fitted into, and the sample measures that area, not the RawImage.
using Luanrobs.Pdf;
using UnityEngine;
using UnityEngine.UI;
public class PageOnImage : MonoBehaviour
{
[SerializeField] private PdfAsset manual;
[SerializeField] private RawImage image;
[SerializeField] private AspectRatioFitter fitter;
private PdfDocument document;
private PdfPageRequest pending;
private Texture2D texture;
private int page;
private void Start()
{
if (!PdfDocument.IsSupported)
{
return;
}
document = PdfDocument.Load(manual);
Show(0);
}
// Wire these two to the On Click () lists of a Next and a Previous button.
public void Next()
{
if (document != null && document.IsReady && page < document.PageCount - 1)
{
Show(page + 1);
}
}
public void Previous()
{
if (document != null && page > 0)
{
Show(page - 1);
}
}
private void Show(int pageIndex)
{
page = pageIndex;
if (pending != null)
{
pending.Cancel();
}
// Ask for the size of the area the page is fitted into, in pixels.
Canvas.ForceUpdateCanvases();
RectTransform area = (RectTransform)image.rectTransform.parent;
Vector2 size = area.rect.size * image.canvas.rootCanvas.scaleFactor;
int width = Mathf.Max(1, Mathf.RoundToInt(size.x));
int height = Mathf.Max(1, Mathf.RoundToInt(size.y));
pending = document.RenderPage(pageIndex, width, height, OnPageRendered);
}
private void OnPageRendered(PdfPageRequest request)
{
pending = null;
if (request.Texture == null)
{
// request.Error says why. The package has already logged it.
return;
}
Destroy(texture);
texture = request.Texture;
image.texture = texture;
fitter.aspectRatio = (float)texture.width / texture.height;
}
private void OnDestroy()
{
if (document != null)
{
document.Dispose();
}
Destroy(texture);
}
}
The demo scene 07 Page To Texture does the same with night mode, a page label and a strip of thumbnails.
Thumbnails
Request every page at a small size, and put each texture into the slot of its page. Because requests can finish in any order, use request.PageIndex to find the slot. A Letter page in a 160 x 160 box renders at 124 x 160 pixels.
using System.Collections;
using System.Collections.Generic;
using Luanrobs.Pdf;
using UnityEngine;
using UnityEngine.UI;
public class ThumbnailStrip : MonoBehaviour
{
[SerializeField] private PdfAsset manual;
[SerializeField] private RawImage thumbnailPrefab;
[SerializeField] private Transform content;
private readonly List<Texture2D> textures = new List<Texture2D>();
private PdfDocument document;
private RawImage[] slots;
private IEnumerator Start()
{
if (!PdfDocument.IsSupported)
{
yield break;
}
document = PdfDocument.Load(manual);
yield return document;
if (!document.IsReady)
{
yield break;
}
slots = new RawImage[document.PageCount];
for (int page = 0; page < slots.Length; page++)
{
slots[page] = Instantiate(thumbnailPrefab, content);
document.RenderPage(page, 160, 160, OnThumbnail);
}
}
private void OnThumbnail(PdfPageRequest request)
{
if (request.Texture == null)
{
return;
}
textures.Add(request.Texture);
slots[request.PageIndex].texture = request.Texture;
}
private void OnDestroy()
{
if (document != null)
{
document.Dispose();
}
foreach (Texture2D texture in textures)
{
Destroy(texture);
}
}
}
Only two thumbnails of a document are rendered at a time. For a long document, request the thumbnails that are visible, and Cancel() the requests of the ones that scroll away before they start.
A page on a 3D surface
A page texture can be assigned to any material. This sample puts the first page of a PDF on a quad, a plane or any other mesh.
using Luanrobs.Pdf;
using UnityEngine;
public class PageOnPoster : MonoBehaviour
{
[SerializeField] private PdfAsset poster;
[SerializeField] private Renderer surface;
private PdfDocument document;
private Material material;
private Texture2D texture;
private void Start()
{
if (!PdfDocument.IsSupported)
{
return;
}
// Renderer.material returns a copy of the material that belongs to this object.
material = surface.material;
document = PdfDocument.Load(poster);
document.RenderPage(0, 2048, 2048, OnPageRendered);
}
private void OnPageRendered(PdfPageRequest request)
{
if (request.Texture == null)
{
return;
}
texture = request.Texture;
material.mainTexture = texture;
}
private void OnDestroy()
{
if (document != null)
{
document.Dispose();
}
Destroy(material);
Destroy(texture);
}
}
Page textures have no mipmaps. On a 3D surface that means a page seen from far away, or at a shallow angle, can shimmer or look noisy, because the graphics card cannot pick a smaller version of the texture. Render the page at about the size it covers on screen, keep the surface facing the camera when you can, and render it again at a different size if the surface moves much nearer or farther. Textures are bilinear filtered.
Lifetime and ownership
- The document is yours.
Dispose()closes the PDF, cancels the requests that are not done and deletes the temporary copy. It is safe to call more than once. Always dispose a document when you are done with it, for example inOnDestroy. Do it there rather than at the end of a coroutine, because a coroutine that is stopped never reaches its last line. - Textures are yours. Every texture a request delivers belongs to you. Destroy it with
Object.Destroywhen you replace it or stop showing it (Object.DestroyImmediatein Edit mode). It stays valid after the document is disposed, so a page on screen does not disappear when you dispose its document. - Cancelled requests deliver nothing. After
Cancel()orDispose()the request has no texture and no callback is invoked. - A document that nobody disposes keeps its PDF open, and its temporary copy on disk, until Play mode ends or the application quits. Documents that are still open when Play mode starts or ends, before a script recompile in the Editor, or when the application quits, are disposed automatically: their files are released and their copies deleted. Textures are not destroyed for you.
- Everything runs on the main thread. Call every member from the Unity main thread. A call from another thread throws
InvalidOperationException. Callbacks are invoked on the main thread.
Page rendering errors
Invalid arguments throw, at once, like the PdfViewer methods:
| Call | Throws |
|---|---|
Load(PdfAsset) |
ArgumentNullException for a null asset. |
Load(byte[]) |
ArgumentNullException for null, ArgumentException for an empty array. |
LoadFile |
ArgumentNullException for null, ArgumentException for an empty path, a blank path or a path that is not absolute. |
LoadStreamingAsset |
ArgumentNullException for null, ArgumentException for an empty path. |
RenderPage, GetRenderSize |
ArgumentOutOfRangeException when maxWidth or maxHeight is less than 1. |
Any Load method, RenderPage, Dispose, PdfPageRequest.Cancel |
InvalidOperationException when called from a thread other than the Unity main thread. |
Everything else does not throw. A page index that does not exist is not an exception either. These problems are reported through PdfDocument.Error or PdfPageRequest.Error as a short message in English, and logged once with Debug.LogError, with the prefix [PdfDocument].
A document can fail to load for these reasons:
- the platform does not support page rendering. The message is "PDF page rendering is not supported on this platform.",
- a
PdfAssetthat contains no data (reimport the file), - a file or StreamingAssets path that does not exist,
- the temporary copy could not be written,
- a corrupt, unsupported or password-protected PDF, with the same limits as the viewer. On Windows this includes every PDF encrypted with AES-256,
- running out of memory while opening the PDF.
When a document has failed, IsReady is false, PageCount is 0 and every page request made on it fails with the same message.
How a request ends, depending on the situation when its turn comes:
| Situation | Texture and Error |
onCompleted |
Logged |
|---|---|---|---|
| The page is rendered. | Texture is set, Error is null. |
Invoked. | No. |
pageIndex is below 0 or not below PageCount. |
Error says the index is out of range. |
Invoked. | Once. |
| The renderer reports a failure, for example not enough memory or a damaged page. | Error is the renderer's message. |
Invoked. | Once. |
| The document failed to load. | Error is the Error of the document. |
Invoked. | No. The load failure was logged when loading ended. |
RenderPage was called on a disposed document. |
Error says the document is disposed. |
Invoked, after RenderPage has returned. |
Once. |
Cancel() or Dispose() came first. |
IsCancelled is true, Texture is null. |
Not invoked. | No. |
Memory and limits of page rendering
- At most 4096 pixels per side.
PdfDocument.MaxTextureSizeis 4096, or the largest texture the graphics device supports when that is smaller. A box larger than that counts asMaxTextureSize. - Ask for the size you show. A texture of W x H pixels uses W x H x 4 bytes of graphics memory, with no mipmaps. 1024 x 1024 is 4 MB, 2048 x 2048 is 16 MB, and the 4096 x 4096 maximum is 64 MB. Copying a finished page into its texture happens on the main thread and takes longer the more pixels it has, so a box larger than the area on screen only costs time and memory.
- Two requests of a document at a time. The others wait in the order they were made. There are no priorities and no way to move a request ahead, so cancel the requests you no longer need. This also means a document never holds more than two finished pages that are waiting to be copied into textures, however many you queue.
- The limits count per document. Two requests at a time, and the few textures created per frame, are limits of one document; they are not shared between documents. Ten documents can render twenty pages at once, each with a pixel buffer of its own, and their textures can be created in the same frame. Every PDF Page Image component opens a document of its own, so a screen with many of them at a large Resolution renders them all at once: twelve components at 4096 can need twelve 64 MB buffers and twelve 64 MB textures at the same moment. Use a smaller size there, or stagger the work: enable the components, or make the requests, a few at a time.
- Loading an asset or bytes writes the PDF to disk on the main thread, inside the
Loadcall. For very large PDFs useLoadStreamingAssetorLoadFile: the file is then not loaded into managed memory first. See Memory notes. - Many documents are possible. Each one holds its PDF file open, and a temporary copy when it was loaded from an asset or from bytes. Dispose the ones you do not need.
Page rendering on each platform
| Platform | Page rendering |
|---|---|
| Android player (API 23+; API 25+ with Unity 6000.3) | Supported, with the Android class PdfRenderer, on a background thread. Textures are RGBA32. Run on emulators (API 23, 24, 26, 29 and 36) and on a Samsung Galaxy S23 (Android 16); see What was tested. |
| Windows 10/11 x64, Standalone player | Supported. Rendered by the PDF engine of Windows through LuanrobsPdf.dll, on a background thread. Textures are BGRA32. |
| Windows Editor, Play mode and Edit mode | Supported, whatever the build target is. |
| macOS, Linux, iOS, WebGL, and a macOS or Linux Editor | Not supported. PdfDocument.IsSupported is false, and every Load method returns a document that fails with "PDF page rendering is not supported on this platform." Nothing throws and no other app is opened. |
- Android. One background thread renders the pages of every document and of the viewer, one page at a time, and never the Android UI thread. The game does not wait for a render. Unity is paused while the native viewer is on screen, so results arrive when the player returns to the game.
- Windows. Each document has a renderer of its own, separate from the viewer's. Unity keeps running under the in-game viewer, so documents can be loaded and rendered while it is open.
- Edit mode on Windows. The API also works outside Play mode, driven by the Editor's update loop, so you can use it in editor tools such as an EditorWindow. Dispose the document when the tool closes.
- The two platforms use different PDF engines, so how a page is drawn, forms and annotations included, depends on the platform, as it does in the viewer. On Android 6.0 (API 23), text in fonts that are not embedded in the PDF is not drawn in page textures either.
Page rendering together with the viewer
Documents and the viewer are independent. You can load documents and render pages while the viewer is open, and open the viewer while documents are loaded. On Windows the results arrive live. On Android the game is paused behind the native viewer, so they arrive when the player returns to the game.
This sample opens the viewer on the page that was picked, for example when the player clicks a thumbnail:
using Luanrobs.Pdf;
using UnityEngine;
public class ThumbnailLinks : MonoBehaviour
{
[SerializeField] private PdfAsset manual;
// Call this with the page index of the clicked thumbnail.
public void OpenAtPage(int pageIndex)
{
PdfViewerOptions options = manual.DefaultOptions ?? new PdfViewerOptions();
options.startPage = pageIndex;
manual.Open(options);
}
}
The rule of one viewer at a time does not apply to documents. Only PdfViewer calls are rejected while a viewer is open.
PDF Page Image (no code)
PdfPageImage is a component that shows one page of a PDF in the RawImage on the same GameObject, without writing a script. It is built on PdfDocument, so it works where Rendering pages to textures works: Android and Windows. It needs the com.unity.ugui package, and it is only available when that package is installed.
- Select a GameObject under a Canvas. If it has no Raw Image, the component adds one.
- Click Add Component > luanrobs > PDF Page Image.
- Assign a
PdfAssetto the Pdf field. - Set the page and the resolution, and press Play.
| Inspector field | Property in code | Type | Purpose |
|---|---|---|---|
Pdf |
PdfAsset |
The PDF whose page is shown. | |
| Page Index | PageIndex |
int |
Zero-based index of the page. A negative value counts as 0. Once the PDF is loaded, a value past the last page shows the last page. |
| Resolution | Resolution |
int |
Longest side of the page texture in pixels, from PdfPageImage.MinResolution (64) to PdfPageImage.MaxResolution (4096). The default is 1024. The page is fitted into a square of this size, so a portrait page is this tall and narrower. Larger is sharper and uses more memory. |
| Night Mode | NightMode |
bool |
Inverts all page colors, including images, like the viewer's night mode. |
The component also has read-only properties and three methods:
| Member | Description |
|---|---|
int PageCount { get; } |
Number of pages of the PDF, or 0 until it is loaded. |
bool IsLoading { get; } |
true while the PDF is loading or a page is being rendered. |
string Error { get; } |
Why the page could not be shown, or null when nothing went wrong. |
Texture2D Texture { get; } |
The texture currently shown, or null. It belongs to the component. |
void Refresh() |
Loads the PDF if it is not loaded yet and renders the current page again. Does nothing outside Play mode. |
void NextPage() |
Shows the next page. Does nothing on the last page. |
void PreviousPage() |
Shows the previous page. Does nothing on the first page. |
How it behaves:
- Play mode and players. While the component is enabled it loads the PDF, renders the page and assigns the texture to the RawImage. In Edit mode it does nothing, and calling
Refresh()there does nothing either, so the RawImage has no texture until you press Play. uGUI draws a RawImage without a texture as a plain rectangle in its Color (white by default). - Changes render again. Setting
PageIndex,ResolutionorNightModefrom code to a different value renders the page again, and the previous page stays on screen until the new one is ready. SettingPdfto a different asset is different: it clears the RawImage at once, and the RawImage stays without a texture until the page of the new PDF has been rendered. - Inspector changes while the game runs. In the Editor, changing a field in the Inspector during Play mode renders again at once, and a new Pdf is loaded. A script or an animation that changes the serialized fields without using the properties does not: call
Refresh()afterwards, which also loads a different PDF. From code, use the properties. - Buttons without code.
NextPageandPreviousPagecan be picked in a Button's On Click () list: drag the GameObject that has the component into the object slot and pick PdfPageImage > NextPage (). - Page shape. The RawImage is not resized. To keep the page undistorted, add an Aspect Ratio Fitter to the same GameObject and choose an Aspect Mode such as Fit In Parent. The component sets its aspect ratio to the page's every time a page is shown.
- Cleanup. When the component is disabled or destroyed it disposes its document, destroys its texture and clears the RawImage. The texture belongs to the component, so do not destroy it yourself.
- One document for each component. To show many pages of the same PDF, for example a grid of thumbnails, use one
PdfDocumentfrom a script instead. The limits of page rendering (two pages at a time, a few textures per frame) count per document, so they count per component and are not shared: many components with a large Resolution that are enabled together all render at once. On such a screen use a smaller Resolution, or enable the components a few at a time. - No PDF assigned. The component logs one warning and does nothing, so the RawImage has no texture.
- Platform without page rendering. The RawImage gets no texture,
Erroris set to a message and one warning is logged. Nothing throws. Because uGUI draws a RawImage without a texture as a plain rectangle, checkPdfDocument.IsSupportedand hide the GameObject, or show something else, when it isfalse. - No events. Read
PageCount,IsLoading,ErrorandTexturewhen you need them. If you need a callback when a page arrives, usePdfDocument. - Memory. A 1024 pixel page is at most 4 MB, a 2048 pixel page at most 16 MB and a 4096 pixel page at most 64 MB. See Memory and limits of page rendering.
The same properties can be set from code:
using Luanrobs.Pdf;
using UnityEngine;
public class PosterRack : MonoBehaviour
{
[SerializeField] private PdfPageImage pageImage;
[SerializeField] private PdfAsset[] posters;
public void Show(int posterIndex)
{
pageImage.Pdf = posters[posterIndex];
pageImage.PageIndex = 0;
pageImage.Resolution = 2048;
pageImage.NightMode = false;
}
public void ShowAgain()
{
pageImage.Refresh();
}
}
Platform support
| Platform | What happens | Options | Events |
|---|---|---|---|
| Android (API 23+; API 25+ with Unity 6000.3) | Native full-screen viewer. Unity is paused behind it. | Applied. | Delivered when the player returns to the game. |
| Windows 10/11 x64, Standalone player | In-game full-screen viewer. Unity keeps running. | Applied. | Delivered live. |
| Windows Editor, Play mode | In-game full-screen viewer in the Game view. | Applied. | Delivered live. |
| Editor outside Play mode | Opens the system PDF app (fallback). | Ignored. | Opened and Closed fire immediately. |
| macOS, Linux (player and Editor) | Opens the system PDF app (fallback). | Ignored. | Opened and Closed fire immediately. |
| iOS | Not supported in this version. A native iOS viewer is planned. | - | - |
| WebGL | Not supported in this version. | - | - |
The viewer is chosen for each open call. In the Windows Editor the in-game viewer is used in Play mode whatever the build target is, including Android; the "Open PDF" button in the Inspector outside Play mode uses the system PDF app.
Use PdfViewer.IsNativeViewerSupported to branch your UI. It is true in an Android player, and on Windows (player and Editor) when the Windows renderer can be loaded. It is false on macOS and Linux, and in a macOS or Linux Editor even when the build target is Android. In the Windows Editor it is true outside Play mode as well, although documents opened there still go to the system PDF app.
using Luanrobs.Pdf;
using UnityEngine;
public class ReaderHint : MonoBehaviour
{
[SerializeField] private GameObject externalAppHint;
private void Start()
{
externalAppHint.SetActive(!PdfViewer.IsNativeViewerSupported);
}
}
Rendering pages to textures is a separate feature with its own check, PdfDocument.IsSupported. It is true in an Android player, and on Windows (player and Editor, in Play mode and in Edit mode) when the Windows renderer can be loaded. It is false on macOS, Linux, iOS and WebGL, and there is no fallback there: loading a document fails with a message. See Page rendering on each platform.
Windows viewer
On Windows the PDF is shown inside your game, in a full-screen viewer shown on top of everything else. It is used in a Standalone player and in the Editor's Play mode.
Requirements and setup
- Windows 10 or 11, 64-bit (x64). Tested on Windows 11 only.
- No setup. The viewer creates its own hidden object when a PDF is opened; see Which objects does the package create at run time?. It needs no Canvas, no EventSystem, no PanelSettings, no prefab and no shader.
- It is drawn with IMGUI on top of the rendered frame, so it does not use the render pipeline. It was run with the Built-in pipeline and with URP. HDRP was not tested.
- It reads the mouse, keyboard and touch screen directly: through the Input System package when that package is installed and active, otherwise through the legacy Input Manager. What was tested says how far each of the two was tested.
- Pages are rendered by the PDF engine built into Windows (
Windows.Data.Pdf) through one small native DLL that ships with the package. The page rendering API (PdfDocument) uses the same DLL.
Controls
| Input | Vertical mode | Horizontal mode |
|---|---|---|
| Mouse wheel | Scroll. | Previous or next page. While zoomed: scroll inside the page. |
| Shift + mouse wheel | Scroll sideways while zoomed. | Scroll sideways while zoomed. |
| Ctrl + mouse wheel | Zoom in or out at the cursor. | Zoom in or out at the cursor. |
| Drag with the left button | Pan. | Drag to the previous or next page. While zoomed: pan inside the page. |
| Double-click | Zoom in at that point, or back to zoom 1. | Same. |
| Scrollbar on the right edge | Drag the thumb, or click the track. | - |
| On-screen previous / next buttons | - | Previous or next page. |
+ (the = key or numpad +) / - / 0 |
Zoom in, zoom out, reset zoom. | Same. |
| Page Down, Space | Scroll down by almost one screen. | Next page. |
| Page Up, Shift + Space | Scroll up by almost one screen. | Previous page. |
| Up / Down arrows | Scroll. | Previous or next page. While zoomed: pan. |
| Left / Right arrows | Previous or next page. While zoomed: pan sideways. | Previous or next page. While zoomed: pan. |
| Home / End | Top or bottom of the document. | First or last page. |
| Esc | Close. | Close. |
| Toolbar close button, or the corner close button when the toolbar is hidden | Close. | Close. |
| Touch: drag, flick, pinch, double-tap | Scroll, scroll with inertia, zoom, toggle zoom. | Change page, zoom, toggle zoom. |
Touch input is implemented but has not been tested on a touch device yet. The viewer does not read gamepads.
Options on Windows
Every PdfViewerOptions field has the same meaning as on Android. A few details are specific to Windows:
- Vertical mode. Pages are fitted to the window width, but the page column stops growing at 1200 units (1200 pixels at 100% display scaling) and is centered. This keeps a page readable on a very wide window.
- Horizontal mode. One whole page is fitted at a time, with previous and next buttons on the sides.
- Night mode. Dark toolbar and background, and pages with inverted colors.
- Hidden toolbar. With
showToolbar = falsethe top bar is replaced by a small round close button in the top-left corner. Esc also closes. - Zoom. Double-click zooms to 2.5x, or to
maxZoomwhen that is lower. Zoom resets when the window size changes; the current page is kept.
Rendering quality
Each page is rendered at the size it has on screen. After you zoom, the visible pages are rendered again, sharper, as soon as the zoom has settled.
Sharpness has a ceiling. The viewer keeps its page textures inside a memory budget (64 to 256 MB, depending on the machine), and one page may use only a share of it. The budget is a thirty-second of the system memory, limited to a quarter of the graphics memory. How far the sharpening goes depends on the budget, the display scaling and the shape of the page. For an A4 page in vertical mode in a 1920 x 1080 window at 100% display scaling, text keeps getting sharper up to about 1.2x zoom with a 64 MB budget, 1.75x with 128 MB and 2.4x with 256 MB. Beyond that the page is magnified from the sharpest version, so it gets larger but not sharper.
A page that cannot be rendered shows a "This page could not be rendered" mark and the rest of the document stays usable. If no page at all can be rendered, the viewer closes and raises PdfViewer.Error.
Your game keeps running under the viewer
Unlike on Android, Unity is not paused. Update, coroutines, physics, audio and Time.timeScale are left alone.
- uGUI is blocked automatically. While the viewer is open, Buttons and other uGUI controls under it do not react. The EventSystem stays enabled and
EventSystem.currentremains valid (IsPointerOverGameObject()returnsfalse), but its input modules are disabled. They are enabled again when the viewer closes. - Direct input is not blocked. Scripts that read
Input.GetKey,Input.GetMouseButton,Keyboard.current,Mouse.currentand so on still see every key and click. CheckPdfViewer.IsOpenin that code. UI Toolkit runtime panels are not blocked either. - The cursor is shown. If your game locks or hides the cursor, the viewer unlocks and shows it while it is open and restores the previous state when it closes.
- Pause if you need to. If the game should not go on while the player reads, pause it yourself.
using Luanrobs.Pdf;
using UnityEngine;
public class PlayerShooting : MonoBehaviour
{
private void Update()
{
if (PdfViewer.IsOpen)
{
return;
}
if (Input.GetMouseButtonDown(0))
{
Fire();
}
}
private void Fire()
{
Debug.Log("Fire");
}
}
The sample above uses the legacy Input Manager. The same check applies to code that uses the Input System package.
using Luanrobs.Pdf;
using UnityEngine;
public class PauseWhileReading : MonoBehaviour
{
private float previousTimeScale = 1f;
private void OnEnable()
{
PdfViewer.Opened += OnOpened;
PdfViewer.Closed += OnClosed;
PdfViewer.Error += OnError;
}
private void OnDisable()
{
PdfViewer.Opened -= OnOpened;
PdfViewer.Closed -= OnClosed;
PdfViewer.Error -= OnError;
}
private void OnOpened(int pageCount)
{
previousTimeScale = Time.timeScale;
Time.timeScale = 0f;
}
private void OnClosed(int lastPageIndex)
{
Time.timeScale = previousTimeScale;
}
private void OnError(string message)
{
Time.timeScale = previousTimeScale;
}
}
The viewer itself is not affected by Time.timeScale.
Files
The Windows viewer reads pages from the file on demand, so the file stays open for as long as the viewer shows it. Do not replace or rewrite a file passed to OpenFile until the viewer is closed. Files from a PdfAsset, from bytes or from a URL are the package's own temporary copies, so this needs no attention there.
If the renderer cannot be loaded
The viewer needs LuanrobsPdf.dll and the PDF engine of Windows 10 or later. If the DLL is missing from the build, or cannot be loaded, the package silently uses the fallback: the PDF opens in the system PDF app, Opened and Closed fire immediately, and PdfViewer.IsNativeViewerSupported is false. No error is raised.
PdfDocument.IsSupported is false in that case too. Page rendering has no fallback app: a document you load fails with a message in its Error property.
In the Editor
- The in-game viewer is used in Play mode only. Outside Play mode, for example from the "Open PDF" button in the Inspector, the PDF opens in the system PDF app.
PdfDocumentalso works outside Play mode, so editor tools can render pages. See Page rendering on each platform.- A script recompile during Play mode closes the viewer.
- The Editor keeps the DLL loaded once it has been used. To replace the DLL, close the Editor first.
The native DLL and its source
- The DLL is
Runtime/Plugins/Windows/x86_64/LuanrobsPdf.dll, about 200 KB, x64 only. - It contains no third-party library. It calls the Windows PDF engine and links Microsoft's C/C++ runtime statically, so players need no Visual C++ redistributable. The Microsoft code compiled into it (the C/C++ runtime and C++/WinRT) is listed in
Third-Party Notices.txt. - Its C++ source ships with the package in
Native~/Windows. Unity ignores that folder because of the~in its name. - You do not need to build anything. To rebuild the DLL anyway, you need a copy of the package that can be written to, because
build.batputs the new DLL into theRuntime/Plugins/Windows/x86_64folder of the package it is run from. A package installed from the Asset Store is read-only, so copy its folder into thePackagesfolder of your project first. Then close the Unity Editor and runbuild.batin theNative~/Windowsfolder of that copy. It needs Visual Studio 2019 or newer, or the Visual Studio Build Tools, with the "Desktop development with C++" workload and a Windows 10/11 SDK. The README in that folder has the details.
How it works on Android
- The Android side ships as source code in a Unity Android Library folder inside the package:
Runtime/Plugins/Android/LuanrobsPdfViewer.androidlib. Unity includes it in the Gradle project and Gradle compiles it when you build the player. There is no prebuilt.aarand no binary to trust. - Pages are rendered with the Android platform class
android.graphics.pdf.PdfRenderer. Nothing else renders PDF content. - Rendering pages into textures (
PdfDocument) uses the samePdfRenderer. It runs on the one background thread that also renders the viewer's pages, never on the Android UI thread, and the Unity main thread does not wait for a render. The finished pixels of a page come back to Unity as a byte array, at most one page per frame for each document, and become the texture. It needs no extra library, permission or manifest entry. - No third-party libraries are used. No AndroidX, no Kotlin.
- No permissions are declared by the library. The viewer reads only files your app can already access: its cache, the path you pass to
OpenFile, or the APK.OpenUrlneeds the standard INTERNET permission, which Unity adds automatically. - No native (.so) libraries are part of an Android build, so the package does not affect Google Play's 16 KB page size requirement. The Windows DLL in the package is used on Windows only.
- No Gradle or manifest setup is needed. The library declares its own Activity in its own manifest, and Unity merges it at build time. You do not need custom Gradle templates.
- The viewer is a separate full-screen Activity that opens on top of the Unity Activity. It survives device rotation; zoom resets and the position in the document is kept.
- The PDF file never crosses the C#/Java boundary as a byte array. C# writes the file to the app cache and passes only the path.
- Minimum Android version. The library itself declares a minimum of API 23. The minimum of your app is set by Unity: API 23 is the lowest with Unity 6000.0, and Unity 6000.3 raises it to API 25 on its own.
- HOME, then the launcher icon. If the user presses HOME while the viewer is open and then starts the game again from its launcher icon, the viewer is closed, because the Unity Activity uses the
singleTasklaunch mode.Closedis raised with the page that was on screen, so code that resumes reading keeps working. Returning to the game through the Recents screen was not tested. - Fonts on Android 6.0. The PDF renderer of Android 6.0 (API 23) does not draw text whose font is not embedded in the PDF. See Limitations.
Memory notes
The bytes of a PDF are serialized inside the PdfAsset. This has two consequences.
- A
PdfAssetreferenced by a scene (or by a prefab or ScriptableObject that the scene references) is loaded into memory together with that scene. A 40 MB PDF referenced from your main menu costs 40 MB of memory for as long as the menu is loaded, even if the user never opens it. - Opening a
PdfAssetwrites those bytes to the temporary cache folder, so the file also takes that much disk space. It is deleted when later PDFs are opened; at most the current and the previous file are kept.
For small and medium documents (manuals, terms, rule sheets) this is fine and is the most convenient path.
For very large files, put the PDF in Assets/StreamingAssets and open it with PdfViewer.OpenStreamingAsset. The file is then never loaded into managed memory. On Android it is copied from the APK to the cache on a background thread and opened from there. On Windows it is read directly from the StreamingAssets folder.
On Windows the viewer also keeps rendered pages as textures while it is open, inside a budget of 64 to 256 MB depending on the machine. They are released when the viewer closes.
PdfDocument has costs of its own. Loading a PdfAsset or bytes writes a temporary copy of the PDF to disk inside the Load call, on the main thread, and deletes it when the document is disposed; the bytes of the asset stay in memory as before. Every page texture takes width x height x 4 bytes of graphics memory (4 MB at 1024 x 1024, 64 MB at the 4096 x 4096 maximum) until you destroy it. For very large PDFs use PdfDocument.LoadStreamingAsset or PdfDocument.LoadFile, as with the viewer. See Memory and limits of page rendering.
using Luanrobs.Pdf;
using UnityEngine;
public class OpenLargeBook : MonoBehaviour
{
public void Open()
{
// Assets/StreamingAssets/Books/atlas.pdf
PdfViewer.OpenStreamingAsset("Books/atlas.pdf");
}
}
Note that a .pdf placed in StreamingAssets is not imported as a PdfAsset, so reference it by path, not by Inspector field.
Other ways to keep memory low with PdfAsset:
- Reference large PDF assets from a scene that is loaded only when needed.
- Load them on demand with Addressables or an AssetBundle and release them after opening. This path was not part of the tests.
Limitations
These are known and stated up front.
- Password-protected PDFs are not supported. Opening one raises
PdfViewer.Error, and aPdfDocumentfails to load it with a message inError. On Windows, every PDF encrypted with AES-256 is rejected the same way, even without a user password. PDFs that only carry an owner (permissions) password with RC4 or AES-128 encryption open on Windows. - Interactive forms and annotations. Whether form fields and annotations are drawn depends on the platform PDF engine: the Android version on Android, the Windows PDF engine on Windows. Forms cannot be filled in.
- No text selection, no links, no search. The viewer shows every page as an image. Text cannot be selected or copied, links inside the PDF cannot be clicked, and there is no search. This is the same in the Android viewer, in the Windows viewer and in the pages rendered with
PdfDocument. - Page rendering to textures: Android and Windows only. The viewer is full-screen; to put a page in your own UI or on a 3D surface, render it into a texture with
PdfDocumentor PDF Page Image. On macOS, Linux, iOS and WebGLPdfDocument.IsSupportedisfalseand loading a document fails with a message. See Rendering pages to textures. - Page textures have no mipmaps and are not readable. They are uncompressed 32-bit textures that live on the graphics device, so
GetPixelsdoes not work on them, and a page seen far away or at a shallow angle on a 3D surface can shimmer. - Page textures are at most 4096 pixels per side.
PdfDocument.MaxTextureSizeis 4096, or less when the graphics device supports only smaller textures. - Two page requests of a document at a time, and no priorities. The other requests wait in the order they were made. Cancel the ones you no longer need. The limit counts per document and is not shared, and every PDF Page Image has a document of its own; see Memory and limits of page rendering.
- Rendered pages are plain images. A page texture has no text selection and no links, and forms cannot be filled in.
- Android: page results wait while the native viewer is on screen. Unity is paused behind it, so they arrive when the player returns to the game.
- Page count in the Inspector may be "Unknown" for encrypted files or files with unusual compression settings.
PdfAsset.PageCountis0for these. Most files, including those with compressed object streams, report their page count. - Built-in viewers on Android and Windows only. macOS, Linux and the Editor outside Play mode open the system PDF app, ignore viewer options and cannot report page changes.
- Android 6.0 (API 23): text in fonts that are not embedded is not drawn. This is how the PDF renderer of that Android version behaves. In testing, a PDF that used the standard Courier font without embedding it showed blank code blocks, while its text in standard Helvetica was drawn. The same file is rendered correctly on API 24 and newer. Embed the fonts when you export a PDF; most tools do so by default. Page textures are drawn by the same renderer, so this applies to them as well.
- Android 6.0 to 7.1 (API 23 to 25): the viewer draws rotated and cropped pages wrongly. The native viewer draws a page that is stored rotated (
/Rotate), or whose page box does not start at the origin, without the rotation or the cropping. In testing, the viewer showed a white area beside such a page on API 23 and 24; API 25 was not run. On API 36, the only newer level checked, the viewer draws these pages correctly. The page renderer behindPdfDocumentdrew them correctly on API 23, 24 and 36 when a test harness called it directly. See On Android 6 or 7 a rotated or cropped page looks wrong in the viewer. - Android: a repeated
PageChangedwas seen once. In 42 synthetic trials on API 26 (Android 8.0), in which the app was frozen for 450 ms during a fling while the device was rotated, the callback received the same page twice once. It happened in the first 12 trials and not in a repeat of 30. The cause was not determined, and it did not happen in 22 trials on each of API 23, 24, 29 and 36. Treat the event as "the current page is N", not as a counter. - Android: HOME, then the launcher icon, closes the viewer. Unity's Activity uses the
singleTasklaunch mode, so starting the game again from its icon removes the viewer that was on top of it.Closedis raised with the page that was on screen. Returning through the Recents screen was not tested. - Windows: 64-bit Windows 10 or 11 only. Tested on Windows 11 only. If the renderer cannot be loaded, the system PDF app is used instead.
- Windows: zoom sharpness has a ceiling. See Rendering quality.
- Windows: no gamepad control. The viewer is operated with mouse, keyboard or touch. In a gamepad-only game, close it from code with
PdfViewer.Close(). - Windows: only uGUI input is blocked. Input your scripts read directly, and UI Toolkit runtime panels, still react under the viewer. Check
PdfViewer.IsOpen. - iOS is not supported in this version. Calls do not show the document there. A native iOS viewer is planned.
- One viewer at a time. On Android and Windows, an open call made while a viewer is open is ignored and raises
PdfViewer.Error. - Android: the viewer cannot be closed from code while it is on screen. Unity is paused behind it. See Closing the viewer.
- No legacy OBB support for StreamingAssets. On Android,
OpenStreamingAssetreads from the APK/AAB assets and does not support the legacy Split Application Binary (OBB) layout.
What was tested
This is what was run for version 1.0.0. Anything that is not listed under the first four headings was not tested; "Not tested" names the main items. Runs of earlier builds are marked as such.
EditMode tests
All 506 EditMode tests pass:
- on Unity 6000.3.12f1 in the development project (URP, Input System package), where the package is embedded;
- on Unity 6000.0.84f1 in a new project with the Built-in pipeline and the legacy Input Manager, with the package installed from a package tarball, so it is read-only in the project;
- on Unity 6000.3.12f1 in a new project with the Input System package, with the package installed from a package tarball.
They include tests of PdfDocument, PdfPageRequest and PDF Page Image with a fake renderer, and tests that load and render real PDFs with the Windows renderer in Edit mode. In both new projects a check of the installed sample found its eight scenes with no missing scripts, no unresolved asset references and no broken button callbacks.
A third new project, on Unity 6000.3.12f1 and without the com.unity.ugui package, had the package installed from a tarball and the Demo sample imported. It compiled: the sample scripts were skipped, PDF Page Image did not exist and the rest of the package did. The 472 EditMode tests that do not need uGUI passed there. Nothing else was run in that project: no scene, no Play mode and no player.
On Windows
- Three Windows 11 x64 players were run with the Mono scripting backend and no input sent to them: one built from a copy of the development project (Unity 6000.3.12f1, Direct3D 12, Input System package), run in a 1280 x 720 window and in a 540 x 960 window, and one built in each of the two new projects (Unity 6000.0.84f1 with Direct3D 11 and the legacy Input Manager, and Unity 6000.3.12f1 with the Input System package).
- The same automated check passed in all three. It opened and closed the viewer on the three sample PDFs and saw
Opened,PageChangedandClosedeach time. It loaded the three sample PDFs (4, 6 and 32 pages) withPdfDocumentand rendered pages in normal and in night mode; the night mode inverted the colors exactly. A box of 6000 x 6000 pixels gave a texture of 2894 x 4096. The errors for a page out of range and for a disposed document were logged once each. A page was rendered while the viewer was open on another PDF. The hidden objects were named[PDF Viewer] Dispatcherand[PDF Viewer] Overlay, and no object had a name that contains "luanrobs". It walked the eight sample scenes, and in scene07 Page To Textureit showed a page and its thumbnails, went to the next page, switched night mode on and clicked a thumbnail. No document was left open after leaving that scene. - In the player built from the development project, scene 07 was also resized from 1280 x 720 to 720 x 900 and from 540 x 960 to 900 x 640: the page was rendered again at the new size and the layout changed between side by side and stacked.
- In the Windows Editor, scene
07 Page To Textureran in two Play sessions in a row with Domain Reload disabled. No document, no package object and no event subscriber was left after either session. - In an earlier build, before this version, an automation script sent mouse, wheel and keyboard input to the viewer in a Windows 11 x64 player, in a project that uses the Input System package. This covered opening, wheel scrolling, Page Down, Ctrl + wheel zoom, dragging, Esc, horizontal mode, night mode, the events, resuming at the last page and the blocking of uGUI while the viewer is open. In the Windows Editor's Play mode, an earlier build was opened, closed and watched for events, also with Domain Reload disabled. With the legacy Input Manager an earlier build compiled and ran in a player with a document open, but no input was sent to it. None of this was repeated for this version.
PDF Page Image
- In the Windows Editor's Play mode, a check run in batch mode showed a page in the RawImage, replaced and destroyed the old texture when the next page was shown, rendered again after a value was changed the way the Inspector changes it, and left no document open after the component was disabled, enabled, deactivated and destroyed.
- The component was also tested in EditMode tests with a fake renderer.
On Android
- Two Android builds (IL2CPP, ARM64 and x86_64) were made from a copy of the development project: one with Unity 6000.3.12f1, whose minimum is API 25 because Unity 6000.3 raises it, and one with Unity 6000.0.84f1, whose minimum is API 23.
- They ran on five emulators: API 36 with the Unity 6000.3 build, and API 29, 26, 24 and 23 with the Unity 6000.0 build.
- The automated check passed on all five. It rendered pages of the sample PDFs and read back their size, format, orientation (upright) and night-mode inversion, logged the errors for a page out of range and for a disposed document once each, rendered a page while the viewer was open on another PDF, and opened the viewer four times. Textures were
RGBA32, with clamp wrapping, bilinear filtering and no mipmaps. A box of 6000 x 6000 pixels gave 2894 x 4096 and 4096 x 2304 on every level without a memory error. The hidden object was named[PDF Viewer] Dispatcherand no object had a name that contains "luanrobs". - The viewer was driven on all five emulators: scrolling, double-tap zoom, rotation both ways, closing with the toolbar button and with Back.
Opened, onePageChangedfor each page crossed, in order, andClosedarrived once each. The Unity build's scene 05 showed the same events on screen, also after two recreations of the viewer. No crash and no "application not responding" state occurred in any viewer run. - Repeated page report after the viewer was recreated. The font size and the display size were changed six times in a row while the viewer was open. With the previous library,
PageChangedrepeated the current page every time on API 36, 29 and 24, and four times out of four on API 23. With this version it never repeated it, on API 36, 29, 26, 24 and 23. A page that really changed after a recreation was still reported once. - Skipped page numbers during a fling. Rotating the device during a fling did not reproduce the skip on an emulator, so the app process was frozen for 450 ms in the middle of a fling, with and without a rotation while it was frozen. With the previous library page numbers were skipped on API 36, 29, 24 and 23 (for example from page 5 straight to page 10). With this version no page number was skipped in 22 trials on each of API 36, 29, 24 and 23 and in 52 trials on API 26. The freeze is synthetic: it reproduces a screen that stalls, not the frame drops of a real device.
- One repeated report. In 42 of those trials on API 26, in which the app was frozen during a fling while the device was rotated, the callback received the same page twice once. The cause was not determined; see Limitations.
- Page rendering beyond the automated check. Scene
07 Page To Texturewas driven by taps (84 page changes on API 36, 60 on each other level), with thumbnails, the night mode toggle, leaving the app and returning, and a viewer session in between. Memory use stayed flat after the first rounds and went back to its starting level when idle. Apart from the abort described below, no out-of-memory error, "bitmap too large" error, JNI error, crash or "application not responding" state was logged. A test harness without Unity called the Java page renderer directly on all five emulators: the row order and the red, green, blue, alpha byte order were confirmed by pixel values, night mode inverted exactly, the failure messages for a page out of range and for unsupported sizes were the expected ones, cancelled requests delivered nothing, a closed document delivered nothing and left no temporary copy, 30 open, render and close cycles left no copy, and 60 renders ran while the native viewer was open and scrolled. - Rotated and cropped pages. PDFs stored with
/Rotate 90,/Rotate 270, a crop box and a page box that does not start at the origin were rendered correctly on API 23, 24 and 36 by the package's Java page renderer, which a test harness called directly; they were not run throughPdfDocumentin a Unity build. The viewer drew them correctly on API 36 and wrongly on API 23 and 24; see Limitations. - Time. On the API 36 emulator (192 MB Java heap), four 4096 x 4096 renders in a row all succeeded but took 813, 6639, 488 and 2430 ms. On the API 24 emulator (256 MB heap) they took 109 to 158 ms each. Ask for the size you show.
- The API 29 emulator ran with the Vulkan graphics API. After the automated check had passed, the player aborted while quitting inside the emulator's Vulkan driver; no code of the package was in the stack. This did not happen with OpenGL ES 3 on API 23, 24, 26 and 36.
- In earlier builds, before this version, the Android viewer was run on emulators with API 23, 25, 26, 29 and 36, and on a Samsung Galaxy S23 (Android 16, ARM64). Opening and closing a document 15 times left memory use flat, a fling went through the 32 pages of the long sample document, and night mode, horizontal mode, the start page, the events and resuming at the last page worked.
- Samsung Galaxy S23 (Android 16, ARM64), an automated check of a build made with Unity 6000.3.12f1, with no touch input:
PdfDocumentloaded the three sample PDFs and rendered pages in normal and night mode, the native viewer was opened four times and closed with the Back key, withOpened,PageChangedandClosedraised once per opening, the eight sample scenes loaded and scene 07 showed its page. In a second run, taps and swipes sent through adb scrolled and flung the 32-page sample in the native viewer to page 25 and back to page 19:PageChangedwas raised once per page, in order, on the way back,Closedreported page 19 and "Continue from page 19" reopened the viewer there. In scene 07 the Next button, a thumbnail and the night mode toggle each showed the expected page. Pinch zoom and rotating the device while reading were then tried by hand on the same phone by the publisher and worked; nothing was logged or measured for that part.
Not tested
- Pinch zoom and rotation on a real Android device beyond one hand trial on the Samsung Galaxy S23: pinch zoom cannot be sent through adb, so nothing was logged or measured, and no other phone was used.
- Android API 25 (7.1), 27 (8.1), 28 (9) and 30 to 35, and Unity 6000.3 builds below API 36.
PdfDocument.Load(byte[]),PdfDocument.LoadFileandPdfDocument.LoadStreamingAssetthrough the C# code on Android. OnlyLoad(PdfAsset)ran there. The Java side of the StreamingAssets copy ran in the harness without Unity, and disposing a document while that copy is in progress was not run from C#.- The PDF Page Image component in a player and on Android.
- Scene
07 Page To Texturein landscape on Android: the test build does not rotate, so the side-by-side layout was not seen on a device. - Real out-of-memory conditions on Android devices with a small memory: the emulators had Java heaps of 192 to 512 MB and a 4096 x 4096 page never ran out of memory.
- Windows 10. The Windows viewer was run on Windows 11 only.
- Mouse, keyboard and touch input in the Windows players of this version, and in the Windows viewer: double-click zoom, the
+/-/0keys, the arrow keys, Home / End, Space, Page Up, Shift + wheel, the scrollbar, the on-screen page buttons and the close buttons. They are implemented but were not part of the runs above. - Touch input in the Windows viewer, high-DPI display scaling and resizing the window while the viewer is open.
- The Windows viewer with the Input System package set to Fixed Update or Manual update mode, and with UI Toolkit runtime panels.
- Windows players with the IL2CPP scripting backend, and page rendering with IL2CPP on Windows.
- HDRP, URP with Unity 6000.0, and, in a project without the
com.unity.uguipackage, anything beyond compiling and the EditMode tests: the viewer, page rendering in Play mode and a player were not run there. - This version with the package copied under
Assets/, and in a new URP project. Both were run on an earlier build. - macOS and Linux. Nothing was run on those systems.
- ARMv7 (32-bit) Android builds and the Mono scripting backend on Android.
- Devices with little memory, and opening from a real URL on old Android versions.
- Addressables and AssetBundles.
- Returning to the game through the Recents screen while the Android viewer is open.
- PDFs with forms or annotations.
- Password-protected PDFs, beyond the error they raise.
- iOS, which is not supported.
API reference
Namespace: Luanrobs.Pdf. Assembly: Luanrobs.Pdf.
If your scripts live in an assembly definition, add a reference to Luanrobs.Pdf.
PdfAsset
public sealed class PdfAsset : ScriptableObject
A PDF document imported into the project. Created automatically for every .pdf file.
| Member | Description |
|---|---|
byte[] Bytes { get; } |
Raw contents of the PDF file. Do not modify the returned array. |
int PageCount { get; } |
Number of pages detected at import time, or 0 if it could not be determined. |
long SizeInBytes { get; } |
Size of the PDF file in bytes. |
bool HasDefaultOptions { get; } |
true when this PDF carries its own default viewer options (Override Default Options in its import settings). |
PdfViewerOptions DefaultOptions { get; } |
A copy of this PDF's default viewer options, or null when HasDefaultOptions is false. Every call returns a new copy. |
void Open() |
Opens this PDF with its own default options if it has any, otherwise with the built-in defaults. Can be used directly as a UnityEvent target, for example in a Button's On Click () list. |
void Open(PdfViewerOptions options) |
Opens this PDF with the given options, which replace the PDF's own defaults completely. null behaves like Open(). |
See Default options per PDF for the precedence rules.
[SerializeField] private PdfAsset manual;
public void ShowManual()
{
manual.Open(new PdfViewerOptions { nightMode = true });
}
PdfViewerOptions
[Serializable] public sealed class PdfViewerOptions
Settings for a single viewer session.
| Member | Description |
|---|---|
string title |
Text shown in the toolbar. Empty uses the asset or file name. Default "". |
int startPage |
Zero-based index of the page shown when the viewer opens. Out-of-range values are clamped. Default 0. |
PdfScrollDirection scrollDirection |
Page layout and scroll direction. Default Vertical. |
bool nightMode |
Inverts all page colors, including images and photos. Default false. |
bool showToolbar |
Shows the top bar with the close button and title. Default true. |
bool showPageIndicator |
Shows a permanent "page / count" badge at the bottom of the viewer. Default true. |
bool enableZoom |
Allows zoom: pinch and double-tap on Android; Ctrl + wheel, double-click, + / - and pinch on Windows. Default true. |
float maxZoom |
Maximum zoom factor relative to the fitted page. Clamped to 1-10; 1 or less disables zoom. Default 5. |
PdfViewerOptions Clone() |
Returns an independent copy of these options. |
PdfScrollDirection
public enum PdfScrollDirection
| Value | Description |
|---|---|
Vertical = 0 |
Pages are stacked and scroll continuously. |
Horizontal = 1 |
One page is shown at a time. |
PdfViewer
public static class PdfViewer
Entry point for opening and closing the viewer and for listening to its events.
Properties
| Member | Description |
|---|---|
static bool IsOpen { get; } |
true from the moment an open call is accepted, including loading, until Closed or Error is raised for it. false during an OpenUrl download. When the fallback is used it is already false again when the open call returns. |
static bool IsNativeViewerSupported { get; } |
true in an Android player, and on Windows (player and Editor) when the Windows renderer can be loaded. false everywhere else. |
Methods
| Member | Description |
|---|---|
static void Open(PdfAsset asset, PdfViewerOptions options = null) |
Opens an imported PDF asset. Options that are not null are used as they are; with null, the asset's own default options apply if it has any, otherwise the built-in defaults. |
static void Open(byte[] pdfBytes, string name = null, PdfViewerOptions options = null) |
Opens a PDF from raw bytes. name is used for the temporary file and the default title. |
static void OpenFile(string absolutePath, PdfViewerOptions options = null) |
Opens a PDF from an absolute file path readable by the app. |
static void OpenStreamingAsset(string relativePath, PdfViewerOptions options = null) |
Opens a PDF from StreamingAssets. The path is relative to that folder. |
static void OpenUrl(string url, PdfViewerOptions options = null) |
Downloads a PDF to the cache, then opens it. |
static void Close() |
Cancels an OpenUrl download that is still running. On Windows, closes the viewer. On Android, closes a viewer that is still starting. See Closing the viewer. |
For every open method: a null options means the built-in defaults (for a PdfAsset, its own default options first), and an empty title is filled with the asset name or file name. The options object is copied, never modified. Null or empty arguments throw ArgumentNullException or ArgumentException, and so does a relative path or URL. I/O failures raise Error instead of throwing. On Android and Windows, an open call made while a viewer is open is ignored and raises Error.
Every member must be used from the Unity main thread. The open and close methods throw InvalidOperationException when called from another thread.
Events
| Member | Description |
|---|---|
static event Action<int> Opened |
The document was opened. Argument: page count. |
static event Action<int, int> PageChanged |
The current page changed. Arguments: zero-based page index, page count. |
static event Action<int> Closed |
The viewer was closed. Argument: zero-based index of the last page shown. |
static event Action<string> Error |
A document could not be opened or shown, or an open request was rejected. Argument: readable message. |
All events are raised on the Unity main thread. Each subscriber is invoked on its own, so a handler that throws does not stop the others.
PdfViewer.Opened += pageCount => Debug.Log($"Opened, {pageCount} pages.");
PdfViewer.OpenStreamingAsset("Docs/catalog.pdf", new PdfViewerOptions { startPage = 4 });
PdfOpenButton
public sealed class PdfOpenButton : MonoBehaviour
Component menu: luanrobs > PDF Open Button. Opens a PDF from the Inspector without code. Hooks a uGUI Button on the same GameObject automatically.
The Inspector shows the fields Pdf, Override Options and Options. From code, use the properties below.
| Member | Description |
|---|---|
PdfAsset Pdf { get; set; } |
The PdfAsset to open. |
bool OverrideOptions { get; set; } |
When on, Options is used. When off, the PDF's own default options apply if it has any, otherwise the built-in defaults. |
PdfViewerOptions Options { get; set; } |
The PdfViewerOptions used when OverrideOptions is on. Setting null restores the built-in defaults. |
void Open() |
Opens the assigned PDF. Can be wired to any UnityEvent. Logs one warning and does nothing if no PDF is assigned. |
PdfDocument
public sealed class PdfDocument : CustomYieldInstruction, IDisposable
A PDF opened for reading its pages as textures, without showing the viewer. It has no public constructor: use one of the Load methods. Because it is a CustomYieldInstruction, yield return document; in a coroutine waits until loading has ended. Every member must be used from the Unity main thread. See Rendering pages to textures.
Static members
| Member | Description |
|---|---|
static bool IsSupported { get; } |
true in an Android player, and on Windows (player and Editor) when the PDF engine of Windows can be loaded. false everywhere else. Never throws. |
static int MaxTextureSize { get; } |
Largest width or height of a page texture: 4096, or the largest texture the graphics device supports when that is smaller. |
static PdfDocument Load(PdfAsset asset, Action<PdfDocument> onLoaded = null) |
Loads an imported PDF. Returns at once, never null, with a document that is still loading. onLoaded is invoked once on the main thread when loading has ended, after Load has returned (later in the same frame or in a later frame, never inside the call); it is not invoked when the document is disposed first. |
static PdfDocument Load(byte[] pdfBytes, string name = null, Action<PdfDocument> onLoaded = null) |
Loads a PDF held in memory. name becomes Name; null or empty gives "Document". |
static PdfDocument LoadFile(string absolutePath, Action<PdfDocument> onLoaded = null) |
Loads a PDF from an absolute file path. The file is read in place and never modified or deleted. |
static PdfDocument LoadStreamingAsset(string relativePath, Action<PdfDocument> onLoaded = null) |
Loads a PDF from StreamingAssets. The path is relative to that folder. |
Properties
| Member | Description |
|---|---|
string Name { get; } |
The asset name, the name passed with the bytes, or the file name without .pdf. Page textures are named after it, for example "Manual (page 3)". |
bool IsLoading { get; } |
true from the Load call until loading has ended, successfully or not, or the document is disposed. |
bool IsReady { get; } |
true when the document was loaded and is not disposed. |
bool IsDisposed { get; } |
true after Dispose(). |
string Error { get; } |
Why loading failed, as a short message in English, or null while loading and when it was loaded. |
int PageCount { get; } |
Number of pages, or 0 while IsReady is false. |
bool keepWaiting { get; } |
true while IsLoading is true. This is what makes yield return document; wait. |
Methods
| Member | Description |
|---|---|
Vector2 GetPageSize(int pageIndex) |
Size of a page in PDF points (1/72 inch), with its rotation applied. Vector2.zero when there is no such page. |
Vector2Int GetRenderSize(int pageIndex, int maxWidth, int maxHeight) |
Size in pixels of the texture that RenderPage produces for the page and the box. Vector2Int.zero when there is no such page. Throws ArgumentOutOfRangeException when maxWidth or maxHeight is less than 1. |
PdfPageRequest RenderPage(int pageIndex, int maxWidth, int maxHeight, Action<PdfPageRequest> onCompleted = null) |
Renders a page, in the background, into a new texture that fits the box with the aspect ratio kept. Returns the request at once, never null. onCompleted is invoked once on the main thread, after RenderPage has returned (later in the same frame or in a later frame, never inside the call), for success and for failure, but not when the request is cancelled. Throws ArgumentOutOfRangeException when maxWidth or maxHeight is less than 1. |
PdfPageRequest RenderPage(int pageIndex, int maxWidth, int maxHeight, bool nightMode, Action<PdfPageRequest> onCompleted = null) |
The same, optionally with all colors inverted like the nightMode option of the viewer. |
void Dispose() |
Cancels the requests that are not done, closes the PDF and deletes the temporary copy, if there is one. Safe to call more than once. Textures that were delivered are not destroyed. |
Null and invalid arguments throw ArgumentNullException, ArgumentException or ArgumentOutOfRangeException, and a call from a thread other than the Unity main thread throws InvalidOperationException. Everything else, a page index that does not exist included, is reported through Error. See Page rendering errors.
using Luanrobs.Pdf;
using UnityEngine;
using UnityEngine.UI;
public class FirstPage : MonoBehaviour
{
[SerializeField] private PdfAsset manual;
[SerializeField] private RawImage image;
private PdfDocument document;
private void Start()
{
document = PdfDocument.Load(manual);
document.RenderPage(0, 1024, 1024, request => image.texture = request.Texture);
}
private void OnDestroy()
{
document.Dispose();
}
}
PdfPageRequest
public sealed class PdfPageRequest : CustomYieldInstruction
One page being rendered into a texture, returned by PdfDocument.RenderPage. It has no public constructor. In a coroutine, yield return request; waits until the request is done. Every member must be used from the Unity main thread.
| Member | Description |
|---|---|
PdfDocument Document { get; } |
The document the page belongs to. |
int PageIndex { get; } |
Zero-based index of the requested page, as passed to RenderPage. |
bool NightMode { get; } |
true when the page is rendered with inverted colors. |
bool IsDone { get; } |
true once the request has succeeded, failed or been cancelled. |
bool IsCancelled { get; } |
true when the request ended because Cancel() was called or the document was disposed before the page was delivered. |
Texture2D Texture { get; } |
The rendered page, or null while the request is pending and when it failed or was cancelled. It belongs to the caller: destroy it with Object.Destroy when it is no longer needed. |
string Error { get; } |
Why the request did not produce a texture, as a short message in English, or null while it is pending and when it succeeded. |
bool keepWaiting { get; } |
true while the request is pending. This is what makes yield return request; wait. |
void Cancel() |
Gives up the request. Does nothing when it is already done. Afterwards IsDone and IsCancelled are true, no texture is delivered and onCompleted is not invoked. Throws InvalidOperationException when called from another thread. |
PdfPageImage
[AddComponentMenu("luanrobs/PDF Page Image")] public sealed class PdfPageImage : MonoBehaviour
Component menu: luanrobs > PDF Page Image. Shows one page of a PdfAsset in the RawImage on the same GameObject, in Play mode. The GameObject needs a RawImage (the component adds one) and can hold only one PdfPageImage. The type exists only when the com.unity.ugui package is installed. See PDF Page Image (no code).
| Member | Description |
|---|---|
const int MinResolution |
64, the smallest value of Resolution. |
const int MaxResolution |
4096, the largest value of Resolution. |
PdfAsset Pdf { get; set; } |
The PDF whose page is shown. Assigning a different one clears the RawImage at once, loads the new PDF and shows its page when it is ready. |
int PageIndex { get; set; } |
Zero-based index of the page. A negative value counts as 0; once the PDF is loaded, a value past the last page counts as the last page. |
int Resolution { get; set; } |
Longest side of the page texture in pixels, clamped to MinResolution through MaxResolution. The page is fitted into a square of this size. Default 1024. |
bool NightMode { get; set; } |
true to show the page with inverted colors. |
int PageCount { get; } |
Number of pages, or 0 until the PDF is loaded. |
bool IsLoading { get; } |
true while the PDF is loading or a page is being rendered. |
string Error { get; } |
Why the page could not be shown, or null when nothing went wrong. |
Texture2D Texture { get; } |
The texture currently shown, or null. It belongs to the component, which destroys it when another page replaces it and when the component is disabled. |
void Refresh() |
Loads the PDF if it is not loaded yet and renders the current page again. Logs one warning and does nothing when no PDF is assigned. Does nothing outside Play mode, and in Play mode while the component is disabled. |
void NextPage() |
Shows the next page. Does nothing on the last page. Can be a UnityEvent target. |
void PreviousPage() |
Shows the previous page. Does nothing on the first page. Can be a UnityEvent target. |
Troubleshooting and FAQ
The PDF is not imported as a PdfAsset, or the Console reports an importer conflict
Unity allows one default importer per file extension. If another package in the project also registers an importer for .pdf, the two conflict and Unity reports it in the Console. Remove or disable the other PDF importer, then right-click the PDF and choose Reimport.
To keep both, add the scripting define LUANROBS_PDF_IMPORTER_OPT_IN in Player Settings > Scripting Define Symbols. This importer then stops being the default for .pdf files and can be chosen per file from the importer dropdown in the Inspector.
The Android build fails after adding the package
The Android viewer is compiled by Gradle from the LuanrobsPdfViewer.androidlib folder inside the package. If your project uses custom Gradle templates or a build script that excludes or filters plugin folders, that library can be left out of the build or fail to resolve.
Check that:
- your custom
settings.gradletemplate still contains Unity's**INCLUDES**placeholder, - your custom
mainTemplate.gradlestill contains Unity's**DEPS**placeholder, - no build script removes
.androidlibfolders from the exported project.
A project without custom Gradle templates needs no setup at all.
I changed the PDF's default options but the viewer still uses the old ones
The options in the PDF's Inspector are import settings. Press Apply after changing them. Also check where the PDF is opened: options passed in the call, or a PDF Open Button with Override Options on, replace the PDF's own defaults completely. See Default options per PDF.
PdfAsset > Open () does not appear in the On Click () function list
Drag the .pdf itself from the Project window into the object slot of the On Click () entry, not a GameObject. The function list then shows PdfAsset, with Open () under it. If the object slot does not accept the file, it was not imported as a PdfAsset; see the first entry of this section.
Nothing happens when I call Open() in the Editor
Outside Play mode, and in a macOS or Linux Editor, the PDF is handed to the system PDF app. If no app is associated with .pdf files on your machine, the operating system has nothing to launch. Install a PDF reader or set a default app for .pdf, then try again. A web browser set as the default PDF app works too.
Opened and Closed fire at the same time
This is expected whenever the fallback is used: on macOS and Linux, and in the Editor outside Play mode. An external app cannot report back, so both events fire immediately and PageChanged does not fire. To test page tracking, use Play mode in the Windows Editor, a Windows build or an Android device.
On Windows the PDF opens in the system PDF app instead of in the game
The in-game viewer is used in a Windows x64 player and in Play mode in the Windows Editor. It is not used outside Play mode. If it is not used in a player either, the renderer could not be loaded: check that LuanrobsPdf.dll is in the build's Plugins/x86_64 folder, that the build is x64, and that the machine runs Windows 10 or later. PdfViewer.IsNativeViewerSupported tells you which case applies.
On Windows my game reacts to clicks and keys while the viewer is open
The viewer blocks uGUI, not the input your scripts read directly. Check PdfViewer.IsOpen in that code. See Your game keeps running under the viewer.
Events and Unity pausing while the viewer is open
This section is about Android. On Windows, Unity keeps running and events arrive live.
On Android the viewer is a separate full-screen Activity on top of the Unity Activity. While it is open, Android pauses Unity:
OnApplicationPause(true)is called when the viewer opens andOnApplicationPause(false)when it closes.Updateand coroutines do not run while the viewer is on screen.- Audio played by Unity is paused, as with any app pause.
Events are always delivered on the Unity main thread. Because that thread is paused while the viewer is in front, do not rely on a handler running at the exact moment the user turns a page. Handlers may run only once Unity resumes, in the order the events happened. Use the events to record state (last page read, document finished), not to drive real-time gameplay behind the viewer.
If your game treats an app pause as "the player left" (for example by showing a pause menu or disconnecting from a session), check PdfViewer.IsOpen in your pause handling.
The Inspector shows "Unknown" for the page count
The importer reads the page count without a full PDF parser. It works for most files, including those with compressed object streams, but not for encrypted files or files with unusual compression settings. An unknown page count does not mean the file is broken. PdfViewer.Opened reports the real page count on Android and Windows.
Open raises "A PDF viewer is already open"
Only one viewer can be open at a time on Android and Windows. The call was made while PdfViewer.IsOpen was true, for example from a double tap or from a button that is wired twice. Wait for PdfViewer.Closed before opening another document.
On Android 6 some text is missing from a page
Android 6.0 (API 23) does not draw text whose font is not embedded in the PDF. In testing this affected text in the standard Courier font, while text in standard Helvetica was drawn. Export the PDF with its fonts embedded, which most tools do by default, and import it again. Android 7.0 (API 24) and newer draw the same file correctly.
On Android 6 or 7 a rotated or cropped page looks wrong in the viewer
On Android 6.0 to 7.1 (API 23 to 25) the native viewer draws a page that is stored rotated (/Rotate) without its rotation, and it ignores a crop box and a page box that does not start at the origin. In testing, a white area showed beside such pages on API 23 and 24. API 25 was not run. The viewer draws the same pages correctly on API 36. Page rendering with PdfDocument draws them correctly on API 23, 24 and 36, so on those versions you can show such a page as a texture.
On Android the viewer is gone after pressing HOME and starting the game again
Starting the game from its launcher icon brings the Unity Activity back and removes the viewer that was on top of it, because the Unity Activity uses the singleTask launch mode. PdfViewer.Closed is raised with the page that was on screen, so your game can offer to continue from there.
OpenStreamingAsset reports that the file was not found on Android
Check the path and its letter case; it is relative to Assets/StreamingAssets and case-sensitive on Android. Also check Split Application Binary in Player Settings: the legacy OBB layout stores StreamingAssets outside the APK and is not supported by OpenStreamingAsset.
An http:// URL fails to download
Plain http:// is blocked unless Allow downloads over HTTP permits it in Player Settings and, on Android, the app allows cleartext traffic. Use https:// when you can.
A PDF opens in a desktop PDF app but raises an error in the viewer
The most common causes are a password-protected PDF or a damaged file that desktop readers repair silently. On Windows, PDFs encrypted with AES-256 are also rejected, even when they open without asking for a password elsewhere. All of these are reported through PdfViewer.Error. Re-save the file without encryption from a PDF editor and import it again.
Can I show a PDF page inside my UI or on a 3D object?
Yes, on Android and Windows. Render the page into a texture with PdfDocument, or use the PDF Page Image component to show a page in a RawImage without code. See Rendering pages to textures and PDF Page Image (no code). The viewer itself is always full-screen. On macOS, Linux, iOS and WebGL page rendering is not available.
Loading a document fails because page rendering is not supported
Page rendering works in an Android player and on Windows 10 or 11 (64-bit), in the player and in the Editor. PdfDocument.IsSupported is false anywhere else, for example on macOS, Linux, iOS and WebGL and in a macOS or Linux Editor. It is also false on Windows when the renderer could not be loaded; check that LuanrobsPdf.dll is in the build's Plugins/x86_64 folder. Check PdfDocument.IsSupported before loading, and show something else when it is false.
A page texture looks soft, or a page on a 3D surface shimmers
A page texture has the size of the box you asked for, fitted to the page, and at most 4096 pixels per side. A box much smaller than the area the page covers on screen gives a soft page. A much larger box only costs memory and time. Ask for about the size the page has on screen, in pixels. Page textures have no mipmaps, so a page seen from far away or at a shallow angle can shimmer; render it at about the on-screen size and render it again when that size changes a lot. See Memory and limits of page rendering.
Which objects does the package create at run time?
At run time the package creates a hidden object named [PDF Viewer] Dispatcher the first time a PDF is opened or a PdfDocument is loaded, and, while the Windows viewer is open, a hidden object named [PDF Viewer] Overlay. Both are hidden in the Hierarchy, are not saved in your scenes, and are removed when Play mode ends or the application quits. You do not need to create, move or keep them.
Pages are rendered on a background thread named "PDF Viewer Renderer", on Android and on Windows. On Android, copying a StreamingAssets file runs on a short-lived thread named "PDF Viewer Asset Copy". Those are the names you see in the Profiler or in a crash report.
Does it work on iOS?
No. iOS is not supported in this version. Calls do not show the document there, although Opened and Closed still fire right away. A native iOS viewer is planned.
Does the package add permissions or SDKs to my build?
The Android library declares one Activity and no permissions. It uses only Android platform APIs and adds no SDK. OpenUrl uses Unity's networking, which needs the standard INTERNET permission; Unity adds it automatically.
A Windows build gets one extra file, LuanrobsPdf.dll (about 200 KB). It uses only Windows platform APIs, contains no third-party library and needs no installer or redistributable. Microsoft's C/C++ runtime and C++/WinRT code are compiled into it; see Third-Party Notices.txt.
The package contains no third-party library and no third-party source file. The sample PDFs and the PDF version of this manual embed subsets of two fonts, Nunito and Fira Code, both under the SIL Open Font License 1.1. No font file is part of the package. The details, and the Microsoft components compiled into the Windows DLL, are in the Third-Party Notices.txt file in the root folder of the package.
My app got much bigger or uses more memory after adding PDFs
PDF bytes are stored inside each PdfAsset and loaded with whatever references it. See Memory notes.
Support
Product page, manual and changelog: https://luanrobs.com/pdf-viewer/
Email: luanrobs@gmail.com
When reporting a problem, please include your Unity version, the platform (device model and Android version, or the Windows version), and the Console, Logcat or Player log output. If the problem is specific to one PDF and you can share it, attach the file.
I maintain and support this package myself. If it saves you time, a review on the Asset Store helps a lot. Thank you.