Open in a new tab

Join two PDFs into one in the browser: every page of the first, then the pages of the second you choose, in the order you type them. Each page of the result is listed with its text, and the file downloads. Nothing is uploaded.

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

Putting a cover page in front of a report, appending the signed annex to a contract, keeping three pages of a long scan: the files stay on the user's machine, which matters when they are confidential.

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); the import map in index.html points there.
  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. Call pdfMerge.merge(sources) with as many sources as you need: each is a Uint8Array (all its pages) or { bytes, pages } (0-based indices).

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 pdfMerge, pdfBuilder (the two samples) and pdf (read back).
  • The merge: merge([first, { bytes: second, pages: [2, 0] }]) returns a new document of those pages in that order; a page given twice is copied twice. Each page comes with everything it uses (fonts, images), written once when several copied pages share it. The header version is the highest of the sources'.
  • Page numbers: people count from 1, merge from 0: parsePages("3, 1") gives [2, 0], and an empty field means every page.
  • Read back: pdf.read(bytes).pageContents(i) gives each page's content stream, decoded; the page lists the strings it shows (Tj), so the order is visible.
  • Errors: a page the second document does not have shows the package's pdf/merge/bad-page; an encrypted source is refused (pdf/merge/encrypted-source) rather than written out unencrypted.
  • Not carried: what belongs to a document rather than a page — outlines (bookmarks), the structure tree (tags), the Info dictionary, form fields (their widgets are dropped). A fillable form is filled before or instead of being merged (pdf/fill-form).

Code

main.js

javascriptAGPL-3.0-only77 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, BUILDER, MERGE, DOWNLOAD] = ['pdf', 'pdfBuilder', 'pdfMerge', 'download'].map((name) => rt.resolve(name));

/** A sample document: one A4 page per label, the label written on it. @param {string[]} labels */
export function buildSample(labels) {
    const doc = BUILDER.builder();
    for (const label of labels) {
        doc.addPage({ mediaBox: [0, 0, 595.28, 841.89] }).addFont({ name: 'F1', baseFont: 'Helvetica' })
            .addContent(`BT /F1 32 Tf 72 760 Td (${label}) Tj ET`);
    }
    return doc.build();
}

/**
 * "3, 1" → [2, 0]: the 1-based page numbers people type, as 0-based indices.
 * Empty means every page (`null`).
 * @param {string} text
 * @returns {number[] | null}
 */
export function parsePages(text) {
    const parts = text.split(',').map((s) => s.trim()).filter(Boolean);
    if (!parts.length) return null;
    return parts.map((s) => {
        if (!/^\d+$/.test(s) || Number(s) < 1) throw new Error(`"${s}" is not a page number`);
        return Number(s) - 1;
    });
}

/**
 * Merge: the whole of `first`, then the chosen pages of `second`, in that order.
 * @param {Uint8Array} first @param {Uint8Array} second @param {number[] | null} pages
 */
export const mergeTwo = (first, second, pages) => MERGE.merge([first, pages ? { bytes: second, pages } : second]);

/** What each page of a document says: the strings its content shows (`Tj`). @param {Uint8Array} bytes */
export function pageTexts(bytes) {
    const doc = PDF.read(bytes);
    const latin1 = new TextDecoder('latin1');
    return doc.pages.map((_, i) => [...latin1.decode(doc.pageContents(i)).matchAll(/\(([^)]*)\)\s*Tj/g)]
        .map((m) => m[1]).join(' '));
}

/** @type {Record<'first' | 'second', Uint8Array>} */
const sources = { first: buildSample(['A1', 'A2']), second: buildSample(['B1', 'B2', 'B3']) };
const el = (/** @type {string} */ id) => /** @type {HTMLElement} */ (document.getElementById(id));
const pagesInput = /** @type {HTMLInputElement} */ (el('pages'));
const saveButton = /** @type {HTMLButtonElement} */ (el('download'));
let merged = /** @type {Uint8Array | null} */ (null);

for (const key of /** @type {const} */ (['first', 'second'])) {
    const input = /** @type {HTMLInputElement} */ (el(key));
    input.addEventListener('change', async () => {
        const [file] = input.files ?? [];
        if (file) sources[key] = new Uint8Array(await file.arrayBuffer());
    });
}

el('merge').addEventListener('click', () => {
    try {
        merged = mergeTwo(sources.first, sources.second, parsePages(pagesInput.value));
        el('pages-out').replaceChildren(...pageTexts(merged).map((text, i) =>
            Object.assign(document.createElement('li'), { textContent: `page ${i + 1}: ${text || '(no text)'}` })));
        el('status').textContent = `${merged.length} bytes, ${PDF.read(merged).pages.length} page(s)`;
    } catch (err) {
        merged = null;
        const { code, message } = /** @type {Error & { code?: string }} */ (err);
        el('status').textContent = code ? `${code}: ${message}` : message;
    }
    saveButton.disabled = merged === null;
});
saveButton.addEventListener('click', () => { if (merged) DOWNLOAD.bytes(merged, 'merged.pdf', 'application/pdf'); });

index.html

htmlAGPL-3.0-only51 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 · Merge pages from two PDFs</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>Merge pages from two PDFs</h1>
    <p>Two samples are ready (A: pages A1, A2; B: pages B1, B2, B3); pick your own files to replace them.</p>
    <p>
      <label for="first">First PDF (all its pages)</label>
      <input id="first" type="file" accept=".pdf,application/pdf">
    </p>
    <p><label for="second">Second PDF</label> <input id="second" type="file" accept=".pdf,application/pdf"></p>
    <p>
      <label for="pages">Pages of the second, in order (empty for all)</label>
      <input id="pages" type="text" value="3, 1" inputmode="numeric">
    </p>
    <p>
      <button id="merge" type="button">Merge</button>
      <button id="download" type="button" disabled>Download merged.pdf</button>
    </p>
    <p id="status" aria-live="polite"></p>
    <ol id="pages-out"></ol>
  </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>