onex-pdf
v1.4.0
Published
Universal lightweight multilingual PDF engine - Chromium rendering, Unicode 16 pipeline, font subsetting, and size optimization.
Maintainers
Readme
ONEX renders any language — Hindi, Arabic, Urdu, Chinese, Japanese, Korean, Thai, Hebrew, emoji, and 160+ Unicode scripts — into small, valid, searchable PDFs, then optimizes, merges, splits, watermarks, and verifies them with its own pure-TypeScript PDF pipeline.
"माँ — Invoice ₹१२,३४५.५० — مرحبا — こんにちは — 😀 👨👩👧👦 🇮🇳"Why ONEX?
| Concern | ONEX Approach |
| --- | --- |
| Text shaping | Chromium / HarfBuzz — Indic conjuncts, Arabic joining, and bidi rendered natively and verified |
| Unicode 16 pipeline | Tables generated from official Unicode 16.0 UCD (scripts, grapheme clusters, emoji properties) |
| Smaller PDFs | Custom optimizer: object-stream packing, stream + resource deduplication, reachability pruning, and recompression (~17–21% smaller, text stays searchable) |
| Pure-JS PDF toolkit & compliance | Collision-free mergePdfs(), extractPages(), splitPdf(), watermarkPdf(), table/invoice & GSTIN extraction (extractTables(), extractInvoiceData(), isValidGstin()), inspectScanQuality(), verifyPdfSignatures(), and PDF/A-1b/PDF/A-2b (validatePdfA(), enforcePdfA()) |
| Multilingual & legacy fonts | Bundled Latin, Devanagari, Bengali, Tamil, Arabic, and ₹ Noto fonts, RTL bidi handling, plus krutiDevToUnicode() / chanakyaToUnicode() converters |
| Drop-in migration | onex-pdf/puppeteer adapter lets existing Puppeteer code switch with a 1-line import change |
| POS & Batch ready | Native 80mm / 58mm thermal receipt presets + bounded parallel engine.renderBatch() |
| Server & AI tools | Built-in onex serve HTTP microservice (+ Dockerfile), onex mcp stdio MCP server, and onex doctor |
| Zero browser bloat | ~3 MB + bundled Noto fonts (~1.7 MB) with a single runtime dependency (playwright-core); uses your existing Chrome/Chromium |
| Fail-closed security | file:// off, private-network + IPv4-mapped IPv6 SSRF blocked, root-prefix containment, unsafe Chromium flags refused |
Installation
npm install onex-pdfAlso available on GitHub Packages as @bahubalisid/onex-pdf:
npm install @bahubalisid/onex-pdf --registry=https://npm.pkg.github.com/Browser setup & diagnostics
No browser is downloaded during npm install. Point ONEX at any Chrome/Chromium, or check your host environment in one command:
npx onex doctorexport ONEX_CHROME_PATH=/path/to/chrome
# or install Playwright's Chromium binary once:
npx playwright install chromiumQuick Start
import { ONEX } from "onex-pdf";
const engine = await ONEX.launch({ backend: "chromium" });
const doc = await engine.createDocument();
await doc.setContent(`
<h1>माँ</h1>
<p>Invoice ₹१२,३४५.५० — مرحبا — こんにちは — 😀</p>
`);
const buffer = await doc.toBuffer({ format: "A4", optimize: "balanced" });
await doc.save("invoice.pdf");
await engine.close();Thermal POS Receipt (80mm / 58mm) & Batch Rendering
// 80mm / 58mm automatically enable singlePage continuous height with 0 margins
const receipt = await doc.toBuffer({ format: "80mm", optimize: "balanced" });
// Bounded parallel batch rendering (clamped to security.maxConcurrency)
const batch = await engine.renderBatch(
[
{ html: "<h1>Bill #101</h1>", options: { format: "A4" } },
{ html: "<h1>Bill #102</h1>", options: { format: "80mm" } },
],
{ concurrency: 4 },
);1-Line Puppeteer Drop-In Migration
Switch existing Puppeteer PDF/screenshot workflows by changing just your import:
import puppeteer from "onex-pdf/puppeteer";
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.setContent("<h1>नमस्ते ONEX</h1>");
await page.pdf({
path: "invoice.pdf",
format: "A4",
printBackground: true,
optimize: "balanced",
});
await browser.close();Supports newPage(), goto(), setContent(), waitUntil: "networkidle0" | "networkidle2", waitForTimeout(), $(), $$(), pdf(), screenshot(), click(), type(), fill(), evaluate(), $eval(), $$eval(), waitForSelector(), waitForFunction(), setRequestInterception(), setViewport(), emulateMediaType(), cookies(), setExtraHTTPHeaders(), and exposeFunction() — while preserving ONEX's fail-closed security defaults.
PDF Post-Processing (Pure JS)
Manipulate any PDF buffer without launching Chromium:
import { mergePdfs, extractPages, splitPdf, watermarkPdf } from "onex-pdf";
// Merge PDFs with cross-document font/image stream deduplication
const merged = mergePdfs([pdfA, pdfB], { title: "Monthly Invoices", deduplicateResources: true });
// Stamp a diagonal or positioned watermark safely
const stamped = watermarkPdf(merged.bytes, {
text: "PAID",
opacity: 0.2,
angle: 45,
position: "diagonal",
});
// Extract specific pages or split into chunks
const summary = extractPages(stamped, "1,3-4");
const parts = splitPdf(stamped, { chunkSize: 1 });Live-Page Interactive API
Every ONEXDocument owns a persistent, isolated browser page that you can drive programmatically before printing (toBuffer() / pdf()):
const doc = await engine.createDocument();
await doc.setContentLive(invoiceHtml);
await doc.waitForSelector("#invoice");
await doc.fill("#customer-note", "धन्यवाद!");
await doc.click("#apply-discount");
await doc.waitForFunction(() => window.invoiceReady === true);
const pdfBuffer = await doc.toBuffer({ optimize: "balanced" });
const screenshot = await doc.screenshot({ type: "png", fullPage: true });- Engine:
ONEX.launch(),ONEX.doctor(),engine.createDocument(),engine.renderBatch(),engine.getVersion(),engine.getCapabilities(),engine.fonts,ONEX.inspectFont(),engine.close() - Document:
setContent(),setHTML(),setURL(),setLanguage(),setMetadata(),setMargins(),setPageSize(),toBuffer(),pdf(),save(),inspect(),validate(),extractText(),close() - Navigation:
goto(),setContentLive(),reload(),goBack(),goForward(),currentUrl(),bringToFront() - Input:
click(),type(),fill(),focus(),hover(),select(),check(),uncheck(),press(),setInputFiles(),mouseMove(),mouseDown(),mouseUp(),mouseWheel(),scrollBy() - Queries & Waits:
evaluate(),evalOnSelector(),evalOnSelectorAll(),content(),title(),textContent(),waitForSelector(),waitForFunction(),waitForNavigation(),waitForRequest(),waitForResponse() - Capture & Emulation:
screenshot(),addStyleTag(),addScriptTag(),setViewport(),setUserAgent(),emulate(),emulateMediaType(),setOffline() - Network & Diagnostics:
setExtraHTTPHeaders(),setCookies(),cookies(),clearCookies(),authenticate(),blockUrls(),interceptRequests(),exposeFunction(),startConsoleCapture(),getConsoleCapture()
Crash-resilient sessions: If Chromium exits unexpectedly mid-session, the next call transparently relaunches the browser and replays the document's last URL or HTML (doc.wasRecovered reports when recovery occurred).
HTTP Microservice & MCP Server
Run as a Docker / HTTP Microservice
onex serve --port 3000 --host 127.0.0.1 --api-key "$ONEX_API_KEY"Or via Docker (Dockerfile included):
docker build -t onex-server .
docker run -p 3000:3000 -e ONEX_API_KEY=your-secret-key onex-serverAvailable endpoints:
GET /healthPOST /render({ html | url, options?, language?, metadata? }->application/pdf,503 Retry-After: 5onONEX_QUEUE_FULL)POST /optimize({ pdfBase64, level?, allowModifySigned? }->application/pdf)POST /inspect({ pdfBase64 }-> JSON report)POST /tables({ pdfBase64, invoice? }-> extracted tables orextractInvoiceData()result)POST /scan-quality({ pdfBase64 }-> scan classification, per-page DPI,<200 KBreport)POST /verify-signatures({ pdfBase64 }-> PKCS#7/ByteRange+ certificate verification)POST /pdfa({ pdfBase64, level?, enforce?, allowModifySigned? }-> PDF/A compliance report or archival PDF)POST /convert-legacy({ text | html, encoding? }-> converted Unicode text/HTML)POST /merge({ pdfsBase64, title?, deduplicateResources?, allowModifySigned? }->application/pdf)POST /split({ pdfBase64, pages?, ranges?, chunkSize?, allowModifySigned? }->application/pdfor{ count, chunksBase64 })POST /watermark({ pdfBase64, text, opacity?, fontSize?, angle?, position?, allowModifySigned? }->application/pdf)POST /sign({ pdfBase64, p12Base64 | keyPem + certPem, passphrase?, reason?, location?, docMdp?, tsaUrl? }-> signedapplication/pdf)POST /redact({ pdfBase64, detect?, search?, regions?, burnIn?, scrubMetadata?, returnPdf? }->{ pdfBase64, report })POST /diff({ oldPdfBase64, newPdfBase64, granularity?, redline? }-> diff JSON or redlineapplication/pdf)POST /render-verified({ html, data?, expectations?, hmacSecret?, options? }->{ pdfBase64, verification, manifest })POST /einvoice({ invoiceData, html, cii?, indiaQr?, options? }->{ pdfBase64, xml, validation, qrDecoded, roundTrip })
Run as an MCP Server (for AI Agents)
onex mcpExposes onex_doctor, onex_render_pdf, onex_inspect_pdf, onex_extract_text, onex_extract_tables, onex_inspect_scan, onex_verify_signatures, onex_pdfa, onex_convert_legacy, onex_optimize_pdf, onex_merge_pdfs, onex_split_pdf, onex_watermark_pdf, onex_sign_pdf, onex_redact_pdf, onex_diff_pdfs, onex_render_verified, and onex_render_einvoice over stdio JSON-RPC 2.0 with strict path confinement.
Render & Optimization Options
| Option | Default | Description |
| --- | --- | --- |
| format | "A4" | A3 | A4 | A5 | Letter | Legal | Tabloid | 80mm | 58mm (or custom size) |
| margins | 0 | Per-side CSS lengths ("10mm", "36pt", "1in", "96px") or points |
| singlePage | false (true for 80mm/58mm) | Auto-height single page (clamped to PDF spec 14,400 pt) — long bills never split |
| optimize | "balanced" | none · fast · balanced · maximum |
| waitUntil | "load" | load · domcontentloaded · networkidle · commit |
| waitForSelector | — | Wait for a DOM selector before rendering |
| waitForImages | true | Wait for all <img> elements to load |
| extraWaitMs | 0 | Extra delay (ms) after all waits complete |
| emulateMedia | "print" | "screen" preserves @media screen CSS |
| scale | 1 | CSS pixel scale factor (up to 2) |
| maxImageDpi | 200 | Downscale oversized images (0 disables); transparent PNGs stay PNG with alpha preserved |
| imageQuality | 0.82 | JPEG quality (0–1) for re-encoded opaque images |
| fallbackFonts | true | Auto-inject bundled Devanagari, Bengali, Tamil, Arabic, ₹, and Latin fallback fonts |
| reportMode | false | Repeating <thead>/<tfoot>, row break protection, and default dynamic "Page X of Y" footers |
| pageNumbers | false | Custom/default footer pagination (true or { format, fontSize, color, align }) |
| maxBytes | — | Target maximum PDF byte budget via progressive image downsampling + maximum optimization |
| grayscaleImages | false | Convert raster <img> assets to grayscale before embedding |
| pdfA | — | Post-process rendered PDF into compliant "PDF/A-1b", "PDF/A-2b", or "PDF/A-3b" |
| convertLegacyFonts | "auto" | Automatically normalize Kruti Dev & Chanakya HTML spans into Unicode Devanagari (false disables) |
CLI
onex render invoice.html invoice.pdf --optimize balanced --format A4
onex render receipt.html pos.pdf --format 80mm
onex render longbill.html one.pdf --single-page
onex merge combined.pdf a.pdf b.pdf --title "Invoices"
onex split combined.pdf summary.pdf --pages 1-2,4
onex split combined.pdf parts-dir --chunk-size 2
onex watermark invoice.pdf paid.pdf --text "PAID" --opacity 0.2 --angle 45
onex inspect invoice.pdf
onex optimize big.pdf small.pdf --level maximum
onex validate invoice.pdf
onex fonts NotoSansTamil-Regular.ttf
onex render report.html out.pdf --report --page-numbers --pdfa PDF/A-2b --max-bytes 204800
onex tables invoice.pdf --invoice
onex scan-quality upload.pdf
onex verify-signatures tender.pdf
onex pdfa raw.pdf archival.pdf --level PDF/A-3b --enforce
onex sign tender.pdf signed.pdf --p12 cert.p12 --passphrase secret
onex redact draft.pdf clean.pdf --detect aadhaar,pan,gstin,phone
onex diff v1.pdf v2.pdf --redline changes.pdf
onex render-verified bill.html verified.pdf --expect expectations.json
onex einvoice bill.html einvoice.pdf --invoice-json invoice.json --irp-qr "$IRP_JWT"
onex convert-legacy "Hkkjr" --encoding krutidev
onex doctor --json
onex serve --port 3000 --api-key "$ONEX_API_KEY"
onex mcp
onex versionSubpath Modules
| Import | Purpose |
| --- | --- |
| onex-pdf | Core ONEX engine, ONEXDocument, renderBatch(), PDF tools, and ONEX.doctor() |
| onex-pdf/puppeteer | 1-line drop-in Puppeteer compatibility adapter |
| onex-pdf/server | Programmatic startServer() HTTP PDF microservice |
| onex-pdf/mcp | Programmatic startMcpServer() stdio MCP server |
| onex-pdf/unicode | Script detection, grapheme segmentation, and emoji analysis |
| onex-pdf/fonts | Font inspection, coverage reporting, and fallback resolution |
| onex-pdf/optimize | Stream recompression, resource deduplication, and object-stream packing |
| onex-pdf/inspect | PDF inspection, structural validation, extractText(), extractTables(), extractInvoiceData(), isValidGstin(), inspectScanQuality(), diffPdfs(), and buildRedlinePdf() |
| onex-pdf/compliance | signPdf(), verifyPdfSignatures(), isSignedPdf(), validatePdfA(), enforcePdfA(), attachEInvoice(), buildCiiXml(), generateQrSvg(), parseIndiaIrpQr(), verifyIntegrity() |
| onex-pdf/redact | redactPdf() fail-closed PII and content-stream redaction engine |
| onex-pdf/merge | mergePdfs(), extractPages(), splitPdf(), and watermarkPdf() |
Security & Server Deployment
ONEX defaults to a fail-closed security profile for untrusted HTML/URLs. See SECURITY.md for SSRF rules, path confinement, HTTP microservice authentication, and Ubuntu AppArmor root guidance.
Measured Performance
Measured on a 2 vCPU sandbox:
| Document | Raw Chromium | ONEX (balanced) | Saved |
| --- | --- | --- | --- |
| Multilingual invoice (2 pages, 11 scripts) | 162 KB | 128 KB | 20.8% |
| Multilingual one-pager | 65 KB | 53 KB | 19.4% |
Cold browser render time is ~1 s per document; PDF parsing and optimization take ~10 ms.
Contributors
Thanks to everyone who has helped improve ONEX (contributing guide):
License
Apache-2.0. Generated Unicode tables derive from the Unicode Character Database (Unicode License). Bundled and test fonts are Google Noto (SIL Open Font License).
