Read, write, sign and verify PDF documents in plain JavaScript, in the browser: a typed PDF 2.0 object model, a from-scratch builder, encryption and PAdES signatures.
Pure JavaScript library to read and write PDF documents in the browser, with
no runtime dependency beyond
@awacloud/fw
and
@awacloud/fonts.
The reference is ISO 32000-2:2020 (PDF 2.0); PDF 1.x files
are read too. pdf.write emits a %PDF-2.0 header; pdfBuilder.setVersion
and pdfWriter.writeDocument({ version }) emit the header they are given
(for example %PDF-1.7). Objects are re-emitted as read, not converted.
The core reads the file structure (classical cross-reference tables,
cross-reference streams, object streams, incremental updates) into a typed
object graph, and types the document layer on top of it: pages, resources,
content streams, fonts (parsing delegated to @awacloud/fonts), AcroForm,
annotations, Tagged PDF, optional content, outlines, actions, destinations,
embedded files, metadata and prepress boxes. It writes documents from a read
model or from scratch (pdfBuilder), as an incremental update, with
cross-reference streams, or encrypted with the standard security handler. It signs and verifies
PKCS#7 / PAdES signatures (levels B, T, LT, LTA) with public-key verification
through @awacloud/fw/crypto/* (synchronous, worker-safe, no Web Crypto). An
opt-in layer (extra/*) adds the long tail of PDF 2.0 and PDF 1.7 legacy
reading, grouped into the bundles pdf-large, pdf-full and pdf-legacy.
Known limits, so they are not a surprise:
- The whole file must be in memory as a
Uint8Array; there is no streaming reader. - An encrypted file read with no
passwordis opened with the empty one when it opens (recordedpdf/document/opened-with-empty-password, with the permission bits), and refused (pdf/document/encrypted) when it does not, unless you passpassword(decrypting read: the Standard handler V=4 R=4, V=5 R=5 and V=5 R=6; RC4 V=1 / V=2 through the opt-inlegacyRc4) or opt in to the raw ciphertext container withallowEncrypted: true.emptyPassword: falserefuses every encrypted file read with no password; see Reading options. - A FlateDecode stream is inflated to at most 256 MiB (
pdfFlate.limits): past thatpdf/flate/output-limitis thrown instead of a decompression bomb filling memory.pdfFlate.decode(bytes, params, { maxOutput })sets another ceiling (0disables it); seedocs/api/syntax/filters/flate.md. - Content streams are parsed to an operator list, not rendered.
writere-emits the objects it is given: it does not convert legacy content (XFA, RC4 encryption, LZW streams, Sound / Movie annotations) to PDF 2.0 equivalents.- JBIG2 is read at the segment-header level only (no image decode), and the linearization extra builds the linearization dictionary and a hint-stream placeholder, not a linearized file.
Installation
npm install @awacloud/pdf
In the browser, via import map:
<script type="importmap">
{ "imports": {
"@awacloud/fw": "/node_modules/@awacloud/fw/src/main.js",
"@awacloud/fw/": "/node_modules/@awacloud/fw/src/",
"@awacloud/fonts": "/node_modules/@awacloud/fonts/src/main.js",
"@awacloud/fonts/": "/node_modules/@awacloud/fonts/src/",
"@awacloud/pdf": "/node_modules/@awacloud/pdf/src/main.js",
"@awacloud/pdf/": "/node_modules/@awacloud/pdf/src/"
}}
</script>
Quick Start
In the snippets below, bytes is a Uint8Array holding a PDF file.
Stand-alone (without the @awacloud/fw runtime)
pdf (src/pdf.js) is a factory descriptor whose factory takes its
dependencies as positional arguments, so import { pdf } from '@awacloud/pdf'
cannot be invoked on its own. The zero-ceremony path is the committed
dist/standalone build, whose pdf root has every dependency inlined and is
invocable with no arguments:
import { pdfBundled } from '@awacloud/pdf/standalone/pdf.js';
const api = pdfBundled.factory();
const doc = api.read(bytes); // Uint8Array → typed model
console.log(doc.version); // header version, e.g. "1.5" or "2.0"
console.log(doc.pages.length); // number of pages
console.log(doc.pages[0].mediaBox); // the page's own /MediaBox, or null when inherited
const out = api.write(doc); // → Uint8Array, %PDF-2.0
console.log(api.read(out).pages.length); // the written file reads back
api.write(doc) re-emits the read model's indirect object graph in canonical
form: %PDF-2.0 header, sequential objects, classical cross-reference table,
trailer. A %PDF-2.0 file requires the trailer /ID (ISO 32000-2
Table 15), so when the model carries none, write (and pdfBuilder without
setId) derives one: both halves are the first 16 bytes of the SHA-256 of the
bytes written before the trailer, so the same input still gives the same bytes.
An explicit /ID is written as given and another version gets none; the
cross-reference-stream writer (pdfXrefStreamWriter) derives none. PDF 2.0
also requires FirstChar, LastChar, Widths and a FontDescriptor on every
simple font, the Standard 14 included: pdfBuilder.addFont({ name, baseFont, encoding, standard14 }) writes them from the @awacloud/fonts
standard14Lookup metrics when you pass it, and keeps the legacy bytes
otherwise (docs/api/document/builder.md).
The layered dist/standalone roots (pdf-large, pdf-full,
pdf-legacy and the four -rw roots) are invocable the same way as pdf — see
Committed dist below.
With the @awacloud/fw runtime
import { ModuleRuntime } from '@awacloud/fw/core/runtime.js';
import { fw_require, modules } from '@awacloud/pdf';
const rt = new ModuleRuntime();
for (const m of fw_require) rt.register(m);
for (const m of modules) rt.register(m);
const api = rt.resolve('pdf');
const doc = api.read(bytes);
console.log(doc.pages.length);
.use(...) hook (idempotent extension)
import { pdfBundled } from '@awacloud/pdf/standalone/pdf.js';
const api = pdfBundled.factory();
api.use({
name: 'my-extra',
register(self) {
return {
countAnnots: (b) => self.read(b).pages
.reduce((n, p) => n + p.annots.length, 0)
};
}
});
console.log(api.countAnnots(bytes));
console.log(api.usedExtension('my-extra')); // true
.use() is idempotent by name: applying the same extension twice is a
no-op.
With a bundle (extras wired automatically)
Bundles are module descriptors, consumed through a ModuleRuntime:
import { ModuleRuntime } from '@awacloud/fw/core/runtime.js';
import { fw_require, pkg_require, modules, extras, bundle } from '@awacloud/pdf';
const rt = new ModuleRuntime();
for (const m of fw_require) rt.register(m);
for (const m of pkg_require) rt.register(m);
for (const m of modules) rt.register(m);
for (const m of extras) rt.register(m);
for (const m of bundle) rt.register(m);
const api = rt.resolve('pdfLargeBundle');
const doc = api.read(bytes);
console.log(doc.pages.length);
// Each wired extra is reachable under its factory name:
console.log(api.usedExtension('pdfAOutputIntent')); // true
console.log(api.pdfAOutputIntent.PDFA_PROFILES['2b'].iso); // 'ISO 19005-2:2011'
Reading cross-reference forms
api.read(bytes) accepts classical (xref table) and PDF 1.5+
cross-reference-stream (/Type /XRef, §7.5.8) sections — mixed /Prev
chains and hybrid-reference files (a classical trailer carrying /XRefStm)
resolve end to end, and objects held in a /Type /ObjStm container (§7.5.7)
are materialised on demand. /DecodeParms (e.g. a PNG predictor on a
cross-reference stream) reach the decoders as plain parameters and are
honoured, and an indirect /ExtGState (or other resource category) on a page
does not drop the whole resource map. A non-catalog object that is free but
still referenced degrades to a recorded entry in doc.losses instead of
throwing (a free /Root is still refused); appendIncremental extends a
cross-reference-stream base with an uncompressed /Type /XRef section.
Reading options
api.read(bytes, opts) and pdfDocument.readDocument(bytes, opts) take
the options below; each is off by default, and a read given none of them is
unchanged.
| Option | Default | Effect |
|---|---|---|
password |
none | Opens an encrypted document: a string or bytes ('' is the empty user password). The Standard handler V=4 R=4, V=5 R=5 or V=5 R=6 is applied, the password tried as the user, then as the owner password, and every string and stream is decrypted as it is read. Without it the empty password is tried (emptyPassword), and a document it does not open throws pdf/document/encrypted; a wrong one pdf/document/bad-password. Ignored on an unencrypted document. |
emptyPassword |
true |
With no password, an encrypted document is opened with the empty one when it opens, recorded pdf/document/opened-with-empty-password in doc.losses (context: permissions, the /P bits). false throws pdf/document/encrypted on every encrypted document read with no password. |
legacyRc4 |
none | The opt-in pdfLegacyRc4Read instance, which decrypts an RC4 V=1 / V=2 document (R2, R3) under password. The pdf-legacy bundle's read passes its own. |
fastCipher |
false |
With password: routes the key check and the AES-CBC decryption through fw's T-table AES (a 30-page R6 file reads in about 25 ms instead of 0.9 s). Not constant-time: for a trusted, single-user host only. |
allowEncrypted |
false |
true returns the raw ciphertext container of an encrypted document instead of throwing (an object stream's members cannot be read there). password wins over it. |
sourceWindow |
65,536 | With a byte source { byteLength, read(offset, length) } given in place of the bytes (the file read by windows, never held whole): the first window's size in bytes, doubled while a parse runs out of it, up to the parser's maxStreamBytes plus 64 KiB (pdf/document/source-window). A source whose cross-reference chain fails is read whole once for the rebuild (recoverXref). |
recoverXref |
true |
rebuilds a cross-reference chain the reader cannot use (a wrong offset, an undecodable cross-reference stream, no startxref, a trailer without /Root) from the file's bytes and records pdf/document/xref-rebuilt in doc.losses; a byte source whose chain fails is read whole for it. false reads strictly, the chain's error thrown. Signing and the AcroForm fill read their base strictly. |
// Reuses `api` and `bytes` of the Quick Start; `encrypted` is a password-protected file.
const doc = api.read(encrypted, { password: 'user', fastCipher: true });
console.log(doc.pages.length);
Two classic cross-reference table shapes that real producers write — a
subsection header ending with spaces or tabs, and 19-byte entries — are read
without any option; each is recorded once as pdf/document/xref-tolerated in
doc.losses. The full reference is
docs/api/document/document.md.
Titles
The Info dictionary's strings (typeInfo's title, author …) are the
strings' bytes as read. pdfInfo.decodeTextString(bytes) turns a text string
into a JavaScript string — UTF-16BE after its byte order mark (language
escapes removed), UTF-8 after its BOM, else PDFDocEncoding. The opt-in
pdfXmpExtended.dcTitle(packet) returns an XMP packet's dc:title (its
x-default alternative, else the first, else a leaf value), which the leaf
harvest of parsePacket does not reach.
// Resolved from a `ModuleRuntime` with the core modules and `extras` registered.
const info = rt.resolve('pdfInfo');
console.log(info.decodeTextString(new Uint8Array([0xfe, 0xff, 0x00, 0x41, 0x20, 0xac]))); // 'A€'
console.log(rt.resolve('pdfXmpExtended').dcTitle(xmpPacket)); // 'Hello'
Bundles
src/main.js exports the five descriptor arrays (fw_require,
pkg_require, modules, extras, bundle) and every modules descriptor
by binding name; the extras and bundle descriptors are not exported
individually from the root, so import { pdfLargeBundle } from '@awacloud/pdf'
is undefined — register the arrays as above, or import one bundle from its
own sub-path (@awacloud/pdf/pdf-large, @awacloud/pdf/pdf-full,
@awacloud/pdf/pdf-legacy).
pdfLargeBundle— the core plus the P0 and P1 extras (common PDF 2.0 features).pdfFullBundle—pdf-largeplus the P2 and P3 extras, including the opt-in action sandbox linter.pdfLegacyBundle—pdf-fullplus the PDF 1.7 legacy readers (XFA, RC4, deprecated filters, deprecated multimedia annotations).
Each bundle's extras are listed literally in its descriptor's
dependencies; see docs/api/bundles/ for the
per-bundle tables.
Committed dist — two build surfaces
For consumers who don't want to hand-assemble the fw_require / modules
manifest, dist/ ships a committed, pre-generated build: an 8-root matrix
crossing the four assembly roots (pdf, pdf-large, pdf-full,
pdf-legacy, the Read family) with four -rw roots (pdf-rw,
pdf-large-rw, pdf-full-rw, pdf-legacy-rw, the Read+Write family —
each Read root plus the write inventory, including pdfXrefStreamWriter, and
the signature verifier pdfSignature beside the signer), in two
path-discriminated surfaces:
| Surface | Path | Contents |
|---|---|---|
dist/build/ |
@awacloud/pdf/build/<root> |
fw-mode: declares its @awacloud/fw modules as dependencies (DI-injected), needs an @awacloud/fw runtime; a -rw root also declares @awacloud/fonts' standard14Lookup and encodingLookup, so register pkg_require (fonts' manifest) too |
dist/standalone/ |
@awacloud/pdf/standalone/<root> |
framework-free: every reachable fw factory inlined in the body, @awacloud/fonts' lookups included in the -rw roots, zero runtime dependency (Worker-serializable) |
Each root emits a .js / .min.js / .meta.json triplet (e.g.
dist/build/pdf-large.js, pdf-large.min.js, pdf-large.meta.json), plus a
single dist/build/index.js barrel re-exporting the whole src/main.js
namespace (the five registration arrays and every named descriptor) for
registration on an @awacloud/fw runtime. Each .meta.json sidecar records
the root's modules, fwDependencies (read back from the generated
descriptor, never hardcoded), for a dist/build -rw root the
siblingDependencies it declares from @awacloud/fonts, and build byte
sizes. See
docs/api/bundles/dist-matrix.md for the
8-root × 2-surface table, the -rw naming scheme and the write inventory.
Idempotence: bun run gen:bundles (tools/generate-bundles.mjs) produces
byte-identical output across runs (no build stamp; every .js / .min.js
opens with the /*! … */ licence banner at byte 0). It is a thin wrapper
around @awacloud/tool-prebuild-generator, a build tool of the source
monorepo that is not published.
Invocability: every dist/standalone root is invocable with no
arguments, the layered ones included — each layered extra is registered
through the { name, register } envelope pdf.use() requires, so
pdfRwBundled.factory() returns a core on which
core.usedExtension('pdfSign') and core.usedExtension('pdfSignature') are
both true and core.pdfSignature.verifySignature is callable. The
dist/build roots need an @awacloud/fw runtime to inject their declared
dependencies: fw_require, plus pkg_require (@awacloud/fonts' manifest)
for the -rw roots, which declare standard14Lookup and encodingLookup
instead of inlining them.
Source structure
src/
├── main.js — entry point: the five descriptor arrays + named descriptors
├── pdf.js — top-level api (read, header, write, use, usedExtension)
├── errors.js — `pdfErrors` (PdfError + ParseError / RenderError /
│ ContractError / EncryptionError + isPdfError)
├── _shared/ — `pdfShared` byte constants and stateless helpers
├── syntax/ — tokenizer, parser, serializer, xref, trailer,
│ object streams, cross-reference streams, filters/
├── document/ — catalog, page tree, document reader, writers
│ (classical, builder, incremental, xref-stream, encrypted)
├── content/ font/ form/ annot/ tagged/ ocg/ outline/ destination/ action/
├── embedded/ associatedFiles/ linearization/ metadata/ prepress/
├── crypto/ — security handlers V4 / V5 / V6, permissions, AES-GCM
├── sig/ — signature typing + verification, signing, ByteRange,
│ RFC 3161 timestamps, certificate chains, DSS
├── extra/ — opt-in extras (P0–P3 + legacy)
└── bundles/ — pdf-large, pdf-full, pdf-legacy descriptors
Documentation
| Guide | Link |
|---|---|
| Getting started | docs/guide/getting-started.md |
| Read pipeline | docs/guide/read-pdf.md |
Extending via .use() |
docs/guide/extending.md |
| Coverage | docs/guide/coverage.md |
| PDF 1.7 legacy reading | docs/guide/legacy-1.7.md |
| Crypto — risks and limitations | docs/guide/crypto.md |
| PAdES signing and verification | docs/guide/pades-integration.md |
API per module: docs/api/README.md. Sibling package
with the same factory + bundles layout:
@awacloud/ooxml.
Tests
$ bun test packages/front/office/pdf/
Co-located unit tests (*.test.js next to each source file) plus integration
suites under tests/, among them:
tests/roundtrip.integration.test.js— wiring via the@awacloud/fwModuleRuntime, read → write → read, worker transportability of every factorytests/legacy-conversion.test.js— PDF 1.x read tolerancetests/fuzz.test.js— garbage and truncated input → typedParseErrortests/_helpers/build.js— shared fixture builder
Design choices
- Plain binary format — no ZIP (unlike
@awacloud/ooxmland@awacloud/odf). The PDF container is its own format:%PDF-2.0header + indirect objects + cross-reference section + trailer. - Worker-safe — each factory is self-sufficient (serializable via
factory.toString()). Constants are inlined in the body, no mutable module-level closure. - No external dependency —
@awacloud/fwand@awacloud/fontsonly. Codecs that@awacloud/fwdoes not provide (the simple filters, RC4, CCITT fax) are implemented in this package. - Typed errors — no raw
throw new Error(...); onlyPdfErrorand its subclasses, with a stable kebab-casecodeand a structuredcontext. The classes are not exported at the top level: they are declared inside thepdfErrorsfactory body, so eachpdfErrors.factory()call creates a fresh set of classes. ResolvepdfErrorsthrough oneModuleRuntime(which caches the instance) to share class identities across consumers; across two separatefactory()calls,instanceofdoes not hold — comparee.codeinstead.
Exposed sub-paths
| Sub-path | Target | Usage |
|---|---|---|
@awacloud/pdf |
src/main.js |
entry point — the five descriptor arrays + every core descriptor by name |
@awacloud/pdf/pdf |
src/pdf.js |
the top-level pdf descriptor only |
@awacloud/pdf/errors |
src/errors.js |
the pdfErrors descriptor (resolves PdfError + 4 subclasses) |
@awacloud/pdf/serializer |
src/syntax/serializer.js |
the pdfSerializer descriptor (typed object → bytes) |
@awacloud/pdf/filters/*.js |
src/syntax/filters/*.js |
stream filters by file name with the .js suffix, e.g. @awacloud/pdf/filters/ascii85.js |
@awacloud/pdf/filters/* |
src/syntax/filters/*.js |
stream filters (flate, asciiHex, ascii85, runLength, dispatch); resolved by Bun/Node through the exports map |
@awacloud/pdf/annot/*.js |
src/annot/*.js |
annotations by file name with the .js suffix, e.g. @awacloud/pdf/annot/annot.js |
@awacloud/pdf/annot/* |
src/annot/*.js |
annotations (text, link, markup, widget, redact, …); resolved by Bun/Node through the exports map |
@awacloud/pdf/tagged/*.js |
src/tagged/*.js |
Tagged PDF by file name with the .js suffix |
@awacloud/pdf/tagged/* |
src/tagged/*.js |
Tagged PDF (structure tree, elements, parent tree, …); resolved by Bun/Node through the exports map |
@awacloud/pdf/crypto/*.js |
src/crypto/*.js |
encryption by file name with the .js suffix |
@awacloud/pdf/crypto/* |
src/crypto/*.js |
encryption (security handlers V4 / V5 / V6, permissions, AES-GCM); resolved by Bun/Node through the exports map |
@awacloud/pdf/sig/*.js |
src/sig/*.js |
signatures by file name with the .js suffix |
@awacloud/pdf/sig/* |
src/sig/*.js |
signatures (verify, sign, ByteRange, RFC 3161, certificate chain, DSS); resolved by Bun/Node through the exports map |
@awacloud/pdf/ocg/*.js |
src/ocg/*.js |
optional content by file name with the .js suffix |
@awacloud/pdf/ocg/* |
src/ocg/*.js |
optional content (OCG + configuration); resolved by Bun/Node through the exports map |
@awacloud/pdf/action/*.js |
src/action/*.js |
actions by file name with the .js suffix |
@awacloud/pdf/action/* |
src/action/*.js |
actions (GoTo, URI, Named, Launch, …); resolved by Bun/Node through the exports map |
@awacloud/pdf/embedded/*.js |
src/embedded/*.js |
embedded files by file name with the .js suffix |
@awacloud/pdf/embedded/* |
src/embedded/*.js |
embedded files (file specification, embedded file, collection); resolved by Bun/Node through the exports map |
@awacloud/pdf/metadata/*.js |
src/metadata/*.js |
metadata by file name with the .js suffix |
@awacloud/pdf/metadata/* |
src/metadata/*.js |
metadata (Info dictionary, XMP); resolved by Bun/Node through the exports map |
@awacloud/pdf/prepress/*.js |
src/prepress/*.js |
prepress by file name with the .js suffix |
@awacloud/pdf/prepress/* |
src/prepress/*.js |
prepress (output intents, page boundaries); resolved by Bun/Node through the exports map |
@awacloud/pdf/extra/*.js |
src/extra/*.js |
opt-in extra descriptors by file name with the .js suffix |
@awacloud/pdf/extra/* |
src/extra/*.js |
opt-in extra descriptors (P0–P3 + legacy); resolved by Bun/Node through the exports map |
@awacloud/pdf/bundles/*.js |
src/bundles/*.js |
bundle descriptors by file name with the .js suffix |
@awacloud/pdf/bundles/* |
src/bundles/*.js |
bundle descriptors (pdf-large, pdf-full, pdf-legacy); resolved by Bun/Node through the exports map |
@awacloud/pdf/pdf-large |
src/bundles/pdf-large.js |
the pdfLargeBundle descriptor |
@awacloud/pdf/pdf-full |
src/bundles/pdf-full.js |
the pdfFullBundle descriptor |
@awacloud/pdf/pdf-legacy |
src/bundles/pdf-legacy.js |
the pdfLegacyBundle descriptor |
@awacloud/pdf/build/* |
dist/build/* |
committed fw-mode build — Read roots (pdf, pdf-large, pdf-full, pdf-legacy), Read+Write roots (pdf-rw, pdf-large-rw, pdf-full-rw, pdf-legacy-rw), and the index.js barrel |
@awacloud/pdf/standalone/* |
dist/standalone/* |
committed framework-free build, same 8 roots |
The src/document/* modules (writers, builder, catalog, pages, resources)
have no sub-path of their own: they are reached through the root entry's
named descriptors.
Maturity
L4 (awa.maturity in package.json): the package covers its declared
surface, within the limits listed above, and ships a test suite and
per-module reference pages.
Licence
AGPL-3.0-only — see LICENSE. The package is also available
under a commercial licence; see NOTICE.
Copyright (c) 2026 AwaCloud SAS
Project
- Website: https://awaforge.eu/
- Source:
packages/front/office/pdf - Issues: https://github.com/awacloud/awa/issues
- Security policy: https://github.com/awacloud/awa/blob/@awacloud/pdf@2.0.0/SECURITY.md
Relations
Depends on
Used by
Install
npm install @awacloud/pdf@2.0.0Source
https://github.com/awacloud/awa
Directory: packages/front/office/pdf