Read the text of a PDF
Pull the text out of a PDF the user picks, page by page, in the browser; nothing is uploaded.
AGPL-3.0-onlyRuns on this page
Package: @awacloud/oconv
Pick a PDF (or press "Try a sample"), extract its text in the page with
oconv.toMd, and show it page by page with the page count and the loss
ledger. Nothing is uploaded.
Uses @awacloud/oconv (AGPL-3.0-only) over @awacloud/fw (Apache-2.0). This example's code is AGPL-3.0-only.
When to use it
Getting at the words of a PDF people already have — a report to search, an invoice to file, a contract to quote — on their machine: the file is read into memory and its text extracted there, so a confidential document never reaches a server. The pages stay apart, so a quote can say where it came from, and the ledger says what the extraction could not read instead of hiding it.
Copy-paste steps
npm install @awacloud/oconv(it depends on@awacloud/fw,md,ooxml,odf,pdfandfonts).- Serve each package's
src/directory at/vendor/<name>/—fw,pdf,fonts,oconv,md,ooxml,odf— with any static server; the import map inindex.htmlpoints there. - 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. - Use
readText(name, bytes, convertedAt)on its own where you need the text: it returns{ pages, losses }, one string per page.
What it shows
- Wiring: one
ModuleRuntimeregisters@awacloud/oconv'sfw_requireandmodulesarrays;rt.resolve('oconv')is the façade, and becausemodulesalready carries@awacloud/pdf's graph,rt.resolve('pdfBuilder')builds the sample on the same runtime. - One reading path: the file input and the "Try a sample" button both
end in
show(name, bytes). The sample is two A4 pages of standard Helvetica, a title and a line each, built in the page withbuilder().addPage(…).addFont(…).addContent(…). - The extraction:
oconv.toMd({ name, bytes, convertedAt, engine })detects the format from the extension and returnsmarkdown(YAML front matter with provenance, then the text),lossyandlosses. The PDF reader writes each page boundary as a---thematic break, sosplitPagesdrops the front matter and cuts at those lines; each page's text is Markdown, its lines grouped into paragraphs. - The ledger: every
{ code, detail }the reader records (an undecodable glyph, a dropped image…) is listed; an empty ledger shows an explicit "no loss recorded" line. - Errors: an unsupported file (
.txt) showsoconv: unsupported format; a file named.pdfthat is not one shows the PDF reader's typedParseErrorascode: message(pdf/document/short: …). Either way the pages and the ledger are cleared and nothing is thrown at the page. - Not shown: the reader's options on
toMd(pdfInferfor headings, tables and running headers,pdfIncludefor images), scanned pages (an image has no text to extract: no OCR), and the oconv Web Worker entry for large files (oconv/worker-convert).
Code
main.js
// SPDX-License-Identifier: AGPL-3.0-only
import { ModuleRuntime } from '@awacloud/fw/core/runtime.js';
import { fw_require, modules } from '@awacloud/oconv';
const rt = new ModuleRuntime();
rt.registerAll([...fw_require, ...modules]); // `modules` carries @awacloud/pdf's graph, its builder included
const OCONV = rt.resolve('oconv');
const BUILDER = rt.resolve('pdfBuilder');
const A4 = [0, 0, 595.28, 841.89];
/** Two A4 pages of standard Helvetica, built in the page so it runs without a file. */
export function buildSample() {
const page = (/** @type {string} */ title, /** @type {string} */ line) =>
`BT /F1 24 Tf 72 770 Td (${title}) Tj ET BT /F1 12 Tf 72 730 Td (${line}) Tj ET`;
return BUILDER.builder()
.addPage({ mediaBox: A4 }).addFont({ name: 'F1', baseFont: 'Helvetica' })
.addContent(page('Quarterly report', 'Revenue grew this quarter.'))
.addPage({ mediaBox: A4 }).addFont({ name: 'F1', baseFont: 'Helvetica' })
.addContent(page('Next steps', 'Hire, then ship.'))
.build();
}
/**
* The text of each page of `toMd`'s Markdown: the YAML front matter goes, and
* each `---` line (the page boundary the PDF reader records) starts a new page.
* @param {string} markdown
*/
export const splitPages = (markdown) =>
markdown.replace(/^---\n[\s\S]*?\n---\n/, '').split(/^---$/m).map((page) => page.trim());
/**
* Extract the text of a PDF, in memory, page by page, with the loss ledger.
* @param {string} name the format comes from the extension (`.pdf`)
* @param {Uint8Array} bytes @param {string} convertedAt ISO-8601, recorded in the front matter
* @returns {Promise<{ pages: string[], losses: { code: string, detail: unknown }[] }>}
*/
export async function readText(name, bytes, convertedAt) {
const { markdown, losses } = await OCONV.toMd({ name, bytes, convertedAt, engine: 'browser' });
return { pages: splitPages(markdown), losses };
}
const input = /** @type {HTMLInputElement} */ (document.getElementById('file'));
const pages = /** @type {HTMLElement} */ (document.getElementById('pages'));
const losses = /** @type {HTMLElement} */ (document.getElementById('losses'));
const status = /** @type {HTMLElement} */ (document.getElementById('status'));
/** @param {HTMLElement} parent @param {string} tag @param {string} [text] */
const add = (parent, tag, text = '') =>
Object.assign(parent.appendChild(document.createElement(tag)), { textContent: text });
/** The one reading path, for a picked file and for the sample. @param {string} name @param {Uint8Array} bytes */
async function show(name, bytes) {
pages.replaceChildren();
losses.replaceChildren();
try {
const result = await readText(name, bytes, new Date().toISOString());
result.pages.forEach((text, i) => {
const section = add(pages, 'section');
add(section, 'h3', `Page ${i + 1}`);
add(section, 'pre', text || '(no text on this page)');
});
const ledger = result.losses.map(({ code, detail }) =>
`${code}: ${typeof detail === 'string' ? detail : JSON.stringify(detail)}`);
for (const line of ledger.length ? ledger : ['no loss recorded']) add(losses, 'li', line);
status.textContent = `${name}: ${result.pages.length} page(s)`;
} catch (err) {
const { code, message } = /** @type {Error & { code?: string }} */ (err); // a ParseError carries a code
status.textContent = `${name}: ${code ? `${code}: ` : ''}${message}`;
}
}
input.addEventListener('change', async () => {
const [file] = input.files ?? [];
if (file) await show(file.name, new Uint8Array(await file.arrayBuffer()));
});
document.getElementById('sample')?.addEventListener('click', () => show('sample.pdf', buildSample()));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>oconv · Read the text of a PDF</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/",
"@awacloud/oconv": "/vendor/oconv/main.js", "@awacloud/oconv/": "/vendor/oconv/",
"@awacloud/md": "/vendor/md/main.js", "@awacloud/md/": "/vendor/md/",
"@awacloud/ooxml": "/vendor/ooxml/main.js", "@awacloud/ooxml/": "/vendor/ooxml/",
"@awacloud/odf": "/vendor/odf/main.js", "@awacloud/odf/": "/vendor/odf/" } }
</script>
<script type="module" src="./main.js"></script>
</head>
<body>
<main>
<h1>Read the text of a PDF</h1>
<p>
<label for="file">PDF document</label>
<input id="file" type="file" accept=".pdf,application/pdf">
<button id="sample" type="button">Try a sample</button>
</p>
<p>The file never leaves the page: it is read in memory.</p>
<p id="status" aria-live="polite"></p>
<h2>Text, page by page</h2>
<div id="pages"></div>
<h2>Loss ledger</h2>
<ul id="losses"></ul>
</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>
<li>@awacloud/oconv · AGPL-3.0-only</li>
<li>@awacloud/md · AGPL-3.0-only</li>
<li>@awacloud/ooxml · AGPL-3.0-only</li>
<li>@awacloud/odf · AGPL-3.0-only</li>
</ul>
</footer>
<!-- aln:end -->
</body>
</html>