### Install PDFNative CLI Source: https://pdfnative.dev/guides/quickstart.html Install the PDFNative CLI globally using npm. This is a one-time setup step. ```bash npm install --global pdfnative-cli ``` -------------------------------- ### Run All PDFNative CLI Examples Source: https://pdfnative.dev/guides/cli.html Clone the repository and run this script to execute all available examples in the `samples/` directory. ```bash git clone https://github.com/Nizoka/pdfnative-cli cd pdfnative-cli node samples/run-all.js ``` -------------------------------- ### Install and Run PDFNative CLI Source: https://pdfnative.dev/guides/cli.html Demonstrates two ways to run the PDFNative CLI: directly with npx without global installation, or after installing it globally. ```bash # Run directly with npx — no global install required npx pdfnative-cli render --input document.json --output report.pdf # Or install globally npm install --global pdfnative-cli pdfnative render --input document.json --output report.pdf ``` -------------------------------- ### End-to-End Example: Signed Document Workflow Source: https://pdfnative.dev/guides/mcp.html This example demonstrates a two-step process for creating a signature placeholder and then signing the resulting PDF. It utilizes the 'base64' output mode for both steps. Ensure you replace placeholder values like '', '', and '' with actual data. ```json { "tool": "prepare_signature_placeholder", "input": { "title": "Purchase Order #42", "signerName": "Jane Smith", "reason": "CFO approval", "location": "London, UK", "blocks": [ { "type": "paragraph", "text": "Total amount: $128,000" } ], "outputMode": "base64" } } ``` ```json { "tool": "sign_pdf", "input": { "pdfBase64": "", "algorithm": "rsa-sha256", "certDerBase64": "", "rsaKeyPkcs1DerBase64": "", "signerName": "Jane Smith", "reason": "CFO approval", "location": "London, UK", "signingTime": "2026-04-26T09:00:00Z", "outputMode": "base64" } } ``` -------------------------------- ### Install veraPDF on Linux using Official Installer Source: https://pdfnative.dev/guides/pdfa.md Download, unzip, and install veraPDF using the official headless installer. Set environment variables for veraPDF home and path. ```bash curl -fsSL -o verapdf-installer.zip https://software.verapdf.org/rel/verapdf-installer.zip unzip verapdf-installer.zip java -jar verapdf-izpack-installer-*.jar -console # follow the prompts; defaults are sane export VERAPDF_HOME="$HOME/verapdf" export PATH="$VERAPDF_HOME:$PATH" ``` -------------------------------- ### Install pdfnative-react and Dependencies Source: https://pdfnative.dev/guides/onboarding.html Install the pdfnative-react library along with pdfnative and react for use in React applications. ```bash npm install pdfnative-react pdfnative react ``` -------------------------------- ### Install PDFNative MCP Source: https://pdfnative.dev/guides/mcp.html Install the PDFNative MCP tool directly using npx for immediate use without global installation, or install it globally using npm. ```bash # Run directly with npx — no global install required (recommended) npx -y pdfnative-mcp # Or install globally npm install -g pdfnative-mcp pdfnative-mcp ``` -------------------------------- ### Install pdfnative CLI Source: https://pdfnative.dev/guides/onboarding.html Install the pdfnative command-line interface globally for scripting PDF generation. Alternatively, use npx for one-off commands. ```bash npm install -g pdfnative-cli # or: npx pdfnative-cli ... ``` -------------------------------- ### Install pdfnative MCP Source: https://pdfnative.dev/guides/onboarding.html Install the pdfnative MCP package globally to enable AI assistants to generate and manipulate PDFs. ```bash npm install -g pdfnative-mcp ``` -------------------------------- ### Generate Basic PDF with Headings, Paragraphs, and Lists Source: https://pdfnative.dev/playgrounds/mcp.html Use `generate_basic_pdf` to create a multi-page document. This example creates a one-page welcome memo. ```json { "title": "Welcome to ACME", "blocks": [ { "type": "heading", "text": "Welcome to ACME", "level": 1 }, { "type": "paragraph", "text": "We are thrilled to have you on board. Here is what to expect during your first week." }, { "type": "list", "style": "bullet", "items": [ "Day 1 — meet your team and complete IT setup.", "Day 2 — onboarding deep-dive with the People team.", "Day 3 — shadow a customer call and review our product roadmap." ] } ], "footerText": "Confidential · ACME People Team", "metadata": { "author": "People Team", "subject": "Welcome" } } ``` -------------------------------- ### Install veraPDF on macOS using Homebrew Source: https://pdfnative.dev/guides/pdfa.md Install veraPDF using Homebrew Cask and verify the installation by checking the version. ```bash brew install --cask verapdf verapdf --version ``` -------------------------------- ### Install PDFNative React Packages Source: https://pdfnative.dev/index.html Install the necessary packages for using PDFNative with React, Next.js, or Remix applications. ```bash npm install pdfnative-react pdfnative react ``` -------------------------------- ### Build Document with Smart Table Source: https://pdfnative.dev/guides/tables.md Example demonstrating how to build a PDF document with a smart table, including column definitions, row data, and various table configuration options like wrapping, header repetition, and zebra striping. ```typescript import { buildDocumentPDFBytes } from 'pdfnative'; const bytes = buildDocumentPDFBytes({ blocks: [ { type: 'table', columns: [ { key: 'item', label: 'Item', width: 0.6, autoFit: true }, { key: 'qty', label: 'Qty', width: 0.2, align: 'right' }, { key: 'price', label: 'Price', width: 0.2, align: 'right' }, ], rows: bigInvoiceRows, // any length wrap: 'auto', // ← new (default) repeatHeader: true, // ← new (default) zebra: true, // ← new (opt-in) caption: 'Invoice line items', minRowHeight: 14, cellPadding: 5, }, ], }); ``` -------------------------------- ### TL;DR — sign any PDF in 3 lines Source: https://pdfnative.dev/guides/signatures.html A quick example demonstrating the core functionality of building a PDF, adding a signature placeholder, and signing it with pdfnative. ```APIDOC ## TL;DR — sign any PDF in 3 lines This example shows the minimal code required to sign a PDF using pdfnative. ### Code Example ```typescript import { buildDocumentPDFBytes, addSignaturePlaceholder, signPdfBytes, } from 'pdfnative'; const unsigned = buildDocumentPDFBytes(params); const placeheld = addSignaturePlaceholder(unsigned, { fieldName: 'Author' }); const signed = signPdfBytes(placeheld, { signerCert, rsaKey, algorithm: 'rsa-sha256', }); ``` ### Explanation 1. `buildDocumentPDFBytes(params)`: Creates the initial PDF content. 2. `addSignaturePlaceholder(unsigned, { fieldName: 'Author' })`: Injects an AcroForm signature widget and a `/Sig` dictionary into the PDF. 3. `signPdfBytes(placeheld, { signerCert, rsaKey, algorithm: 'rsa-sha256' })`: Computes the document hash, builds the CMS SignedData, and embeds the signature into the placeholder. ``` -------------------------------- ### Hybrid Layout Model Examples Source: https://pdfnative.dev/guides/cli.html Demonstrates different ways to use the `pdfnative render` command with CLI flags and JSON layout files. This includes ad-hoc invocations, reproducible CI configurations, and hybrid approaches for per-job overrides. ```bash # 1) Flags only — best for ad-hoc invocations pdfnative render --input doc.json --output report.pdf \ --page-size A4 --margin 50 --compress --tagged pdfa2b ``` ```bash # 2) Layout file only — best for reproducible CI configs pdfnative render --input doc.json --output report.pdf \ --layout layout.json ``` ```bash # 3) Hybrid — base config in a file, per-job overrides on the CLI pdfnative render --input doc.json --output report.pdf \ --layout layout.json \ --watermark-text "DRAFT $(date +%Y-%m-%d)" ``` -------------------------------- ### Configure Full-Screen Kiosk Mode Source: https://pdfnative.dev/guides/viewer-preferences.html Set up a kiosk-like full-screen presentation with specific UI and reading direction settings. This example configures the reader to hide toolbars and menus, use thumbnails after exiting full-screen, and set a right-to-left reading order. ```typescript const viewerPreferences: ViewerPreferences = { pageMode: 'fullScreen', nonFullScreenPageMode: 'useThumbs', hideToolbar: true, hideMenubar: true, direction: 'r2l', printScaling: 'none', }; ``` -------------------------------- ### Configure pdfnative-mcp Client Source: https://pdfnative.dev/playgrounds/mcp.html Paste this configuration into your MCP server's settings to enable pdfnative-mcp. `npx` handles the download, so no global installation is required. ```json { "mcpServers": { "pdfnative": { "command": "npx", "args": ["-y", "pdfnative-mcp"] } } } ``` -------------------------------- ### Generate PDF in Browser Source: https://pdfnative.dev/guides/quickstart.html Generate a PDF document in the browser and trigger its download. This example uses an event listener on a button with the ID 'go'. ```javascript ``` -------------------------------- ### Install pdfnative Library Source: https://pdfnative.dev/guides/onboarding.html Install the pdfnative library using npm. This is the primary package for programmatic PDF generation in Node.js, browsers, Deno, and Bun. ```bash npm install pdfnative ``` -------------------------------- ### JSON Layout Configuration Source: https://pdfnative.dev/guides/cli.html An example of a `layout.json` file that accepts a subset of `PdfLayoutOptions`. This file can be used to configure various aspects of the PDF output. ```json { "pageSize": { "width": 595, "height": 842 }, "margin": { "top": 60, "right": 50, "bottom": 60, "left": 50 }, "compress": true, "tagged": "pdfa2b", "headerTemplate": { "left": "{title}", "right": "{date}" }, "footerTemplate": { "center": "Page {page} / {pages}" } } ``` -------------------------------- ### Set Viewer Preferences Source: https://pdfnative.dev/guides/viewer-preferences.html Configure various viewer preferences like page layout, display modes, and UI elements. This example demonstrates setting multiple preferences for a document. ```typescript import { buildDocumentPDFBytes } from 'pdfnative'; import type { ViewerPreferences } from 'pdfnative'; const viewerPreferences: ViewerPreferences = { pageLayout: 'twoColumnLeft', // continuous two-up, odd pages left pageMode: 'useOutlines', // open the bookmark panel displayDocTitle: true, // titlebar shows /Info /Title, not the filename fitWindow: true, centerWindow: true, }; const bytes = buildDocumentPDFBytes({ title: 'Annual Report', blocks: [/* … */], outline: 'auto', layout: { viewerPreferences }, }); ``` -------------------------------- ### Agent-Friendly CLI Output Source: https://pdfnative.dev/guides/cli.html Example of using the CLI for inspection with JSON output and a summary. The status is redirected to a JSON file on stderr. ```bash # Agent-friendly: compact verdict on stdout, structured status on stderr pdfnative inspect --input report.pdf --json --summary 2>status.json ``` -------------------------------- ### Basic Render Command Source: https://pdfnative.dev/playgrounds/cli.html Generates a basic `npx pdfnative-cli render` command. This is a starting point for rendering PDFs. ```bash npx pdfnative-cli render ``` -------------------------------- ### Configure veraPDF on Windows Source: https://pdfnative.dev/guides/pdfa.md Set the VERAPDF_HOME environment variable and add the veraPDF installation directory to the system PATH. Verify by checking the version. ```powershell $env:VERAPDF_HOME = "C:\Program Files\verapdf" $env:Path += ";$env:VERAPDF_HOME" verapdf.bat --version ``` -------------------------------- ### Generate PDF in Node.js Source: https://pdfnative.dev/guides/quickstart.html Create a simple PDF document with a heading and paragraph using Node.js. This example writes the PDF to a file named 'hello.pdf'. ```javascript import { writeFileSync } from 'node:fs'; import { buildDocumentPDFBytes } from 'pdfnative'; const pdf = buildDocumentPDFBytes({ title: 'Hello', blocks: [ { type: 'heading', text: 'Hello, pdfnative', level: 1 }, { type: 'paragraph', text: 'Pure native PDF — zero dependencies, ISO 32000-1.' }, ], }); writeFileSync('hello.pdf', pdf); ``` -------------------------------- ### Add Table to PDF Source: https://pdfnative.dev/playgrounds/mcp.html Use `add_table` to render a tabular report. This example shows Q1 vs Q2 revenue and profit. ```json { "title": "H1 Performance", "blocks": [ { "type": "heading", "text": "H1 2026 — Performance", "level": 1 }, { "type": "table", "headers": [ "Quarter", "Revenue", "Profit" ], "rows": [ { "cells": [ "Q1", "$1.2M", "$400K" ], "type": "credit", "pointed": false }, { "cells": [ "Q2", "$1.5M", "$600K" ], "type": "credit", "pointed": true } ] } ] } ``` -------------------------------- ### Sample JSON Output for Signature Verification Source: https://pdfnative.dev/guides/cli.html An example of the JSON output produced by the 'pdfnative verify' command, detailing signature properties. ```json { "signatures": [ { "integrity": true, "signatureValid": true, "signatureAlgorithm": "ecdsa-sha256", "chainValid": true, "trustedRoot": true, "timestampPresent": false, "signerSubject": "CN=pdfnative-cli ECDSA Test, O=pdfnative-cli, C=FR", "signerIssuer": "CN=pdfnative-cli ECDSA Test, O=pdfnative-cli, C=FR", "notes": ["no --trust provided; accepted self-signed root"] } ] } ``` -------------------------------- ### Table Configuration with Amount Column Source: https://pdfnative.dev/guides/tables.md Example of a table configuration object where the last column is defined with `kind: 'amount'`. This enables specific styling for financial data. ```typescript { type: 'table', headers: ['Date', 'Description', 'Status', 'Amount'], columns: [ { f: 0.20, a: 'l', mx: 12, mxH: 12 }, { f: 0.45, a: 'l', mx: 60, mxH: 60 }, { f: 0.20, a: 'l', mx: 20, mxH: 20 }, { f: 0.15, a: 'r', mx: 18, mxH: 18, kind: 'amount' }, // ← opt-in bold + credit/debit colour ], rows: [ { cells: ['2026-05-01', 'Salary', 'Cleared', '+3 000.00'], type: 'credit', pointed: false }, { cells: ['2026-05-03', 'Rent', 'Pending', '-1 250.00'], type: 'debit', pointed: false }, ], } ``` -------------------------------- ### Set Native Crypto Provider for Signing Source: https://pdfnative.dev/guides/signatures.html Replace pdfnative's pure-JS RSA/ECDSA math with a native, constant-time signer for high-security, high-frequency server pipelines. This example uses Node.js 'crypto' to provide a constant-time signing implementation. ```javascript import { setCryptoProvider, signPdfBytes } from 'pdfnative'; import { createSign, createPrivateKey } from 'node:crypto'; const key = createPrivateKey(pemPrivateKey); setCryptoProvider({ // `tbs` is the DER-encoded CMS signed attributes. The provider hashes it // with SHA-256 internally (node:crypto does this for you) and returns the // raw signature value (RSA PKCS#1 v1.5, or a DER-encoded ECDSA-P256 sig). sign(tbs, algorithm) { return new Uint8Array(createSign('sha256').update(tbs).sign(key)); }, }); const signed = signPdfBytes(placeheld, { signerCert: cert, algorithm: 'rsa-sha256', // rsaKey/ecKey no longer needed }); // Restore the pure-JS default at any time: setCryptoProvider(null); ``` -------------------------------- ### Serve Documentation Locally Source: https://pdfnative.dev/guides/quickstart.html Run this command to serve the documentation directory locally, which is necessary for testing interactive playgrounds that rely on Web Workers. ```bash npm run docs:serve # → http://localhost:5000 ``` -------------------------------- ### Generate and Validate PDF/A Samples Source: https://pdfnative.dev/guides/pdfa.md Run the npm scripts to generate sample files and then validate them for PDF/A compliance using veraPDF. ```bash # 1. Generate the sample suite (writes test-output/) npm run test:generate # 2. Run veraPDF against every PDF/A-claiming sample npm run validate:pdfa ``` -------------------------------- ### JSON Structure for PDF Rendering Source: https://pdfnative.dev/guides/cli.html An example of the JSON structure required for rendering a document using the PDFNative CLI. ```json { "title": "April 2026 Report", "blocks": [ { "type": "heading", "text": "April 2026 Report", "level": 1 }, { "type": "paragraph", "text": "Summary for the financial period ending 30 April 2026." }, { "type": "list", "style": "bullet", "items": [ "Revenue: +18% year-on-year", "Net Promoter Score: 72", "Active customers: 12,400" ]}, { "type": "table", "headers": ["Quarter", "Revenue", "Profit"], "rows": [ { "cells": ["Q1", "$1.2M", "$400K"], "type": "credit", "pointed": false }, { "cells": ["Q2", "$1.5M", "$600K"], "type": "credit", "pointed": true } ] } ], "footerText": "Confidential", "metadata": { "author": "Finance Team", "subject": "April 2026 Report" } } ``` -------------------------------- ### Initialize Node.js Compression Source: https://pdfnative.dev/guides/troubleshooting.html Initialize native compression support in Node.js environments. Without this, a less efficient fallback mechanism is used for compression. ```javascript import { initNodeCompression } from 'pdfnative'; await initNodeCompression(); ``` -------------------------------- ### Branching on Stable Error Codes Source: https://pdfnative.dev/guides/cli.html Example of verifying a PDF and branching execution based on a stable error code captured from stderr. ```bash # Branch on a stable error class pdfnative verify --input report.pdf --json --strict \ || echo "failed: $(jq -r .error.code status.json)" ``` -------------------------------- ### Sample Text Output for PDF Inspection Source: https://pdfnative.dev/guides/cli.html Example of the text-based output from the 'pdfnative inspect' command, showing key PDF metadata. ```text PDF version: 1.7 Pages: 2 Encrypted: no PDF/A conformance: none Signatures: 1 Title: April 2026 Report Author: Finance Team Created: 2026-04-28T10:00:00+00:00 ``` -------------------------------- ### CLI Migration v0.3.0 to v1.1.0 Source: https://pdfnative.dev/guides/cli.html Introduces constant-memory streaming, CI accessibility gates, agent-native output, and parallel directory rendering. ```bash # 1. True constant-memory streaming for very large reports - pdfnative render --input big.json --output big.pdf --stream + pdfnative render --input big.json --output big.pdf --stream-true ``` ```bash # 2. CI accessibility gate (PDF/UA) + pdfnative inspect --input report.pdf --check pdfua ``` ```bash # 3. Agent-native, token-frugal output + pdfnative inspect --input report.pdf --json --summary ``` ```bash # 4. Parallel directory render + pdfnative batch --input inputs/ --output outputs/ --concurrency 4 ``` -------------------------------- ### Generate First PDF with buildDocumentPDFBytes Source: https://pdfnative.dev/guides/faq.html Use `buildDocumentPDFBytes` for mixed-content documents. Ensure `pdfnative` is imported. In the browser, `downloadBlob` handles the file download. For Node.js, use `fs.writeFileSync`. ```javascript import { buildDocumentPDFBytes, downloadBlob } from 'pdfnative'; const pdf = buildDocumentPDFBytes({ title: 'Hello', blocks: [ { type: 'heading', text: 'Hello world', level: 1 }, { type: 'paragraph', text: 'My first PDF.' }, ], }); downloadBlob(pdf, 'hello.pdf'); // browser // or, in Node.js: // fs.writeFileSync('hello.pdf', pdf); ``` -------------------------------- ### Add Barcode to PDF Source: https://pdfnative.dev/playgrounds/mcp.html Use `add_barcode` to embed various barcode formats. This example adds a QR code linking to a payment portal. ```json { "title": "Invoice INV-001", "blocks": [ { "type": "heading", "text": "Invoice INV-001", "level": 1 }, { "type": "paragraph", "text": "Scan the QR code below to settle this invoice." }, { "type": "barcode", "format": "qr", "data": "https://acme.example/pay/INV-001", "width": 140, "ecLevel": "M", "align": "center" } ] } ``` -------------------------------- ### Enable Node.js Compression Source: https://pdfnative.dev/guides/quickstart.html For optimal PDF compression in Node.js, initialize native zlib support once at startup. Then, pass `compress: true` when building the PDF. ```javascript import { initNodeCompression, buildDocumentPDFBytes } from 'pdfnative'; await initNodeCompression(); const pdf = buildDocumentPDFBytes(params, { compress: true }); ``` -------------------------------- ### Configure PDFNative MCP for Continue Source: https://pdfnative.dev/guides/mcp.html Configure PDFNative MCP for Continue by editing the `~/.continue/config.json` file. Define the server name, command, arguments, and environment variables like `PDFNATIVE_MCP_OUTPUT_DIR`. ```json { "mcpServers": [ { "name": "pdfnative", "command": "npx", "args": ["-y", "pdfnative-mcp"], "env": { "PDFNATIVE_MCP_OUTPUT_DIR": "/path/to/pdf-output" } } ] } ``` -------------------------------- ### Serve Local Directory with HTTP Server Source: https://pdfnative.dev/playgrounds/medical-800.html To enable Web Workers, serve the documentation directory using a local HTTP server. Browsers block ESM Workers when a page is opened directly from disk (`file://` protocol). ```bash npx serve docs/ # or: python -m http.server 8080 --directory docs/ # then open http://localhost:5000/playgrounds/medical-800.html ``` -------------------------------- ### Validate PDF/A Conformance with veraPDF Source: https://pdfnative.dev/guides/accessibility.html Use the veraPDF command-line tool to validate your generated PDFs against the PDF/A standard. Install it globally via npm. ```bash npm install -g verapdf verapdf --format text my-document.pdf ``` -------------------------------- ### Add Form Fields to PDF Source: https://pdfnative.dev/playgrounds/mcp.html Use `add_form` to build an interactive AcroForm PDF. This example creates a contact form with text fields and a checkbox. ```json { "title": "Contact us", "blocks": [ { "type": "heading", "text": "Contact us", "level": 1 }, { "type": "formField", "fieldType": "text", "name": "fullName", "label": "Full name", "x": 60, "y": 680, "width": 300, "height": 24 }, { "type": "formField", "fieldType": "text", "name": "email", "label": "Email", "x": 60, "y": 640, "width": 300, "height": 24 }, { "type": "formField", "fieldType": "checkbox", "name": "subscribe", "label": "Subscribe to newsletter", "x": 60, "y": 600, "width": 18, "height": 18, "checked": false } ] } ``` -------------------------------- ### Generate PDF in Browser with downloadBlob Source: https://pdfnative.dev/guides/faq.html This snippet demonstrates PDF generation in a browser environment using `buildDocumentPDFBytes` and `downloadBlob` for immediate download. ```javascript import { buildDocumentPDFBytes, downloadBlob } from 'pdfnative'; const pdf = buildDocumentPDFBytes({ title: 'Hello', blocks: [/* … */] }); downloadBlob(pdf, 'output.pdf'); ``` -------------------------------- ### Register Fonts and Build Document PDF Source: https://pdfnative.dev/playgrounds/extreme-scripts.html Registers fonts for Arabic, Hebrew, and Thai, loads their data, and then builds a PDF document with mixed-language content, including BiDi text and numerals. The generated PDF is then downloaded as a blob. ```javascript import { registerFonts, loadFontData, buildDocumentPDFBytes, downloadBlob } from 'pdfnative'; registerFonts({ ar: () => import('https://esm.sh/pdfnative/fonts/noto-arabic-data.js'), he: () => import('https://esm.sh/pdfnative/fonts/noto-hebrew-data.js'), th: () => import('https://esm.sh/pdfnative/fonts/noto-thai-data.js'), }); const langs = ["ar","he","th"]; const fonts = await Promise.all(langs.map(loadFontData)); const fontEntries = fonts.map((fd, i) => fd ? { fontData: fd, fontRef: `/F${3+i}`, lang: langs[i] } : null).filter(Boolean); const pdf = buildDocumentPDFBytes({ title: "Extreme BiDi", blocks: [ { type: 'heading', text: "Extreme BiDi — Arabic + Hebrew + Thai + Latin + Numerals", level: 1 }, { type: 'paragraph', text: "مثال BiDi قوي: السلام عليكم 654321 — שלום עולם — สวัสดี + Hello from Thailand 789." }, { type: 'paragraph', text: "هذا اختبار للـ shaping المتقدم في اللغة العربية: السلام عليكم ورحمة الله وبركاته." }, { type: 'paragraph', text: "בדיקה של טקסט עברי מורכב עם ניקוד: שָׁלוֹם עֲלֵיכֶם." }, { type: 'paragraph', text: "การทดสอบภาษาไทย: สวัสดีครับ ขอบคุณมากครับ ภาษาไทยมีพยัญชนะและสระและวรรณยุกต์." }, ], fontEntries, }); downloadBlob(pdf, 'extreme.pdf'); ``` -------------------------------- ### Add International Text to PDF Source: https://pdfnative.dev/playgrounds/mcp.html Use `add_international_text` to render text in multiple scripts with BiDi and OpenType shaping. This example includes English, Thai, Arabic, and an emoji. ```json { "title": "Multilingual greeting", "lang": [ "th", "ar", "emoji" ], "blocks": [ { "type": "heading", "text": "Hello · สวัสดี · مرحبا 😊", "level": 1 }, { "type": "paragraph", "text": "English: a multilingual document rendered with native shaping and BiDi." }, { "type": "paragraph", "text": "ภาษาไทย: เอกสารหลายภาษาที่จัดรูปแบบด้วยการสร้างรูปร่างและการจัดวางทิศทางสองทิศทาง" }, { "type": "paragraph", "text": "العربية: مستند متعدد اللغات يتم عرضه باستخدام التشكيل الأصلي ودعم اتجاهي ثنائي." } ] } ``` -------------------------------- ### Sign PDF with Environment Variables Source: https://pdfnative.dev/guides/cli.html Signs a PDF document using provided signing keys and certificate set via environment variables. Recommended for CI/CD. ```bash # Set keys via environment variables (recommended for CI/CD — never logged) export PDFNATIVE_SIGN_KEY="$(cat private.pem)" export PDFNATIVE_SIGN_CERT="$(cat cert.pem)" pdfnative sign \ --input report.pdf \ --output report.signed.pdf \ --reason "Approved by Finance" \ --name "Finance Team" \ --location "Paris, FR" \ --signing-time 2026-04-28T10:00:00Z ``` -------------------------------- ### End-to-End PDF Signing Workflow Source: https://pdfnative.dev/index.html Demonstrates a complete workflow: rendering a JSON input to a PDF, signing the generated PDF using ECDSA-SHA256, and then verifying the signature. Keys and certificates are expected to be available via environment variables. ```bash # Render → sign → verify, end-to-end echo '{"blocks":[{"type":"paragraph","text":"Hello, signed world."}]}' \ | npx pdfnative-cli render -o out.pdf npx pdfnative-cli sign -i out.pdf -o signed.pdf \ --algorithm ecdsa-sha256 \ --key key.pem --cert cert.pem --reason "Approved" npx pdfnative-cli verify -i signed.pdf --strict ``` -------------------------------- ### List PDF/A Conformance Targets Source: https://pdfnative.dev/guides/pdfa.md Import and inspect the `PDF_A_CONFORMANCE_TARGETS` constant to get a list of all supported PDF/A conformance levels. This is useful for validating input or populating UI elements. ```typescript import { PDF_A_CONFORMANCE_TARGETS, type PdfAConformanceTarget } from 'pdfnative'; PDF_A_CONFORMANCE_TARGETS; // → readonly ['pdfa1b', 'pdfa2b', 'pdfa2u', 'pdfa3b'] function isValidTarget(s: string): s is PdfAConformanceTarget { return (PDF_A_CONFORMANCE_TARGETS as readonly string[]).includes(s); } ``` -------------------------------- ### Inspect Document Layout Programmatically Source: https://pdfnative.dev/guides/debugging.html Use `inspectDocumentLayout` to get block geometry data without rendering. This shares the same pagination engine as the builder and is useful for automated testing or layout linting. ```javascript import { inspectDocumentLayout } from 'pdfnative'; import type { LayoutInspection } from 'pdfnative'; const report: LayoutInspection = inspectDocumentLayout(params); report.pages.forEach((page) => { console.log(`Page ${page.index + 1}: ${page.blocks.length} blocks`); page.blocks.forEach((b) => { console.log(` ${b.type} @ (${b.x}, ${b.top}) ${b.width}×${b.height}`); }); }); ``` -------------------------------- ### Register and Load Fonts for Multi-Language Support Source: https://pdfnative.dev/index.html Register lazy-loaded font data modules using `registerFonts` and load them with `loadFontData` for multi-language PDF generation. This example demonstrates loading Thai, Arabic, Bengali, and Japanese fonts. ```javascript import { registerFonts, loadFontData, buildDocumentPDFBytes } from 'pdfnative'; // Register lazy-loaded Noto Sans font data modules registerFonts({ th: () => import('pdfnative/fonts/noto-thai-data.js'), ar: () => import('pdfnative/fonts/noto-arabic-data.js'), bn: () => import('pdfnative/fonts/noto-bengali-data.js'), ja: () => import('pdfnative/fonts/noto-jp-data.js'), }); // Load only the scripts you need const fonts = await Promise.all( ['th', 'ar', 'bn', 'ja'].map(loadFontData) ); const fontEntries = fonts.filter(Boolean).map((fd, i) => ({ fontData: fd!, fontRef: `/F${3 + i}`, lang: ['th', 'ar', 'bn', 'ja'][i], })); const pdf = buildDocumentPDFBytes({ title: 'Multi-Language Document', blocks: [ { type: 'heading', text: 'สวัสดี — مرحبا — こんにちは', level: 1 }, { type: 'paragraph', text: 'pdfnative renders Thai, Arabic (with BiDi), Bengali, ' + 'and Japanese — all from a single API call.' }, ], fontEntries, tagged: true, // PDF/A-2b with structure tree }); ``` -------------------------------- ### splitPdf Source: https://pdfnative.dev/guides/pdf-manipulation.html Splits a PDF document into multiple parts based on specified page ranges. Each part is a new PDF document. The function handles 0-based indexing for pages and allows defining start and end points for each segment. ```APIDOC ## splitPdf(source, ranges) ### Description Splits a PDF document into multiple parts based on specified page ranges. Each part is a new PDF document. ### Method `splitPdf` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body `source`: `Uint8Array` - The PDF document (as byte array) to split. `ranges`: `Array<{ start: number; end?: number }>` - An array of objects defining the page ranges to extract. Pages are 0-based. `end` is inclusive and defaults to `start` if not provided. ### Notes - `end` defaults to `start` if not specified. ### Request Example ```javascript import { splitPdf } from 'pdfnative'; import { readFileSync, writeFileSync } from 'node:fs'; const b = readFileSync('body.pdf'); // Split into page ranges (0-based, end inclusive; end defaults to start) const [intro, rest] = splitPdf(b, [ { start: 0, end: 1 }, // pages 0–1 { start: 2, end: 9 }, // pages 2–9 ]); // writeFileSync('intro.pdf', intro); // writeFileSync('rest.pdf', rest); ``` ### Response Returns an array of `Uint8Array`, where each element represents a split PDF document. ``` -------------------------------- ### prepare_signature_placeholder Source: https://pdfnative.dev/guides/mcp.html Creates a PDF with a signature placeholder, ready to be signed using the `sign_pdf` command. ```APIDOC ## prepare_signature_placeholder ### Description Creates a PDF pre-wired with an AcroForm `/Sig` field, ready to be signed by `sign_pdf`. ### Parameters #### Request Body - **title** (string) - Required - The title of the document. - **signerName** (string) - Optional - The name of the signer. - **reason** (string) - Optional - The reason for signing. - **location** (string) - Optional - The location of signing. - **blocks** (object[]) - Optional - Content blocks to include in the PDF. - **type** (string) - Required - The type of block (e.g., `paragraph`). - **text** (string) - Required - The text content of the block. - **outputMode** (string) - Optional - The output mode (`base64` or `file`). ``` -------------------------------- ### Build PDF with 22 Scripts and Emoji Source: https://pdfnative.dev/playgrounds/all-scripts.html Use this script to generate a PDF document that includes text from 22 different Unicode scripts and COLRv1 color emoji. It automatically loads and registers necessary fonts, builds the document with various blocks, and downloads the resulting PDF. Ensure fonts are correctly imported and loaded. ```javascript import { registerFonts, loadFontData, buildDocumentPDFBytes, downloadBlob } from 'pdfnative'; // 22 scripts + Latin + emoji — each lazy-loaded from the package fonts/ subpath. const langs = ["el","ru","ka","hy","tr","vi","pl","ar","he","am","hi","bn","ta","te","si","th","km","my","bo","zh","ja","ko","latin","emoji"]; registerFonts(Object.fromEntries(langs.map(l => [l, () => import(`https://esm.sh/pdfnative/fonts/${MODULE[l]}`)]))); const fonts = await Promise.all(langs.map(loadFontData)); const fontEntries = fonts .map((fd, i) => fd ? { fontData: fd, fontRef: `/F${3 + i}`, lang: langs[i] } : null) .filter(Boolean); // One call. The engine routes every code point to the right embedded font, // applies BiDi reordering + GSUB/GPOS shaping, and subsets each font. const pdf = buildDocumentPDFBytes({ title: "pdfnative — 22 Unicode scripts + colour emoji", blocks: [ { type: 'heading', text: "One library · 22 scripts · zero dependencies 🌍", level: 1 }, { type: 'paragraph', text: "pdfnative renders all 22 of its supported Unicode scripts and native COLRv1 colour emoji into a single PDF — no Cairo, no HarfBuzz, no fontkit, no rasterization. Each code point below is routed to the correct embedded font automatically." }, { type: 'paragraph', text: "Europe & the Caucasus: English Hello · Ελληνικά Γειά σου · Русский Здравствуйте · ქართული გამარჯობა · Հայերեն Բարև · Türkçe Merhaba · Tiếng Việt Xin chào · Polski Dzień dobry" }, { type: 'paragraph', text: "Middle East & Africa (RTL + BiDi): العربية السلام عليكم · עברית שלום · አማርኛ ሰላም — mixed with Latin 12345 and back." }, { type: 'paragraph', text: "South Asia: हिन्दी नमस्ते · বাংলা নমস্কার · தமிழ் வணக்கம் · తెలుగు నమస్తే · සිංහල ආයුබෝවන්" }, { type: 'paragraph', text: "Southeast Asia & the Himalayas: ไทย สวัสดี · ខ្មែរ សួស្តី · မြန်မာ မင်္ဂလာပါ · བོད་ཡིག བཀྲ་ཤིས་བདེ་ལེགས།" }, { type: 'paragraph', text: "East Asia: 中文 你好 · 日本語 こんにちは · 한국어 안녕하세요" }, { type: 'paragraph', text: "And native colour emoji, composited as PDF vectors: 🌍 🌏 🌎 ✨ 🚀 📄 ⚡ 🔒 ✅ ❤️ 🎉 🥳 👋" }, ], fontEntries, }); downloadBlob(pdf, 'pdfnative-22-scripts.pdf'); ```