Build a PDF and read it back
Build a one-page PDF in the browser, read it back, and download it.
AGPL-3.0-onlyRuns on this page
Package: @awacloud/pdf
Build a one-page PDF from scratch (text and metadata), read it back (version, pages, media box, Info title and author), and download it.
Uses @awacloud/pdf (AGPL-3.0-only) over @awacloud/fw (Apache-2.0). This example's code is AGPL-3.0-only.
When to use it
Generating a small PDF in the browser or in a script without a rendering engine — a receipt, a label, a cover page — and checking what you produced by reading it back with the same package.
Copy-paste steps
npm install @awacloud/pdf(it depends on@awacloud/fwand@awacloud/fonts).- Serve
node_modules/@awacloud/fw/src/,node_modules/@awacloud/pdf/src/andnode_modules/@awacloud/fonts/src/at/vendor/fw/,/vendor/pdf/and/vendor/fonts/(node serve.jsfrom the examples root does this; any static server works). - Copy
index.htmlandmain.jsnext to each other and openindex.htmlthrough that server. The../../_style/examples.csslink is optional: copy that file along, or delete the link. Keep the legal notice under</main>: copy../../LICENSES/AGPL-3.0-only.txtalong, or point its link at your copy. - Write your own content stream in
buildSample:addContenttakes operator text (BT … ET),addFontregisters a standard font under the resource name the stream uses,addMetadatafills the Info dictionary.
What it shows
- Wiring: one
ModuleRuntimewith@awacloud/pdf'sfw_require,pkg_requireandmodulesarrays plus fw'sdownload; the modules used arepdf(read) andpdfBuilder. - Build:
pdfBuilder.builder().addPage({ mediaBox }).addFont({ name, baseFont }).addContent(text).addMetadata({ Title, Author }).build()returns the bytes of a%PDF-2.0file. A builder is single-use.addContenttakes raw content-stream operators, so the text of aTjis a PDF literal string:literal()escapes\,(and)in it, and the standard Helvetica covers Latin-1 text only. - Read back:
pdf.read(bytes)givesversion,pages[](each withmediaBox) and the typedtrailer;doc.info()gives the Info dictionary as decoded text (title,author, …), ornullwhen there is none. This example writes ASCII: the builder writes Info strings as given, and other characters belong in UTF-16BE with a byte-order mark, as the PDF text-string rule says. - Download:
download.bytes(bytes, name, 'application/pdf'). - Not shown: changing a file without rewriting it (see
pdf/incremental-update), embedded fonts and images (addFont({ embedded }),addImage), the cross-reference-stream writer, encryption (seepdf/encrypt) and signing (see the PAdES recipe).
Code
main.js
// SPDX-License-Identifier: AGPL-3.0-only
import { ModuleRuntime } from '@awacloud/fw/core/runtime.js';
import { download } from '@awacloud/fw/dom/fs/download.js';
import { fw_require, pkg_require, modules } from '@awacloud/pdf';
const rt = new ModuleRuntime();
rt.registerAll([...fw_require, ...pkg_require, ...modules, download]);
const PDF = rt.resolve('pdf');
const BUILDER = rt.resolve('pdfBuilder');
const DOWNLOAD = rt.resolve('download');
const A4 = [0, 0, 595.28, 841.89];
/** A PDF literal string escapes `\`, `(` and `)`; the standard Helvetica covers Latin-1 text. @param {string} s */
const literal = (s) => s.replace(/[\\()]/g, '\\$&');
/**
* One A4 page with a line of Helvetica and an Info dictionary.
* @param {{ title?: string, author?: string, line?: string }} [meta]
*/
export function buildSample(meta = {}) {
const { title = 'Quarterly report', author = 'Example author', line = 'Hello from the builder' } = meta;
return BUILDER.builder().addPage({ mediaBox: A4 }).addFont({ name: 'F1', baseFont: 'Helvetica' })
.addContent(`BT /F1 24 Tf 72 770 Td (${literal(line)}) Tj ET`)
.addMetadata({ Title: title, Author: author }).build();
}
/**
* Read a PDF back: header version, page count, first media box, Info title and author.
* @returns {{ version: string, pages: number, mediaBox: number[], title: string | null, author: string | null }}
*/
export function readSummary(/** @type {Uint8Array} */ bytes) {
const doc = PDF.read(bytes);
const info = doc.info(); // the Info dictionary as decoded text, or null
const [title, author] = [info?.title ?? null, info?.author ?? null];
return { version: doc.version, pages: doc.pages.length, mediaBox: doc.pages[0].mediaBox, title, author };
}
const summary = /** @type {HTMLElement} */ (document.getElementById('summary'));
let built = /** @type {Uint8Array | null} */ (null);
document.getElementById('build')?.addEventListener('click', () => {
built = buildSample();
const s = readSummary(built);
const rows = [
['Version', s.version], ['Pages', String(s.pages)], ['Media box', s.mediaBox.join(' ')],
['Title', s.title ?? '—'], ['Author', s.author ?? '—'], ['Bytes', String(built.length)],
];
summary.replaceChildren(...rows.flatMap(([term, value]) => {
const dt = document.createElement('dt');
const dd = document.createElement('dd');
dt.textContent = term;
dd.textContent = value;
return [dt, dd];
}));
/** @type {HTMLButtonElement} */ (document.getElementById('download')).disabled = false;
});
document.getElementById('download')?.addEventListener('click', () => {
if (built) DOWNLOAD.bytes(built, 'report.pdf', 'application/pdf');
});index.html
<!doctype html>
<!-- SPDX-License-Identifier: AGPL-3.0-only -->
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>pdf · Build a PDF and read it back</title>
<link rel="stylesheet" href="../../_style/examples.css">
<script type="importmap">
{ "imports": {
"@awacloud/fw": "/vendor/fw/main.js", "@awacloud/fw/": "/vendor/fw/",
"@awacloud/pdf": "/vendor/pdf/main.js", "@awacloud/pdf/": "/vendor/pdf/",
"@awacloud/fonts": "/vendor/fonts/main.js", "@awacloud/fonts/": "/vendor/fonts/" } }
</script>
<script type="module" src="./main.js"></script>
</head>
<body>
<main>
<h1>Build a PDF and read it back</h1>
<button id="build" type="button">Build the sample</button>
<button id="download" type="button" disabled>Download report.pdf</button>
<dl id="summary"></dl>
</main>
<!-- aln:begin (AGPL-3.0 sections 0, 5d and 13; derived by _harness/contract.js legalNotice, checked by C7) -->
<footer id="legal" aria-label="Legal notices">
<p>Copyright (c) 2026 AwaCloud SAS. This page is free software under the GNU Affero General Public License,
version 3 only (AGPL-3.0-only), with ABSOLUTELY NO WARRANTY:
<a href="../../LICENSES/AGPL-3.0-only.txt">licence text</a>.</p>
<p>It runs these packages, each with its own LICENSE and NOTICE file (third-party notices included):</p>
<ul>
<li>@awacloud/fw · Apache-2.0</li>
<li>@awacloud/pdf · AGPL-3.0-only</li>
<li>@awacloud/fonts · AGPL-3.0-only</li>
</ul>
</footer>
<!-- aln:end -->
</body>
</html>