Open in a new tab

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

  1. npm install @awacloud/pdf (it depends on @awacloud/fw and @awacloud/fonts).
  2. Serve node_modules/@awacloud/fw/src/, node_modules/@awacloud/pdf/src/ and node_modules/@awacloud/fonts/src/ at /vendor/fw/, /vendor/pdf/ and /vendor/fonts/ (node serve.js from the examples root does this; any static server works).
  3. Copy index.html and main.js next to each other and open index.html through that server. The ../../_style/examples.css link is optional: copy that file along, or delete the link. Keep the legal notice under </main>: copy ../../LICENSES/AGPL-3.0-only.txt along, or point its link at your copy.
  4. Write your own content stream in buildSample: addContent takes operator text (BT … ET), addFont registers a standard font under the resource name the stream uses, addMetadata fills the Info dictionary.

What it shows

  • Wiring: one ModuleRuntime with @awacloud/pdf's fw_require, pkg_require and modules arrays plus fw's download; the modules used are pdf (read) and pdfBuilder.
  • Build: pdfBuilder.builder().addPage({ mediaBox }).addFont({ name, baseFont }).addContent(text).addMetadata({ Title, Author }).build() returns the bytes of a %PDF-2.0 file. A builder is single-use. addContent takes raw content-stream operators, so the text of a Tj is a PDF literal string: literal() escapes \, ( and ) in it, and the standard Helvetica covers Latin-1 text only.
  • Read back: pdf.read(bytes) gives version, pages[] (each with mediaBox) and the typed trailer; doc.info() gives the Info dictionary as decoded text (title, author, …), or null when 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 (see pdf/encrypt) and signing (see the PAdES recipe).

Code

main.js

javascriptAGPL-3.0-only58 lines

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

htmlAGPL-3.0-only38 lines

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