Sign a PDF with PAdES in the browser (B-B)
Sign a PDF with a PAdES signature in the browser, verify it, and download it.
AGPL-3.0-onlyRuns on this page
Package: @awacloud/pdf
Build a one-page PDF, generate a throwaway Ed25519 identity with a self-signed certificate, sign it PAdES B-B, verify it, show that one changed byte fails, download the signed file. Nothing leaves the page.
Uses @awacloud/pdf (AGPL-3.0-only) over @awacloud/fw (Apache-2.0). This example's code is AGPL-3.0-only.
The certificate comes from fw's x509 module (RFC 5280, RFC 8410 for
Ed25519). It is a test identity for a demonstration: self-signed, valid
for a day, trusted by no one. A real deployment signs with a certificate
issued by a certification authority and brings its own key material.
When to use it
Signing a document on the user's machine without a signing server: a consent form, an order, a report the user downloads already signed. The whole flow — key, certificate, signature, verification — runs in the page, so the browser's network panel stays empty.
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); the import map inindex.htmlpoints there. - Copy
index.html,main.jsandidentity.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. - Replace
createIdentity()with your own key material:pdfSign.sign()takes the certificate as DER bytes or a PEM string and, for Ed25519, the 64-byte private key (seed followed by the public key). The package's PAdES integration guide documents the RSA-PSS and ECDSA key shapes and the PKCS#8 / PEM conversions fw publishes. Prefer ECDSA (P-256) when the signed file must validate in Adobe Acrobat Reader: Acrobat does not validate EdDSA (Ed25519) signatures; Ed25519 signatures are verified by OpenSSL 3.5.6 and by@awacloud/pdf.
What it shows
- Wiring: one
ModuleRuntimeregisters@awacloud/pdf'sfw_require,pkg_requireandmodulesarrays plus thepdfSigPadesextra and fw'sdownload, thenregisterAllDeep([x509])adds fw'sx509with the modules it needs that pdf does not bring; signing is only reachable this way (the read-only prebuilt bundles carry no signer). - The document:
pdfBuilder.builder()— a page, the Helvetica standard font, one content stream, an Info title —.build()returns the bytes. - The identity:
ed25519.keyPair(random.bytes(32)), a random positive serial, andx509.create(spec, signer): version 3,CN=Example signeras subject (the issuer defaults to it), a 24-hour validity window, the Ed25519 key, basicConstraints CA:false and keyUsage digitalSignature + nonRepudiation, signed with the same key. The test proves two identities of one run share neither key nor serial: nothing is stored in this directory. - Signing:
pdfSign.sign(bytes, { cert, privateKey, algorithm: 'ed25519', hashAlg: 'sha512', level: 'B', useSignedAttrs: true, subFilter: 'ETSI.CAdES.detached' })(RFC 8419: Ed25519 CMS signatures use SHA-512) appends the signature as an incremental update, so the original bytes are a prefix of the signed file. Produces PAdES-B (B-B) signatures in the browser; the signature has no visible appearance. - Verification:
pdfSignature.verifyAllSignatures(signed)reconstructs the PKCS#7, recomputes the/ByteRangedigest and verifies the signer's public-key signature — reported asverified. This is a cryptographic check, not signature validation per EN 319 102: no certificate chain, no revocation, no trust decision. The test flips one byte of the page text and the result turnsinvalidwith the package'spdf/sig/…error codes. - The level:
pdfSigPades.detectPadesProfile(sigDict, context)on the signature dictionary read back from the signed file (doc.resolvefollows the object number the verifier reports) givesB-B; the three context flags are derived from the bytes as the integration guide shows. - Not shown: levels T, LT and LTA (a timestamp needs a Timestamp Authority, a network service the package reaches only through a caller-supplied callback), key import from PKCS#12, visible signature appearances, signing with ECDSA (P-256) — the key shape Acrobat validates (see step 4).
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 { x509 } from '@awacloud/fw/crypto/utils/x509.js';
import { fw_require, pkg_require, modules, extras } from '@awacloud/pdf';
import { createIdentity as newIdentity } from './identity.js';
const rt = new ModuleRuntime();
rt.registerAll([...fw_require, ...pkg_require, ...modules, ...extras, download]); // extras carries pdfSigPades
rt.registerAllDeep([x509]); // and the fw modules it needs that pdf does not
const [PDF, BUILDER, SIGN, SIGNATURE, PADES, ED25519, RANDOM, X509, DOWNLOAD] = [
'pdf', 'pdfBuilder', 'pdfSign', 'pdfSignature', 'pdfSigPades', 'ed25519', 'random', 'x509', 'download',
].map((name) => rt.resolve(name));
/** One page, one line of text: the document to sign. @param {string} [line] */
export function buildSample(line = 'Signed in the browser') {
return BUILDER.builder().addPage().addFont({ name: 'F1', baseFont: 'Helvetica' })
.addContent(`BT /F1 18 Tf 72 720 Td (${line}) Tj ET`).addMetadata({ Title: 'PAdES sample' }).build();
}
/** A throwaway Ed25519 identity with its self-signed certificate (see identity.js). @param {string} [commonName] */
export const createIdentity = (commonName) => newIdentity({ ed25519: ED25519, random: RANDOM, x509: X509 }, commonName);
/** PAdES baseline B (B-B): a detached CAdES signature appended as an incremental update. */
export function signPdf(/** @type {Uint8Array} */ bytes, /** @type {ReturnType<typeof createIdentity>} */ identity) {
return SIGN.sign(bytes, {
cert: identity.cert, privateKey: identity.privateKey, algorithm: 'ed25519', hashAlg: 'sha512',
level: 'B', useSignedAttrs: true, subFilter: 'ETSI.CAdES.detached',
});
}
/**
* Cryptographic check of every signature (digest of the signed ranges, then the signer's public-key
* signature) and the PAdES level the package detects on its signature dictionary.
* @returns {{ valid: boolean, reason: string, level: string | null }[]}
*/
export function verifyPdf(/** @type {Uint8Array} */ signed) {
const doc = PDF.read(signed);
const text = new TextDecoder('latin1').decode(signed);
const context = {
hasSignatureTimestamp: /2A864886F70D010910020E/i.test(text), // the signature-timestamp attribute OID
dss: /\/DSS/.test(text),
hasDocTimestampOverDss: /\/DocTimeStamp/.test(text),
};
return SIGNATURE.verifyAllSignatures(signed).signatures.map((s) => ({
valid: s.verified,
reason: s.verified ? 'digest and signature check out' : s.errors.map((e) => e.code).join(', '),
// The signature dictionary, through the read document's public resolver.
level: PADES.detectPadesProfile(doc.resolve({ type: 'ref', num: s.objNum, gen: s.objGen }), context).level,
}));
}
const input = /** @type {HTMLInputElement} */ (document.getElementById('file'));
const saveButton = /** @type {HTMLButtonElement} */ (document.getElementById('download'));
/** @param {string} id @param {string} text */
const show = (id, text) => { /** @type {HTMLElement} */ (document.getElementById(id)).textContent = text; };
let signed = /** @type {Uint8Array | null} */ (null);
function run(/** @type {Uint8Array} */ bytes) {
try {
const identity = createIdentity();
show('identity', `CN=${identity.commonName}, Ed25519 — throwaway identity generated in this page`);
signed = signPdf(bytes, identity);
show('size', `${bytes.length} → ${signed.length} bytes`);
const [result] = verifyPdf(signed);
show('verification', result.valid ? 'valid' : `invalid: ${result.reason}`);
show('level', result.level ?? 'not a PAdES signature');
} catch (err) {
signed = null;
show('verification', `error: ${/** @type {Error} */ (err).message}`);
}
saveButton.disabled = signed === null;
}
document.getElementById('sign')?.addEventListener('click', () => run(buildSample()));
input.addEventListener('change', async () => {
const [file] = input.files ?? [];
if (file) run(new Uint8Array(await file.arrayBuffer()));
});
saveButton.addEventListener('click', () => { if (signed) DOWNLOAD.bytes(signed, 'signed.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 · Sign a PDF with PAdES in the browser (B-B)</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>Sign a PDF with PAdES in the browser (B-B)</h1>
<p>
<button id="sign" type="button">Sign a sample PDF</button>
or sign your own: <label for="file">PDF file</label> <input id="file" type="file" accept="application/pdf">
</p>
<dl>
<dt>Identity</dt><dd id="identity">—</dd>
<dt>Signed size</dt><dd id="size">—</dd>
<dt>Verification</dt><dd id="verification" aria-live="polite">—</dd>
<dt>Detected level</dt><dd id="level">—</dd>
</dl>
<p><button id="download" type="button" disabled>Download signed.pdf</button></p>
<p>Nothing leaves this page: the key, the certificate and the document stay in memory.</p>
</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>identity.js
// SPDX-License-Identifier: AGPL-3.0-only
// The identity half of the recipe: a key pair and the certificate that names it.
/**
* A fresh Ed25519 key pair and a self-signed X.509 v3 certificate from fw's
* `x509` module: a throwaway identity that lives in this page only. Nothing
* is stored or sent.
* @param {{ ed25519: any, random: any, x509: any }} m fw's resolved modules
* @param {string} [commonName]
*/
export function createIdentity({ ed25519, random, x509 }, commonName = 'Example signer') {
const { publicKey, privateKey } = ed25519.keyPair(random.bytes(32));
const serial = random.bytes(16);
serial[0] = (serial[0] & 0x7f) | 0x40; // a positive 128-bit integer
const notBefore = new Date();
const notAfter = new Date(notBefore.getTime() + 24 * 60 * 60 * 1000); // valid for one day
const cert = x509.create({
subject: { CN: commonName }, serial, notBefore, notAfter, // issuer defaults to subject: self-signed
publicKey: { alg: 'Ed25519', key: publicKey },
extensions: { basicConstraints: { ca: false }, keyUsage: ['digitalSignature', 'nonRepudiation'] },
}, { alg: 'Ed25519', privateKey });
if (!cert) throw new Error('x509: the certificate could not be created');
return { commonName, publicKey, privateKey, serial, cert };
}