Installation
Lpdf generates PDF from XML, or from code that builds the same document. One engine runs in every SDK, so the output is identical on every platform. It is compiled to WebAssembly for the JavaScript SDK, to a WASI binary for the Python, Java, C#, and PHP SDKs (Java runs it compiled to JVM classes), and to a native library for PHP on Linux.
The examples in these docs are XML, and they work in every language: pass the XML to render, as under Create PDF below. Most examples also show the same document built in code, in a tab for each language, as under Create PDF with code. The builders are the same in every language: the same elements, the same attributes under the schema’s names, and the same constants, written in each language’s own case (fontSize in JavaScript, Java and PHP, font_size in Python, FontSize in C#).
Requirements
Section titled “Requirements”- Node.js 20 or later
- No external runtime dependencies — the WASM engine is bundled in the package
Install
Section titled “Install”npm install @lpdfio/lpdfCreate PDF
Section titled “Create PDF”import { L } from '@lpdfio/lpdf'import { writeFileSync } from 'node:fs'
const xml = `<lpdf version="1"> <document size="a4"> <section> <layout margin="48pt"> <column gap="m"> <text font-size="xl">Hello, world</text> <text>This PDF was made with Lpdf.</text> </column> </layout> </section> </document></lpdf>`
const engine = L.engine()
engine.render(xml).then((pdf) => writeFileSync('hello.pdf', pdf))render returns a promise. The example is an ES module: save it as hello.mjs, or set "type": "module" in package.json. CommonJS loads the package with require and gets the same classes:
const { L } = require('@lpdfio/lpdf')From 0.28.1 the package loads either way. Earlier versions load with require only: an import of @lpdfio/lpdf fails with ERR_PACKAGE_PATH_NOT_EXPORTED. To render a file, read it into a string and pass that to render.
Create PDF with code
Section titled “Create PDF with code”The same document, built with L instead of written as XML. render takes either one and makes the same PDF.
import { L, NoAttr } from '@lpdfio/lpdf'import { writeFileSync } from 'node:fs'
const doc = L.document({ size: 'a4' }, [ L.section(NoAttr, [ L.layout({ margin: '48pt' }, [ L.column({ gap: 'm' }, [ L.text({ fontSize: 'xl' }, ['Hello, world']), L.text(NoAttr, ['This PDF was made with Lpdf.']), ]), ]), ]),])
const engine = L.engine()
engine.render(doc).then((pdf) => writeFileSync('hello.pdf', pdf))Versioning
Section titled “Versioning”The first two numbers are the Lpdf engine, and the last number counts changes to this package only. 0.22.3 runs engine 0.22. Every engine release publishes all SDKs at X.Y.0, so the same X.Y means the same engine in every language. To stay on one engine and still get package fixes, use a tilde range in package.json:
"@lpdfio/lpdf": "~0.22.0"Requirements
Section titled “Requirements”- Python 3.11 or later, on Linux (x86_64 or aarch64, glibc or musl), macOS (x86_64 or arm64) or Windows (x64 or arm64)
- Nothing else: the engine runs inside Python on the
wasmtimepackage, which pip installs with the SDK
Install
Section titled “Install”pip install lpdfio-lpdfCreate PDF
Section titled “Create PDF”from pathlib import Pathfrom lpdf import L
xml = """<lpdf version="1"> <document size="a4"> <section> <layout margin="48pt"> <column gap="m"> <text font-size="xl">Hello, world</text> <text>This PDF was made with Lpdf.</text> </column> </layout> </section> </document></lpdf>"""
engine = L.engine()pdf = engine.render(xml)Path('hello.pdf').write_bytes(pdf)To render a file, read it into a string with Path('document.xml').read_text() and pass that to render.
Create PDF with code
Section titled “Create PDF with code”The same document, built with L instead of written as XML. render takes either one and makes the same PDF.
from pathlib import Pathfrom lpdf import L, NoAttr, DocumentAttr, LayoutAttr, ColumnAttr, TextAttr
doc = L.document(DocumentAttr(size='a4'), [ L.section(NoAttr, [ L.layout(LayoutAttr(margin='48pt'), [ L.column(ColumnAttr(gap='m'), [ L.text(TextAttr(font_size='xl'), ['Hello, world']), L.text(NoAttr, ['This PDF was made with Lpdf.']), ]), ]), ]),])
engine = L.engine()pdf = engine.render(doc)Path('hello.pdf').write_bytes(pdf)An attribute class takes its attributes as keyword arguments, TextAttr(font_size='xl'), and raises a TypeError for positional ones, so an attribute added in a later version never changes what a call sets.
Threads
Section titled “Threads”A render releases the GIL, so renders on threads run in parallel: use a thread pool, or asyncio.to_thread in async code. The first render of a process compiles the engine, which takes a few hundred milliseconds, and the renders after it share it.
Versioning
Section titled “Versioning”The first two numbers are the Lpdf engine, and the last number counts changes to this package only. 0.22.3 runs engine 0.22. Every engine release publishes all SDKs at X.Y.0, so the same X.Y means the same engine in every language. To stay on one engine and still get package fixes:
pip install "lpdfio-lpdf~=0.22.0"Requirements
Section titled “Requirements”- Java 17 or later
- No native code: the engine is compiled to JVM classes inside the jar, and runs on Endive, a WebAssembly runtime written in Java, which Maven or Gradle installs with the SDK
Install
Section titled “Install”Maven, with the newest version on Maven Central in place of VERSION:
<dependency> <groupId>io.lpdf</groupId> <artifactId>lpdf</artifactId> <version>VERSION</version></dependency>Gradle:
implementation("io.lpdf:lpdf:VERSION")Create PDF
Section titled “Create PDF”import io.lpdf.L;import java.nio.file.Files;import java.nio.file.Path;
public class Hello { public static void main(String[] args) throws Exception { var xml = """ <lpdf version="1"> <document size="a4"> <section> <layout margin="48pt"> <column gap="m"> <text font-size="xl">Hello, world</text> <text>This PDF was made with Lpdf.</text> </column> </layout> </section> </document> </lpdf> """;
var engine = L.engine(); byte[] pdf = engine.render(xml); Files.write(Path.of("hello.pdf"), pdf); }}To render a file, read it into a string with Files.readString(Path.of("document.xml")) and pass that to render.
Create PDF with code
Section titled “Create PDF with code”The same document, built with L instead of written as XML. render takes either one and makes the same PDF.
import io.lpdf.*;import java.nio.file.Files;import java.nio.file.Path;import java.util.List;import static io.lpdf.L.NoAttr;
public class Hello { public static void main(String[] args) throws Exception { var doc = L.document(new DocumentAttr().size("a4"), List.of( L.section(NoAttr, List.of( L.layout(new LayoutAttr().margin("48pt"), List.of( L.column(new ColumnAttr().gap("m"), List.of( L.text(new TextAttr().fontSize("xl"), List.of("Hello, world")), L.text(NoAttr, List.of("This PDF was made with Lpdf.")) )) )) )) ));
var engine = L.engine(); byte[] pdf = engine.render(doc); Files.write(Path.of("hello.pdf"), pdf); }}An attribute class sets each attribute with a method of its name, new TextAttr().fontSize("xl"), which returns the object, so the calls chain. Each method takes the attribute’s type, such as bold(true) or cols(3), so a value of another type doesn’t compile.
Threads
Section titled “Threads”render runs on the caller’s thread and returns the PDF’s bytes. An engine can be shared by every thread: each render runs in an instance of the engine of its own, so renders on several threads run in parallel.
Versioning
Section titled “Versioning”The first two numbers are the Lpdf engine, and the last number counts changes to this package only. 0.33.2 runs engine 0.33. Every engine release publishes all SDKs at X.Y.0, so the same X.Y means the same engine in every language. To stay on one engine and still get package fixes, use a version range:
<dependency> <groupId>io.lpdf</groupId> <artifactId>lpdf</artifactId> <version>[0.33.0,0.34.0)</version></dependency>Gradle takes the same range: implementation("io.lpdf:lpdf:[0.33.0,0.34.0)").
Requirements
Section titled “Requirements”- .NET 8 or later
- No external runtime dependencies — the Wasmtime runtime and the WASI binary are bundled in the package
Install
Section titled “Install”dotnet add package Lpdfio.LpdfCreate PDF
Section titled “Create PDF”using Lpdf;
var xml = """ <lpdf version="1"> <document size="a4"> <section> <layout margin="48pt"> <column gap="m"> <text font-size="xl">Hello, world</text> <text>This PDF was made with Lpdf.</text> </column> </layout> </section> </document> </lpdf> """;
var engine = L.Engine();var pdf = engine.Render(xml);await File.WriteAllBytesAsync("hello.pdf", pdf);To render a file, read it into a string with File.ReadAllTextAsync and pass that to Render.
Render runs on the caller’s thread and returns the PDF’s bytes. To render on another thread, write await Task.Run(() => engine.Render(xml)).
Create PDF with code
Section titled “Create PDF with code”The same document, built with L instead of written as XML. Render takes either one and makes the same PDF.
using Lpdf;using static Lpdf.L;
var doc = L.Document(new() { Size = "a4" }, [ L.Section(NoAttr, [ L.Layout(new() { Margin = "48pt" }, [ L.Column(new() { Gap = "m" }, [ L.Text(new() { FontSize = "xl" }, ["Hello, world"]), L.Text(NoAttr, ["This PDF was made with Lpdf."]), ]), ]), ]),]);
var engine = L.Engine();var pdf = engine.Render(doc);await File.WriteAllBytesAsync("hello.pdf", pdf);Versioning
Section titled “Versioning”The first two numbers are the Lpdf engine, and the last number counts changes to this package only. 0.22.3 runs engine 0.22. Every engine release publishes all SDKs at X.Y.0, so the same X.Y means the same engine in every language. To stay on one engine and still get package fixes, use a version range:
<PackageReference Include="Lpdfio.Lpdf" Version="[0.22.0,0.23.0)" />Requirements
Section titled “Requirements”- PHP 8.2 or later, with the DOM extension (
ext-dom; on Debian and Ubuntu it is thephp-xmlpackage) - Composer
- One of the two ways the SDK runs the engine, which it picks itself (How PHP runs the engine below):
- The native library in the package, through PHP’s FFI extension (
ext-ffi): on Linux with glibc 2.17 or newer, on x86_64 or arm64. A web server needsffi.enable=truein php.ini; the command line allows FFI as it is. - The
wasmtimecommand-line tool on yourPATH, which runs the bundled WASI binary: everywhere else, such as macOS, Windows and Alpine, and where FFI isn’t allowed. On Linux and macOS, where PHP’s user can’t write its home, aswww-dataunder PHP-FPM, it also needs PHP’s POSIX extension (ext-posix), for the SDK’s cache folder.
- The native library in the package, through PHP’s FFI extension (
Install
Section titled “Install”composer require lpdfio/lpdfCreate PDF
Section titled “Create PDF”<?phprequire_once 'vendor/autoload.php';
use Lpdf\L;
$xml = <<<'XML'<lpdf version="1"> <document size="a4"> <section> <layout margin="48pt"> <column gap="m"> <text font-size="xl">Hello, world</text> <text>This PDF was made with Lpdf.</text> </column> </layout> </section> </document></lpdf>XML;
$engine = L::engine();$pdf = $engine->render($xml);file_put_contents('hello.pdf', $pdf);To render a file, read it into a string with file_get_contents and pass that to render.
Create PDF with code
Section titled “Create PDF with code”The same document, built with L instead of written as XML. render takes either one and makes the same PDF.
<?phprequire_once 'vendor/autoload.php';
use Lpdf\Kit\DocumentAttr;use Lpdf\Kit\LayoutAttr;use Lpdf\L;use Lpdf\Layout\ColumnAttr;use Lpdf\Layout\TextAttr;use const Lpdf\NoAttr;
$doc = L::document(new DocumentAttr(size: 'a4'), [ L::section(NoAttr, [ L::layout(new LayoutAttr(margin: '48pt'), [ L::column(new ColumnAttr(gap: 'm'), [ L::text(new TextAttr(fontSize: 'xl'), ['Hello, world']), L::text(NoAttr, ['This PDF was made with Lpdf.']), ]), ]), ]),]);
$engine = L::engine();$pdf = $engine->render($doc);file_put_contents('hello.pdf', $pdf);An attribute class takes its attributes as named arguments, new TextAttr(fontSize: 'xl'). Positional arguments aren’t supported: the parameters follow the schema’s order, so an attribute added in a later version can move them.
How PHP runs the engine
Section titled “How PHP runs the engine”The package carries the engine twice: a native library, which PHP loads through its FFI extension and calls in its own process, and the WASI binary, which the wasmtime program runs in a process of its own for each render. L::engine() renders with the native library where it loads, and with wasmtime otherwise, and $engine->runner() says which one renders: ffi or wasm. Both make the same PDF.
Native library (ffi) |
wasmtime (wasm) |
|
|---|---|---|
| Runs on | Linux with glibc 2.17 or newer, x86_64 and arm64 | Wherever wasmtime runs |
| Needs | The FFI extension, and ffi.enable=true under a web server |
The wasmtime program on PATH |
| Each render | A call in PHP’s own process | A process of its own, which adds about 20 ms |
| Sandbox | None: the engine has the rights of the PHP process | WebAssembly’s: no files, no network |
The native library loads where PHP has the FFI extension, which the official Docker images leave out (docker-php-ext-install ffi, with libffi-dev), and where ffi.enable allows it. Its default, preload, allows FFI on the command line only, so PHP-FPM and Apache’s PHP module need ffi.enable=true in php.ini. Alpine’s C library, musl, isn’t supported: there the SDK renders with wasmtime.
wasmtime compiles the engine to native code at the first render and keeps it for the renders after, in a folder of the SDK’s: lpdf-wasmtime-<uid> in PHP’s temp directory, sys_get_temp_dir(), made with mode 0700 where it is missing. This way the SDK renders under PHP-FPM too, where PHP runs as www-data, whose home wasmtime can’t write. wasmCacheDir on the engine sets another folder. wasmtime runs what the folder holds without checking it, so the SDK uses a folder only where it is a directory, not a link, that PHP’s user owns and group and others can’t open, which it tells through PHP’s POSIX extension (ext-posix). It checks that folder only, not those above it, so put a wasmCacheDir inside a folder only PHP’s user can write. Most PHP builds have the extension; Alpine packages it apart, such as php83-posix, and Windows has none, so there the SDK uses no folder. Where it uses none, wasmtime keeps the engine in its own default place, in the user’s home or, on Windows, profile, and where it can’t create that either, the render throws an EngineException that says why and what to do: set wasmCacheDir, load the POSIX extension where it is missing, or on Windows let PHP’s user write its profile.
runner on the engine picks how: auto, the default, chooses as above; ffi renders with the native library only, and throws an EngineException that names what stands in the way where it can’t load; wasm renders with wasmtime only. For an app that renders templates, fonts or images its own users upload, wasm keeps the engine in WebAssembly’s sandbox. libPath loads the native library from another path.
<?phprequire_once 'vendor/autoload.php';
use Lpdf\Engine\EngineOptions;use Lpdf\L;
$engine = L::engine(new EngineOptions(runner: 'ffi'));echo $engine->runner(); // ffi, or an EngineException that says why notThe time limit and the memory cap below hold through both, with the differences their PHP notes give, and the engine’s memory is outside PHP’s memory_limit either way. Through the native library, a fault the engine can’t catch, such as running out of memory before its cap stops it, ends PHP’s process; through wasmtime it ends the wasmtime process, and the render throws an EngineException.
Versioning
Section titled “Versioning”The first two numbers are the Lpdf engine, and the last number counts changes to this package only. 0.22.3 runs engine 0.22. Every engine release publishes all SDKs at X.Y.0, so the same X.Y means the same engine in every language. To stay on one engine and still get package fixes:
composer require lpdfio/lpdf:~0.22.0Time limit
Section titled “Time limit”A render stops after 5 seconds with the SDK’s render error, which names the limit: The render timed out after 5 seconds. A PDF renders in milliseconds, so a render that runs that long is a document far larger than usual or a fault in the engine, and stopping it frees the thread or the process it held. timeout on the engine sets another limit, in seconds, and timeout: 0 sets none. A render stopped at its limit leaves the engine as it was, and the next render runs as usual.
import { L } from '@lpdfio/lpdf'
const engine = L.engine({ timeout: 60 })A render runs on a worker thread, one at a time, so it doesn’t hold up the event loop. At its limit the render rejects with an LpdfRenderError, the worker is stopped, and the next render starts a new one. In the browser, initLpdf(wasmUrl, licenseKey, { timeout: 60 }) takes the same option, and renders run on a Web Worker started from a blob: URL: a page with a Content-Security-Policy allows blob: in worker-src.
from lpdf import EngineOptions, L
engine = L.engine(EngineOptions(timeout=60))At its limit the render raises an EngineException. Renders on other threads go on.
import io.lpdf.EngineOptions;import io.lpdf.L;
var engine = L.engine(new EngineOptions().timeout(60));At its limit the engine interrupts the thread the render runs on, and the render throws an EngineException. Renders on other threads go on.
using Lpdf;using Lpdf.Engine;
var engine = L.Engine(new EngineOptions { Timeout = 60 });At its limit the render throws an EngineException. Renders on other threads go on.
<?phprequire_once 'vendor/autoload.php';
use Lpdf\Engine\EngineOptions;use Lpdf\L;
$engine = L::engine(new EngineOptions(timeout: 60));At its limit the render throws an EngineException. Through wasmtime its process is stopped. Through the native library the engine stops the render itself, at its next check: a step the engine hands to a library, such as reading the XML, subsetting a font or compressing an image, finishes first, so a render can run past its limit by that step’s time.
Memory limit
Section titled “Memory limit”A render may allocate 1024 MB, which holds thousands of pages of text and tables. One that needs more stops with the SDK’s render error, which names the cap: the render needs more memory than its cap of 1024 MB: raise the cap in the engine's options, or render the document in smaller parts. What counts is what the render allocates, the data it binds included. In the Python, Java, C# and PHP SDKs the fonts, images and files sent with a render count too; in JavaScript what is loaded on the engine before the render doesn’t. There is no limit on the size of the XML or of a document built in code. maxMemoryMb on the engine sets another cap, a whole number of megabytes from 1 to 4096: lower in a small container, higher for a big document on a machine with the memory for it. 4096 is the most the engine can address as a 32-bit WebAssembly module, and PHP’s native library keeps the same range. A render stopped at its cap leaves the engine as it was, and the next render runs as usual.
If the engine crashes, by a fault in it or a render that runs out of memory before its cap stops it, the render fails with the same message in every SDK: The engine crashed during the render. This is a bug in Lpdf, or the render ran out of memory before its cap stopped it: please report it with the document at https://github.com/lpdfio/lpdf/issues. The next render runs on a fresh engine. PHP’s native library is the exception, below.
import { L } from '@lpdfio/lpdf'
const engine = L.engine({ maxMemoryMb: 2048 })Past the cap the render rejects with an LpdfRenderError. In the browser, initLpdf(wasmUrl, licenseKey, { maxMemoryMb: 2048 }) takes the same option. After a crash the error’s cause holds the engine’s own error, and the worker is replaced for the next render.
from lpdf import EngineOptions, L
engine = L.engine(EngineOptions(max_memory_mb=2048))Past the cap the render raises an EngineException. After a crash it is raised from the engine’s trap.
import io.lpdf.EngineOptions;import io.lpdf.L;
var engine = L.engine(new EngineOptions().maxMemoryMb(2048));Past the cap the render throws an EngineException. The engine’s memory is part of the JVM’s heap, so a render that fills the heap before it reaches the cap throws an EngineException too, which says so: give the JVM more heap with -Xmx, or set a lower cap. After a crash the exception’s cause is the engine’s trap.
using Lpdf;using Lpdf.Engine;
var engine = L.Engine(new EngineOptions { MaxMemoryMb = 2048 });Past the cap the render throws an EngineException. After a crash its InnerException is the engine’s trap.
<?phprequire_once 'vendor/autoload.php';
use Lpdf\Engine\EngineOptions;use Lpdf\L;
$engine = L::engine(new EngineOptions(maxMemoryMb: 2048));Past the cap the render throws an EngineException. Through wasmtime, after a crash its previous exception holds what wasmtime reported. Through the native library, a fault the engine catches throws the same message, its previous exception holding the engine’s own, and the next render runs as usual. A render that runs out of memory before its cap stops it ends PHP’s process instead, and nothing is thrown: under PHP-FPM the request fails and FPM starts a new worker. Where a render could need more memory than the machine has, keep maxMemoryMb below it, or render with wasm.
Images and fonts
Section titled “Images and fonts”An image or a font that comes from a file is declared in assets with a src path. The SDK reads the file from the machine that renders the PDF, so a relative path is relative to the working directory: JavaScript, Python and PHP on their own, Java and C# only through the engine’s SrcFallback (srcFallback in Java), as under Attachments. The engine does not fetch URLs or read data URIs. An image file the SDK cannot read is an error, and a font file it cannot read falls back to Helvetica without one. To supply the bytes yourself, call loadImage(name, bytes) or loadFont(name, bytes) on the engine and leave src out.
Asset names use lowercase letters, digits, and -, and start with a letter: logo, serif-bold.