Skip to content
LpdfDocsv0.38-r1124.9

Lpdf is pre-release. The XML schema and SDK APIs can change between releases.

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#).

  • Node.js 20 or later
  • No external runtime dependencies — the WASM engine is bundled in the package
Terminal window
npm install @lpdfio/lpdf
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.

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))

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"

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.

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.

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.

A document built in code can name each word an attribute takes as a constant. Every closed enumeration of the schema has one in each SDK, but for the words that stand beside a length (below). A constant is named as the schema names its type, with a member for each word in the language’s case:

JavaScript and C# PHP Python and Java The word
Orientation.Landscape Orientation::Landscape Orientation.LANDSCAPE landscape
Paginate.KeepNext Paginate::KeepNext Paginate.KEEP_NEXT keep-next
PdfALevel.Level2a PdfALevel::Level2a PdfALevel.LEVEL_2A 2a

A constant is its word, so Orientation.Landscape and 'landscape' are the same value, and the PDF is the same. A word that starts with a digit takes the last word of its constant’s name in front, since no language accepts a name that starts with one: Level2a in PdfALevel, Part1 in PdfUaPart, Version4 in PdfXVersion and Level0 to Level8 in Pdf417EcLevel.

In JavaScript the constants are exported by the package, import { Orientation } from '@lpdfio/lpdf', in Python by lpdf, from lpdf import Orientation, and in Java by io.lpdf, which import io.lpdf.*; brings in. In C# and PHP each is in the namespace of the elements that take it, Lpdf.Layout, Lpdf.Canvas, Lpdf.Kit or Lpdf.Engine, and in Lpdf.Shared where more than one place takes it: using Lpdf.Layout; in C#, use Lpdf\Layout\Paginate; in PHP. The code tabs of these docs show the imports of each example.

Constant Members For
Align Start, Center, End align of a cell; align and justify of a stamp
Anchor TopLeft, TopCenter, TopRight, CenterLeft, Center, CenterRight, BottomLeft, BottomCenter, BottomRight anchor of a layer shape, a text-at, an img-at and a barcode-at, and of a stamp
BarcodeType Qr, Code128, Ean13, Code39, Ean8, Upca, Datamatrix, Pdf417, Gs1128, Gs1Datamatrix type of a barcode
BoxAlign Start, Center, End, Stretch align of a column and a row
BoxJustify Start, Center, End, Between justify of a column and a row
BuiltinFont Courier, CourierBold, CourierOblique, CourierBoldOblique, Helvetica, HelveticaBold, HelveticaOblique, HelveticaBoldOblique, TimesRoman, TimesBold, TimesItalic, TimesBoldItalic, Symbol, ZapfDingbats core of a font
CaptureMode First, Last capture-mode of a text
CellVAlign Top, Middle, Bottom valign of a cell
Cipher Aes256, Rc4128 encrypt of the output
ColumnFill Auto, Balance column-fill of a section
DividerDirection Horizontal, Vertical direction of a divider
FieldType Text, Checkbox, Dropdown, Radio, Button type of a field
FileRelationship Source, Data, Alternative, Supplement, Unspecified relationship of a file
FillRule Nonzero, Evenodd fill-rule of a path
FootnoteCounter Page, Section, Document footnote-counter of a document and a section
GradientType Linear, Radial type of a gradient
Grow Width, Height, WidthHeight grow of a section
LineCap Butt, Round, Square line-cap of a line and a path
ListBullet Disc, Circle, Square, Dash bullet of a list and an item
ListFormat Decimal, LowerAlpha, UpperAlpha, LowerRoman, UpperRoman format of a list and page-format of a section
ListType Bullet, Number type of a list
Ocg Print, Screen ocg of an element, a layer and a ruling
Orientation Portrait, Landscape orientation of a document and a section
PageScope Each, First, Last, Odd, Even page of a layer and a region; a range stays a string
PageSize A0, A1, A2, A3, A4, A5, A6, B4, B5, Letter, Legal, Tabloid size of a document and a section; a custom size stays a string
Paginate No, BreakBefore, BreakAfter, KeepNext paginate
Pdf417EcLevel Level0, Level1, Level2, Level3, Level4, Level5, Level6, Level7, Level8 ec of a pdf417
PdfALevel Level2a, Level2b, Level2u, Level3a, Level3b, Level3u pdfa of the output
PdfUaPart Part1 pdfua of the output
PdfXVersion Version4 pdfx of the output
Permission All, Print, Modify, Copy, Annotate, FillForms, Accessibility, Assemble the words of allow of the output
Pin Top, Bottom, Left, Right, Inset pin of a region
QrEcLevel L, M, Q, H ec of a qr
RowKeep WithNext keep of a row
RulingOrigin Page, Margin origin of a ruling
SectionType Toc type of a section
ShapeType Rect, Circle, Ellipse type of a shape
StampScale Fit, Fill scale of a stamp
TextAlign Left, Center, Right, Justify align of a text, a text-at and the markdown rules
TextRole H1, H2, H3, H4, H5, H6 role of a text

These stay strings, since a constant is for a word a person chooses by name and an attribute that takes them takes more: a custom page size, such as 100pt 200pt, where PageSize names A0 to A6, B4, B5, Letter, Legal and Tabloid; a range of pages, such as 2-4, where PageScope names each, first, last, odd and even; and the slots xs to xxl and the keywords fill of a width and full and fill of a height, which an attribute that takes a length takes beside a length and an alias.

In TypeScript an attribute that takes one word of a constant has the constant’s type, so a word that is none of its values doesn’t compile: orientation: 'landscpe' is an error, and 'landscape' and Orientation.Landscape both pass. size takes a named size or a width and a height with their units, '210mm 297mm'. TypeScript checks that a custom size is two numbers, each with pt, mm or in, so '210mm' doesn’t compile. The numbers are checked when the document is rendered: a page under 3pt wide or high, such as '-5pt 3mm', is an error then. page, which takes a range beside its named words, and allow, which takes several words separated by spaces, are strings. A variable of type string needs a cast. In the other SDKs an attribute takes a string, and a word that is none of its values is an error when the document is rendered, which names the words it takes, as it does for XML: invalid orientation value: 'landscpe' — expected portrait or landscape.

The code tabs of these docs, and lpdf codegen, write a constant where the schema has one.