JavaScript-API-Referenz
PDF Oxide stellt WebAssembly-Bindings für JavaScript und TypeScript bereit. Das npm-Paket pdf-oxide-wasm läuft in Node.js, im Browser, in Bundlern, in Deno und in Cloudflare Workers.
npm install pdf-oxide-wasm
Multi-Target-Paketierung (v0.3.38)
pdf-oxide-wasm liefert nun drei Builds parallel aus, gesteuert über bedingte Exporte in der package.json. Wählen Sie den Subpfad, der zu Ihrer Laufzeitumgebung passt — der automatisch geroutete Top-Level-Import wird über das exports-Feld in den meisten Umgebungen ebenfalls korrekt aufgelöst.
| Subpfad | Zielumgebung |
|---|---|
pdf-oxide-wasm/nodejs |
Node.js (CommonJS + ESM) |
pdf-oxide-wasm/bundler |
Vite, webpack, Rollup, esbuild, Bun |
pdf-oxide-wasm/web |
Browser, Deno, Cloudflare Workers |
// Node.js
import { WasmPdfDocument } from "pdf-oxide-wasm/nodejs";
// Vite / webpack / Rollup
import init, { WasmPdfDocument } from "pdf-oxide-wasm/bundler";
await init();
// Browsers / Deno / Workers
import init, { WasmPdfDocument } from "pdf-oxide-wasm/web";
await init();
Das behebt den Fehler ReferenceError: Can't find variable: __dirname, der unter Browser-Bundlern vor v0.3.38 ausgelöst wurde.
Für die Rust-API siehe die Rust-API-Referenz. Für die Python-API siehe die Python-API-Referenz. Für Details zu den Typen siehe Typen & Enums.
Einige Methoden sind hinter Rust-Build-Features (
rendering,signatures,barcodes,ocr-tract) freigeschaltet. Das Standardpaketpdf-oxide-wasmaktiviert den gängigen Funktionsumfang; OCR wird im separatenwasm-ocr-Build ausgeliefert. Siehe Feature-Verfügbarkeit.
Module Functions
Freie Funktionen, die auf oberster Ebene des Pakets exportiert werden.
import {
setLogLevel, disableLogging,
generateBarcodeSvg, generateQrSvg,
planSplitByBookmarks, splitByBookmarks,
setCryptoPolicy, cryptoPolicy, cryptoInventory, cryptoCbom,
modelManifest, prefetchAvailable,
signPdfBytes, signPdfBytesPades, hasDocumentTimestamp,
} from "pdf-oxide-wasm";
Logging
setLogLevel(level) // Set log verbosity: "off" | "error" | "warn" | "info" | "debug" | "trace"
disableLogging() // Silence all log output
Barcodes
generateBarcodeSvg(barcodeType, data) -> string // 1D barcode as SVG; type 0–7 (Code128, Code39, Ean13, Ean8, UpcA, Itf, Code93, Codabar)
generateQrSvg(data, errorCorrection, size) -> string // QR code as SVG; errorCorrection 0=Low 1=Medium 2=Quartile 3=High
Aufteilen nach Lesezeichen
planSplitByBookmarks(srcBytes, titlePrefix, ignoreCase, level, includeFrontMatter) -> Array // Plan a split without producing PDFs; returns segment descriptors
splitByBookmarks(srcBytes, titlePrefix, ignoreCase, level, includeFrontMatter) -> Array // Split at bookmark boundaries; returns [segment, bytes] pairs (level 0=all depths, 1=top-level)
Krypto-Governance
setCryptoPolicy(spec) // Install the process-wide crypto policy ("compat" | "strict" | "fips-strict"[;…]); fail-closed
cryptoPolicy() -> string // The active crypto policy as its canonical grammar string
cryptoInventory() -> string[] // Algorithm tokens exercised so far this process
cryptoCbom() -> string // CycloneDX 1.6 Cryptographic Bill of Materials (JSON string)
Bereitstellung von OCR-Modellen
modelManifest() -> string // JSON manifest of OCR detector/recognizer cache filenames and source URLs (host-side fetch)
prefetchAvailable() -> boolean // Whether this build can download OCR models to a local cache (always false in WASM)
Signieren (freie Funktionen)
signPdfBytes(pdfData, cert, reason?, location?) -> Uint8Array // Sign raw PDF bytes with a WasmCertificate; returns the signed PDF
signPdfBytesPades(pdfData, cert, level, timestampToken?, revocation?, reason?, location?) -> Uint8Array // Sign at a PAdES baseline level (BB/BT/BLt); pass a pre-fetched RFC 3161 token for BT/BLt
hasDocumentTimestamp(pdfData) -> boolean // Whether the PDF carries a document-scoped /DocTimeStamp (PAdES-B-LTA)
WasmPdfDocument
Die zentrale Klasse zum Öffnen, Extrahieren, Bearbeiten und Speichern von PDFs.
import { WasmPdfDocument } from "pdf-oxide-wasm";
Konstruktor
new WasmPdfDocument(data, password?)
Lädt ein PDF-Dokument aus rohen Bytes.
| Parameter | Typ | Beschreibung |
|---|---|---|
data |
Uint8Array |
Der Inhalt der PDF-Datei |
password |
string | undefined |
Optionales Passwort für verschlüsselte PDFs |
Wirft: Error, wenn das PDF ungültig ist oder nicht geparst werden kann.
const bytes = new Uint8Array(readFileSync("document.pdf"));
const doc = new WasmPdfDocument(bytes);
Statische Konstruktoren
WasmPdfDocument.openFromDocxBytes(data) -> WasmPdfDocument // Convert DOCX bytes to a PDF document
WasmPdfDocument.openFromPptxBytes(data) -> WasmPdfDocument // Convert PPTX bytes to a PDF document
WasmPdfDocument.openFromXlsxBytes(data) -> WasmPdfDocument // Convert XLSX bytes to a PDF document
Grundlegende Lesezugriffe
pageCount() -> number
Liefert die Anzahl der Seiten im Dokument.
version() -> Uint8Array
Liefert die PDF-Version als [major, minor].
const [major, minor] = doc.version();
console.log(`PDF ${major}.${minor}`);
authenticate(password) -> boolean
Entschlüsselt ein verschlüsseltes PDF. Gibt true zurück, wenn die Authentifizierung erfolgreich war.
| Parameter | Typ | Beschreibung |
|---|---|---|
password |
string |
Die Passwort-Zeichenkette |
hasStructureTree() -> boolean
Prüft, ob das Dokument ein Tagged PDF mit einem Strukturbaum ist.
Signaturprüfung
signatureCount() -> number // Number of digital signatures in the document
signatures() -> WasmSignature[] // Parsed signatures (signer, reason, time, verify())
dss() -> Dss | null // Document Security Store (certs/CRLs/OCSP), or null
Textextraktion
extractText(pageIndex, region?) -> string
Extrahiert reinen Text aus einer einzelnen Seite. Übergeben Sie optional einen [x, y, w, h]-Bereich, um die Extraktion einzugrenzen.
| Parameter | Typ | Beschreibung |
|---|---|---|
pageIndex |
number |
Nullbasierte Seitennummer |
region |
number[] | undefined |
Optionaler [x, y, width, height]-Ausschnitt |
const text = doc.extractText(0);
extractAllText() -> string
Extrahiert reinen Text aus allen Seiten, getrennt durch Seitenvorschubzeichen.
extractStructured(pageIndex) -> string
Extrahiert eine strukturierte JSON-Repräsentation der Seite (Blöcke, Zeilen, Formatierung).
extractChars(pageIndex, region?) -> Array
Extrahiert einzelne Zeichen mit präziser Positionierung und Schrift-Metadaten.
| Parameter | Typ | Beschreibung |
|---|---|---|
pageIndex |
number |
Nullbasierte Seitennummer |
region |
number[] | undefined |
Optionaler [x, y, width, height]-Ausschnitt |
Rückgabe: Array von Objekten mit den Feldern:
| Feld | Typ | Beschreibung |
|---|---|---|
char |
string |
Das Zeichen |
bbox |
{x, y, width, height} |
Begrenzungsrahmen |
fontName |
string |
Schriftname |
fontSize |
number |
Schriftgröße in Punkt |
fontWeight |
string |
Schriftstärke (Normal, Bold usw.) |
isItalic |
boolean |
Kursiv-Flag |
color |
{r, g, b} |
RGB-Farbe (0.0–1.0) |
const chars = doc.extractChars(0);
for (const c of chars) {
console.log(`'${c.char}' at (${c.bbox.x}, ${c.bbox.y})`);
}
extractPageText(pageIndex, readingOrder?) -> object
Liefert Spans, Zeichen und Seitenabmessungen in einem einzigen Extraktionsdurchlauf. Effizienter, als extractSpans() + extractChars() separat aufzurufen. Übergeben Sie "column_aware" für mehrspaltige PDFs.
| Parameter | Typ | Beschreibung |
|---|---|---|
pageIndex |
number |
Nullbasierte Seitennummer |
readingOrder |
string | undefined |
"column_aware" oder "top_to_bottom" (Standard) |
Rückgabe: Ein Objekt mit den Feldern:
| Feld | Typ | Beschreibung |
|---|---|---|
spans |
Array |
Array von Span-Objekten |
chars |
Array |
Array von Zeichen-Objekten |
pageWidth |
number |
Seitenbreite in PDF-Punkt |
pageHeight |
number |
Seitenhöhe in PDF-Punkt |
text |
string |
Vollständiger Textinhalt |
const result = doc.extractPageText(0);
console.log(`Page: ${result.pageWidth}x${result.pageHeight} pt`);
for (const span of result.spans) {
console.log(`'${span.text}' font=${span.fontName} size=${span.fontSize}`);
}
extractSpans(pageIndex, region?, readingOrder?) -> Array
Extrahiert formatierte Text-Spans mit Schrift-Metadaten. Übergeben Sie "column_aware" als readingOrder für mehrspaltige PDFs.
| Parameter | Typ | Beschreibung |
|---|---|---|
pageIndex |
number |
Nullbasierte Seitennummer |
region |
number[] | undefined |
Optionaler [x, y, width, height]-Ausschnitt |
readingOrder |
string | undefined |
"column_aware" oder "top_to_bottom" (Standard) |
Rückgabe: Array von Objekten mit den Feldern:
| Feld | Typ | Beschreibung |
|---|---|---|
text |
string |
Der Textinhalt |
bbox |
{x, y, width, height} |
Begrenzungsrahmen |
fontName |
string |
Schriftname |
fontSize |
number |
Schriftgröße in Punkt |
fontWeight |
string |
Schriftstärke (Normal, Bold usw.) |
isItalic |
boolean |
Kursiv-Flag |
isMonospace |
boolean |
Ob die Schrift dicktengleich ist |
charWidths |
number[] |
Vorschubbreiten pro Glyphe |
color |
{r, g, b} |
RGB-Farbe (0.0–1.0) |
const spans = doc.extractSpans(0);
for (const span of spans) {
console.log(`"${span.text}" size=${span.fontSize}`);
}
Wörter, Zeilen, Tabellen
extractWords(pageIndex, region?) -> Array // Word-level boxes with text + font metadata
extractTextLines(pageIndex, region?) -> Array // Line-level boxes, each with its words
extractTables(pageIndex, region?) -> Array // Detected tables with rows/cells (text + bboxes)
Kopf-/Fußzeilen-Artefakte
Erkennen und entfernen oder löschen Sie laufende Kopf-, Fußzeilen und Seitenmöblierungs-Artefakte.
removeHeaders(threshold) -> number // Remove detected headers across the document; returns count removed
removeFooters(threshold) -> number // Remove detected footers; returns count removed
removeArtifacts(threshold) -> number // Remove detected page artifacts; returns count removed
eraseHeader(pageIndex) // Queue an erase of the header region on a page
editHeader(pageIndex) // Mark the header region for editing on a page
eraseFooter(pageIndex) // Queue an erase of the footer region on a page
editFooter(pageIndex) // Mark the footer region for editing on a page
eraseArtifacts(pageIndex) // Queue an erase of detected artifacts on a page
Bereichsextraktion
within(pageIndex, region) -> WasmPdfPageRegion
Schränkt nachfolgende Extraktionen auf einen rechteckigen Seitenbereich ein. region ist [x, y, width, height]. Siehe WasmPdfPageRegion.
const region = doc.within(0, [50, 600, 400, 150]);
const text = region.extractText();
Formatkonvertierung
toMarkdown(pageIndex, detectHeadings?, includeImages?, includeFormFields?) -> string
Konvertiert eine einzelne Seite nach Markdown.
| Parameter | Typ | Standard | Beschreibung |
|---|---|---|---|
pageIndex |
number |
– | Nullbasierte Seitennummer |
detectHeadings |
boolean |
true |
Überschriften anhand der Schriftgröße erkennen |
includeImages |
boolean |
true |
Bilder einbeziehen |
includeFormFields |
boolean |
true |
Werte von Formularfeldern einbeziehen |
toMarkdownAll(detectHeadings?, includeImages?, includeFormFields?) -> string
Konvertiert alle Seiten nach Markdown.
toHtml(pageIndex, preserveLayout?, detectHeadings?, includeFormFields?) -> string
Konvertiert eine einzelne Seite nach HTML.
| Parameter | Typ | Standard | Beschreibung |
|---|---|---|---|
pageIndex |
number |
– | Nullbasierte Seitennummer |
preserveLayout |
boolean |
false |
Visuelles Layout beibehalten |
detectHeadings |
boolean |
true |
Überschriften erkennen |
includeFormFields |
boolean |
true |
Werte von Formularfeldern einbeziehen |
toHtmlAll(preserveLayout?, detectHeadings?, includeFormFields?) -> string
Konvertiert alle Seiten nach HTML.
toPlainText(pageIndex) -> string
Konvertiert eine einzelne Seite in reinen Text.
toPlainTextAll() -> string
Konvertiert alle Seiten in reinen Text.
Office-Round-Trip
toDocxBytes() -> Uint8Array // Export the document as a DOCX file
toPptxBytes() -> Uint8Array // Export the document as a PPTX file
toXlsxBytes() -> Uint8Array // Export the document as an XLSX file
Suche
search(pattern, caseInsensitive?, literal?, wholeWord?, maxResults?) -> Array
Sucht über alle Seiten hinweg nach Text.
| Parameter | Typ | Standard | Beschreibung |
|---|---|---|---|
pattern |
string |
– | Suchmuster (String oder Regex) |
caseInsensitive |
boolean |
false |
Groß-/Kleinschreibung ignorieren |
literal |
boolean |
false |
Muster als literale Zeichenkette behandeln |
wholeWord |
boolean |
false |
Nur ganze Wörter treffen |
maxResults |
number |
0 |
Maximale Trefferzahl (0 = unbegrenzt) |
Rückgabe: Array von Objekten mit den Feldern:
| Feld | Typ | Beschreibung |
|---|---|---|
page |
number |
Seitennummer |
text |
string |
Gefundener Text |
bbox |
object |
Begrenzungsrahmen |
startIndex |
number |
Startindex im Seitentext |
endIndex |
number |
Endindex im Seitentext |
searchPage(pageIndex, pattern, caseInsensitive?, literal?, wholeWord?, maxResults?) -> Array
Sucht innerhalb einer einzelnen Seite nach Text.
Bildinformationen
extractImages(pageIndex) -> Array
Liefert Bild-Metadaten für eine Seite.
| Feld | Typ | Beschreibung |
|---|---|---|
width |
number |
Bildbreite in Pixel |
height |
number |
Bildhöhe in Pixel |
colorSpace |
string |
Farbraum (z. B. DeviceRGB) |
bitsPerComponent |
number |
Bits pro Farbkanal |
bbox |
object |
Position auf der Seite |
extractImageBytes(pageIndex) -> Array
Extrahiert die rohen Bild-Bytes aus einer Seite. Gibt ein Array von Objekten zurück:
| Feld | Typ | Beschreibung |
|---|---|---|
width |
number |
Bildbreite in Pixel |
height |
number |
Bildhöhe in Pixel |
data |
Uint8Array |
Rohe Bild-Bytes |
format |
string |
Bildformat |
pageImages(pageIndex) -> Array
Liefert Bildnamen und -grenzen für Positionierungsoperationen.
| Feld | Typ | Beschreibung |
|---|---|---|
name |
string |
XObject-Name |
bounds |
number[] |
[x, y, width, height] |
matrix |
number[] |
Transformationsmatrix [a, b, c, d, e, f] |
Vektorinhalte
extractPaths(pageIndex, region?) -> Array // Vector paths (lines, curves, shapes) on a page
extractRects(pageIndex, region?) -> Array // Axis-aligned rectangles detected from path segments
extractLines(pageIndex, region?) -> Array // Straight line segments detected from path data
Dokumentstruktur
getOutline() -> Array | null
Liefert die Lesezeichen / das Inhaltsverzeichnis des Dokuments. Gibt null zurück, wenn keine Gliederung vorhanden ist.
getAnnotations(pageIndex) -> Array
Liefert Annotations-Metadaten (Typ, Rechteck, Inhalt usw.) für eine Seite.
pageLabels() -> Array
Liefert die Seitenbeschriftungsbereiche. Gibt ein Array von Objekten zurück:
| Feld | Typ | Beschreibung |
|---|---|---|
startPage |
number |
Erste Seite in diesem Bereich |
style |
string |
Nummerierungsstil |
prefix |
string |
Beschriftungspräfix |
startValue |
number |
Startnummer |
xmpMetadata() -> object | null
Liefert die XMP-Metadaten. Gibt null zurück, wenn keine vorhanden sind. Zu den Objektfeldern gehören:
| Feld | Typ | Beschreibung |
|---|---|---|
dcTitle |
string | null |
Dokumenttitel |
dcCreator |
string[] | null |
Liste der Ersteller |
dcDescription |
string | null |
Beschreibung |
xmpCreatorTool |
string | null |
Erstellungswerkzeug |
xmpCreateDate |
string | null |
Erstellungsdatum |
xmpModifyDate |
string | null |
Änderungsdatum |
pdfProducer |
string | null |
PDF-Producer |
Formularfelder
getFormFields() -> Array
Liefert alle Formularfelder mit Name, Typ, Wert und Flags.
| Feld | Typ | Beschreibung |
|---|---|---|
name |
string |
Feldname |
fieldType |
string |
Feldtyp (Text, Checkbox usw.) |
value |
string |
Aktueller Wert |
flags |
number |
Feld-Flags |
const fields = doc.getFormFields();
for (const f of fields) {
console.log(`${f.name} (${f.fieldType}) = ${f.value}`);
}
hasXfa() -> boolean
Prüft, ob das Dokument XFA-Formulare enthält.
getFormFieldValue(name) -> any
Liefert einen Formularfeldwert anhand des Namens. Gibt je nach Feldtyp einen string, boolean oder null zurück.
setFormFieldValue(name, value) -> void
Setzt einen Formularfeldwert anhand des Namens.
| Parameter | Typ | Beschreibung |
|---|---|---|
name |
string |
Feldname |
value |
string | boolean |
Neuer Feldwert |
exportFormData(format?) -> Uint8Array
Exportiert Formulardaten als FDF (Standard) oder XFDF.
| Parameter | Typ | Standard | Beschreibung |
|---|---|---|---|
format |
string |
"fdf" |
Exportformat: "fdf" oder "xfdf" |
Formulare zusammenführen (Flatten)
flattenForms() // Flatten all form fields into page content
flattenFormsOnPage(pageIndex) // Flatten forms on a specific page
flattenWarnings() -> string[] // Warnings produced by the last flatten operation
Bearbeitung
Metadaten
| Methode | Parameter | Beschreibung |
|---|---|---|
setTitle(title) |
string |
Dokumenttitel setzen |
setAuthor(author) |
string |
Dokumentautor setzen |
setSubject(subject) |
string |
Dokumentbetreff setzen |
setKeywords(keywords) |
string |
Dokument-Schlüsselwörter setzen |
Seitendrehung
| Methode | Parameter | Beschreibung |
|---|---|---|
pageRotation(pageIndex) |
number |
Aktuelle Drehung abrufen (0, 90, 180, 270) |
setPageRotation(pageIndex, degrees) |
number, number |
Absolute Drehung setzen |
rotatePage(pageIndex, degrees) |
number, number |
Zur aktuellen Drehung hinzufügen |
rotateAllPages(degrees) |
number |
Alle Seiten drehen |
Seitenabmessungen
| Methode | Parameter | Beschreibung |
|---|---|---|
pageMediaBox(pageIndex) |
number |
MediaBox [llx, lly, urx, ury] abrufen |
setPageMediaBox(pageIndex, llx, lly, urx, ury) |
number, ... |
MediaBox setzen |
pageCropBox(pageIndex) |
number |
CropBox abrufen (kann null sein) |
setPageCropBox(pageIndex, llx, lly, urx, ury) |
number, ... |
CropBox setzen |
cropMargins(left, right, top, bottom) |
number, ... |
Alle Seitenränder beschneiden |
Seitenoperationen
deletePage(index) // Delete a page by index
movePage(fromIndex, toIndex) // Move a page to a new position
extractPages(pages) -> Uint8Array // Build a new PDF from the given page indices
Löschen / Whiteout
| Methode | Parameter | Beschreibung |
|---|---|---|
eraseRegion(pageIndex, llx, lly, urx, ury) |
number, ... |
Einen Bereich löschen |
eraseRegions(pageIndex, rects) |
number, Float32Array |
Mehrere Bereiche löschen |
clearEraseRegions(pageIndex) |
number |
Ausstehende Löschungen verwerfen |
Annotationen & Schwärzung
| Methode | Parameter | Beschreibung |
|---|---|---|
flattenPageAnnotations(pageIndex) |
number |
Annotationen auf der Seite zusammenführen |
flattenAllAnnotations() |
– | Alle Annotationen zusammenführen |
applyPageRedactions(pageIndex) |
number |
Schwärzungen auf der Seite anwenden |
applyAllRedactions() |
– | Alle Schwärzungen anwenden |
addRedaction(page, x0, y0, x1, y1, fill?) |
number, ... |
Ein Schwärzungsrechteck einreihen (optionale [r,g,b]-Füllung) |
redactionCount(page) |
number |
Für eine Seite eingereihte Schwärzungen zählen |
applyRedactionsDestructive(scrubMetadata?) |
boolean |
Inhalt destruktiv entfernen; gibt einen Schwärzungsbericht zurück |
sanitizeDocument(scrubMetadata?, removeJavascript?, removeEmbeddedFiles?) |
boolean, ... |
Metadaten, Skripte, eingebettete Dateien entfernen; gibt einen Bericht zurück |
Zusammenführen & Einbetten
mergeFrom(data) -> number
Führt Seiten aus einem anderen PDF zusammen. Gibt die Anzahl der zusammengeführten Seiten zurück.
| Parameter | Typ | Beschreibung |
|---|---|---|
data |
Uint8Array |
Die Bytes der Quell-PDF-Datei |
embedFile(name, data) -> void
Hängt eine Datei an das PDF an.
| Parameter | Typ | Beschreibung |
|---|---|---|
name |
string |
Dateiname für den Anhang |
data |
Uint8Array |
Dateiinhalt |
Bildbearbeitung
| Methode | Parameter | Beschreibung |
|---|---|---|
repositionImage(pageIndex, name, x, y) |
number, string, number, number |
Bild verschieben |
resizeImage(pageIndex, name, w, h) |
number, string, number, number |
Bildgröße ändern |
setImageBounds(pageIndex, name, x, y, w, h) |
number, string, ... |
Bildgrenzen setzen |
Klassifizierung & Auto-Extraktion
classifyDocument() -> string // Classify the whole document (e.g. born-digital vs scanned)
classifyPage(pageIndex) -> string // Classify a single page
extractTextAuto(pageIndex) -> string // Auto-pick native vs OCR extraction for a page
extractPageAuto(pageIndex, optionsJson?) -> string // Auto-extraction returning a structured JSON page
Validierung
validatePdfA(level) -> object // Validate against a PDF/A conformance level (e.g. "2b")
convertToPdfA(level) -> object // Convert toward a PDF/A level; returns a report
validatePdfUa(level?) -> object // Validate against PDF/UA accessibility
validatePdfX(level?) -> object // Validate against a PDF/X print level
Rendering
Erfordert das rendering-Feature.
| Methode | Parameter | Rückgabe | Beschreibung |
|---|---|---|---|
renderPage(pageIndex, dpi?) |
number, number |
Uint8Array |
Eine Seite als PNG-Bytes rendern (Standard 150 dpi) |
flattenToImages(dpi?) |
number |
Uint8Array |
Alle Seiten zu einem bildbasierten PDF zusammenführen |
OCR
Erfordert den wasm-ocr-Build. Siehe WasmOcrEngine.
extractTextOcr(pageIndex, engine) -> string
Führt die In-WASM-OCR-Pipeline auf einer Seite mit einer host-seitig erstellten WasmOcrEngine aus. Gibt den erkannten Text in Lesereihenfolge zurück.
const text = doc.extractTextOcr(0, engine);
Speichern
save() -> Uint8Array
Speichert das bearbeitete PDF als Bytes. saveToBytes() steht als Alias zur Verfügung.
saveWithOptions(compress?, garbageCollect?, linearize?) -> Uint8Array
Speichert mit expliziten Serialisierungsoptionen.
| Parameter | Typ | Standard | Beschreibung |
|---|---|---|---|
compress |
boolean |
true |
Objektstreams komprimieren |
garbageCollect |
boolean |
true |
Nicht referenzierte Objekte verwerfen |
linearize |
boolean |
false |
Ein linearisiertes PDF (“Fast Web View”) erzeugen |
saveEncryptedToBytes(password, ownerPassword?, allowPrint?, allowCopy?, allowModify?, allowAnnotate?) -> Uint8Array
Speichert mit AES-256-Verschlüsselung.
| Parameter | Typ | Standard | Beschreibung |
|---|---|---|---|
password |
string |
– | Benutzerpasswort |
ownerPassword |
string |
Benutzerpasswort | Eigentümerpasswort |
allowPrint |
boolean |
true |
Drucken erlauben |
allowCopy |
boolean |
true |
Kopieren erlauben |
allowModify |
boolean |
true |
Änderungen erlauben |
allowAnnotate |
boolean |
true |
Annotationen erlauben |
free()
Gibt den WASM-Speicher frei. Rufen Sie dies immer auf, wenn Sie mit dem Dokument fertig sind.
WasmPdfPageRegion
Ein Bereichs-Handle, das von WasmPdfDocument.within(pageIndex, region) zurückgegeben wird. Die Extraktionsmethoden sind auf das Rechteck eingeschränkt.
extractText() -> string // Plain text within the region
extractChars() -> Array // Characters within the region
extractWords() -> Array // Words within the region
extractTextLines() -> Array // Text lines within the region
extractTables() -> Array // Tables within the region
extractImages() -> Array // Images within the region
extractPaths() -> Array // Vector paths within the region
extractRects() -> Array // Rectangles within the region
extractLines() -> Array // Line segments within the region
extractTextOcr(engine?) -> string // OCR text within the region (wasm-ocr build)
WasmPdf
Factory-Klasse zur Erstellung neuer PDFs.
import { WasmPdf } from "pdf-oxide-wasm";
Statische Methoden
WasmPdf.fromMarkdown(content, title?, author?) -> WasmPdf // Create a PDF from Markdown text
WasmPdf.fromHtml(content, title?, author?) -> WasmPdf // Create a PDF from HTML
WasmPdf.fromText(content, title?, author?) -> WasmPdf // Create a PDF from plain text
WasmPdf.fromBytes(data) -> WasmPdf // Open an existing PDF from bytes for modification
WasmPdf.fromImageBytes(data) -> WasmPdf // Single-page PDF from one image (JPEG/PNG)
WasmPdf.fromMultipleImageBytes(imagesArray) -> WasmPdf // Multi-page PDF, one page per image
WasmPdf.merge(pdfs) -> WasmPdf // Merge an array of PDF byte buffers into one
WasmPdf.fromHtmlCss(html, css, fontBytes) -> WasmPdf // HTML + CSS with a single embedded font
WasmPdf.fromHtmlCssWithFonts(html, css, fonts) -> WasmPdf // HTML + CSS with multiple [name, bytes] fonts
| Parameter | Typ | Beschreibung |
|---|---|---|
content |
string |
Quellinhalt (Markdown / HTML / Text) |
title |
string | undefined |
Dokumenttitel |
author |
string | undefined |
Dokumentautor |
data |
Uint8Array |
Bytes einer PDF- oder Bilddatei |
imagesArray |
Uint8Array[] |
Array von Bilddatei-Bytes |
pdfs |
Uint8Array[] |
Array von zusammenzuführenden PDF-Datei-Bytes |
Instanzmethoden
toBytes() -> Uint8Array
Liefert das PDF als Bytes.
size -> number
PDF-Größe in Bytes (schreibgeschützter Getter).
const pdf = WasmPdf.fromMarkdown("# Hello World\n\nThis is a PDF.");
console.log(`PDF size: ${pdf.size} bytes`);
writeFileSync("output.pdf", pdf.toBytes());
WasmDocumentBuilder
Fluider, hardwarenaher Seitenlayout-Builder zum seitenweisen Zusammensetzen von PDFs. Verwenden Sie ihn zusammen mit WasmFluentPageBuilder.
import { WasmDocumentBuilder } from "pdf-oxide-wasm";
const builder = new WasmDocumentBuilder();
Dokument-Setup
new WasmDocumentBuilder() // Create an empty builder
title(title) // Set document title
author(author) // Set document author
subject(subject) // Set document subject
keywords(keywords) // Set document keywords
creator(creator) // Set the creator tool name
onOpen(script) // Set a document-level open JavaScript action
taggedPdfUa1() // Enable Tagged PDF / PDF/UA-1 output
language(lang) // Set the document language (e.g. "en-US")
roleMap(custom, standard) // Map a custom structure tag to a standard role
registerEmbeddedFont(name, font) // Register a WasmEmbeddedFont under a name
Seitenerstellung & Ausgabe
a4Page() -> WasmFluentPageBuilder // Start a new A4 page
letterPage() -> WasmFluentPageBuilder // Start a new US Letter page
page(width, height) -> WasmFluentPageBuilder // Start a custom-size page (points)
commitPage(page) // Commit a completed page builder
build() -> Uint8Array // Finish and return the PDF bytes
toBytesEncrypted(userPassword, ownerPassword?) -> Uint8Array // Finish with AES-256 encryption
WasmFluentPageBuilder
Seitenweiser Builder, der von a4Page() / letterPage() / page() zurückgegeben wird. Reihen Sie Operationen ein und committen Sie sie dann mit done(builder) (oder builder.commitPage(page)).
Text & Fluss
font(name, size) // Set the current font and size
at(x, y) // Move the cursor to an absolute position
text(text) // Draw text at the cursor
heading(level, text) // Draw a heading (level 1–6)
paragraph(text) // Draw a wrapped paragraph
space(points) // Advance the cursor vertically
horizontalRule() // Draw a horizontal rule
newline() // Advance to the next line
columns(columnCount, gapPt, text) // Lay text out in N balanced columns
footnote(refMark, noteText) // Add a footnote marker + bottom-of-page note
Inline-Runs
inline(text) // Append an inline text run
inlineBold(text) // Append a bold inline run
inlineItalic(text) // Append an italic inline run
inlineColor(r, g, b, text) // Append a colored inline run (RGB 0.0–1.0)
Link- & Formularaktionen
linkUrl(url) // Wrap the last element in a URL link
linkPage(page) // Link to another page index
linkNamed(destination) // Link to a named destination
linkJavascript(script) // Attach a JavaScript link action
onOpen(script) // Page open action
onClose(script) // Page close action
fieldKeystroke(script) // Keystroke JavaScript for the last field
fieldFormat(script) // Format JavaScript for the last field
fieldValidate(script) // Validate JavaScript for the last field
fieldCalculate(script) // Calculate JavaScript for the last field
Markup-Annotationen
highlight(r, g, b) // Highlight the last text run (RGB 0.0–1.0)
underline(r, g, b) // Underline the last text run
strikeout(r, g, b) // Strike out the last text run
squiggly(r, g, b) // Squiggly-underline the last text run
stickyNote(text) // Add a sticky note at the cursor
stickyNoteAt(x, y, text) // Add a sticky note at an absolute position
stamp(name) // Add a rubber-stamp annotation (e.g. "Approved")
freeText(x, y, w, h, text) // Add a free-text annotation box
watermark(text) // Add a text watermark
watermarkConfidential() // Add a "CONFIDENTIAL" watermark
watermarkDraft() // Add a "DRAFT" watermark
AcroForm-Widgets
textField(name, x, y, w, h, defaultValue?) // Add a text field
checkbox(name, x, y, w, h, checked) // Add a checkbox
comboBox(name, x, y, w, h, options, selected?) // Add a dropdown combo box
radioGroup(name, values, xs, ys, ws, hs, selected?) // Add a radio-button group (parallel arrays)
pushButton(name, x, y, w, h, caption) // Add a clickable push button
signatureField(name, x, y, w, h) // Add an unsigned signature placeholder
Barcodes & Bilder
barcode1d(barcodeType, data, x, y, w, h) // Draw a 1D barcode (type 0–7)
barcodeQr(data, x, y, size) // Draw a QR code
imageWithAlt(bytes, x, y, w, h, altText) // Embed an image with accessibility alt text
imageArtifact(bytes, x, y, w, h) // Embed a decorative image as an /Artifact
Grafik-Primitive
rect(x, y, w, h) // Stroked 1pt rectangle outline
filledRect(x, y, w, h, r, g, b) // Filled rectangle (RGB 0.0–1.0)
line(x1, y1, x2, y2) // 1pt black line
strokeRect(x, y, w, h, width, r, g, b) // Stroked rectangle, explicit width + color
strokeRectDashed(x, y, w, h, width, r, g, b, dash, phase) // Dashed rectangle border
strokeLine(x1, y1, x2, y2, width, r, g, b) // Line with explicit width + color
strokeLineDashed(x1, y1, x2, y2, width, r, g, b, dash, phase) // Dashed line
textInRect(x, y, w, h, text, align) // Lay text inside a rectangle (align 0/1/2)
Layout-Helfer & Abschluss
measure(text) -> number // Rendered width of text in the current font (points)
remainingSpace() -> number // Vertical space left on the page (points)
newPageSameSize() // Start a new page with the same dimensions
table(spec) // Draw a buffered table from a spec object
streamingTable(spec) -> WasmStreamingTable // Open a streaming table for large datasets
done(builder) // Commit this page's queued ops to the document builder
Ein table(spec)-Spezifikationsobjekt verwendet { columns: [{ header, width, align }], rows: [[...]], hasHeader }. Eine streamingTable(spec)-Spezifikation ergänzt { repeatHeader, mode, sampleRows, minColWidthPt, maxColWidthPt, maxRowspan, batchSize }.
WasmStreamingTable
Zeilen-streamendes Tabellen-Handle, das von WasmFluentPageBuilder.streamingTable(spec) zurückgegeben wird. Schieben Sie Zeilen inkrementell ein und rufen Sie dann finish() auf.
columnCount() -> number // Number of columns
pendingRowCount() -> number // Rows in the current un-flushed batch
batchCount() -> number // Number of completed batches
pushRow(cells) // Push one row (array of cell strings)
pushRowSpan(cells) // Push a row whose cells may carry rowspans
flush() // Flush the current batch
finish() // Finalize the table and replay it into the page
WasmEmbeddedFont
Eine Schrift, die über WasmDocumentBuilder.registerEmbeddedFont zum Einbetten registriert wird.
WasmEmbeddedFont.fromBytes(data, name?) -> WasmEmbeddedFont // Load a TTF/OTF font from bytes
font.name -> string // The font's resolved name (getter)
Seitenvorlagen
Wiederverwendbare Kopf-/Fußzeilen-Möblierung, die über mehrere Seiten hinweg angewendet wird.
WasmArtifactStyle
new WasmArtifactStyle() // Default style
font(name, size) -> this // Set font family and size
bold() -> this // Make the text bold
color(r, g, b) -> this // Set the text color (RGB 0.0–1.0)
WasmArtifact
new WasmArtifact() // Empty artifact
WasmArtifact.left(text) -> WasmArtifact // Left-aligned artifact text
WasmArtifact.center(text) -> WasmArtifact // Center-aligned artifact text
WasmArtifact.right(text) -> WasmArtifact // Right-aligned artifact text
withStyle(style) -> this // Apply a WasmArtifactStyle
withOffset(offset) -> this // Set the vertical offset from the edge
WasmHeader / WasmFooter
new WasmHeader() // Empty header (WasmFooter is identical)
WasmHeader.left(text) -> WasmHeader // Left-aligned header text
WasmHeader.center(text) -> WasmHeader // Center-aligned header text
WasmHeader.right(text) -> WasmHeader // Right-aligned header text
WasmPageTemplate
new WasmPageTemplate() // Empty template
header(header) -> this // Set the page header artifact
footer(footer) -> this // Set the page footer artifact
skipFirstPage() -> this // Omit header/footer on the first page
Digitale Signaturen
Erfordert das signatures-Feature.
WasmCertificate
WasmCertificate.load(data) -> WasmCertificate // Load a DER certificate + key bundle
WasmCertificate.loadPem(certPem, keyPem) -> WasmCertificate // Load from PEM cert + key strings
WasmCertificate.loadPkcs12(data, password) -> WasmCertificate // Load from a PKCS#12 (.p12/.pfx) blob
cert.subject -> string // Subject distinguished name (getter)
cert.issuer -> string // Issuer distinguished name (getter)
cert.serial -> string // Serial number (getter)
cert.validity -> bigint[] // [notBefore, notAfter] as unix seconds (getter)
cert.isValid -> boolean // Whether the certificate is currently valid (getter)
WasmSignature
Wird von WasmPdfDocument.signatures() zurückgegeben.
sig.signerName -> string | null // Signer common name (getter)
sig.reason -> string | null // Signing reason (getter)
sig.location -> string | null // Signing location (getter)
sig.contactInfo -> string | null // Signer contact info (getter)
sig.signingTime -> bigint | null // Signing time as unix seconds (getter)
sig.coversWholeDocument -> boolean // Whether the signature covers the entire file (getter)
sig.padesLevel -> PadesLevel // PAdES baseline level of the signature (getter)
sig.verify() -> boolean // Verify the signature cryptographically
sig.verifyDetached(pdfData) -> boolean // Verify including a messageDigest check against the bytes
WasmTimestamp
WasmTimestamp.parse(data) -> WasmTimestamp // Parse a DER TimeStampToken / TSTInfo
ts.time -> bigint // Timestamp time as unix seconds (getter)
ts.serial -> string // Serial number (getter)
ts.policyOid -> string // TSA policy OID (getter)
ts.tsaName -> string // TSA name (getter)
ts.hashAlgorithm -> number // Imprint hash algorithm id (getter)
ts.messageImprint -> Uint8Array // The message imprint digest (getter)
ts.verify() -> boolean // Verify the timestamp token
WasmRevocationMaterial
Offline-Validierungsmaterial für PAdES-B-LT zur Verwendung mit signPdfBytesPades.
new WasmRevocationMaterial() // Empty material set
addCert(der) // Add a DER X.509 certificate
addCrl(der) // Add a DER CRL
addOcsp(der) // Add a DER OCSP response
Dss
Ein geparster Document Security Store, der von WasmPdfDocument.dss() zurückgegeben wird.
dss.certCount -> number // Number of DER certificates (getter)
getCert(i) -> Uint8Array | undefined // i-th DER certificate
dss.crlCount -> number // Number of DER CRLs (getter)
getCrl(i) -> Uint8Array | undefined // i-th DER CRL
dss.ocspCount -> number // Number of DER OCSP responses (getter)
getOcsp(i) -> Uint8Array | undefined // i-th DER OCSP response
dss.vri -> string[] // Per-signature VRI keys (uppercase-hex SHA-1 of /Contents) (getter)
OCR
OCR läuft vollständig in-WASM über das reine Rust-Backend tract im separaten wasm-ocr-Build. Modelle werden host-seitig bereitgestellt — laden Sie die ONNX-Dateien für Detektor/Erkenner sowie das Wörterbuch (siehe modelManifest()) und übergeben Sie die Bytes anschließend an den Konstruktor.
WasmOcrEngine
new WasmOcrEngine(detModel, recModel, dict, config?) // Build from host-supplied model bytes
engine.ocrImage(imageBytes) -> string // OCR a raw image (PNG/JPEG/TIFF); returns JSON {text, confidence, spans}
| Parameter | Typ | Beschreibung |
|---|---|---|
detModel |
Uint8Array |
DBNet-Detektor-ONNX-Bytes |
recModel |
Uint8Array |
SVTR-Erkenner-ONNX-Bytes |
dict |
string |
Zeichenwörterbuch des Erkenners, ein Zeichen pro Zeile |
config |
WasmOcrConfig | undefined |
Reserviert (es werden abgestimmte Standardwerte verwendet) |
WasmOcrConfig
new WasmOcrConfig() // OCR configuration object (reserved for future tuning)
Enums
Align
Diskriminante für die Text-/Zellenausrichtung, die von textInRect und Tabellenspalten-Spezifikationen verwendet wird.
Align.Left // 0
Align.Center // 1
Align.Right // 2
PadesLevel
PAdES-Baseline-Level, verwendet von signPdfBytesPades und WasmSignature.padesLevel.
PadesLevel.BB // 0 — signed attrs incl. ESS signing-certificate-v2
PadesLevel.BT // 1 — B-B + RFC 3161 signature-time-stamp
PadesLevel.BLt // 2 — B-T + Document Security Store (DSS/VRI)
PadesLevel.BLta // 3 — B-LT + document-scoped /DocTimeStamp
Feature-Verfügbarkeit
Einige Features sind hinter Rust-Build-Features freigeschaltet. Das Standardpaket pdf-oxide-wasm aktiviert den gängigen Funktionsumfang; OCR wird im separaten wasm-ocr-Build ausgeliefert.
| Feature | WASM | Hinweise |
|---|---|---|
| Textextraktion | Ja | Volle Unterstützung |
| Strukturierte Extraktion | Ja | Zeichen, Spans, Wörter, Zeilen, Tabellen |
| PDF-Erstellung | Ja | Markdown, HTML, Text, Bilder, DocumentBuilder |
| PDF-Bearbeitung | Ja | Metadaten, Drehung, Abmessungen, Löschen, Seiten |
| Formularfelder | Ja | Lesen, Schreiben, Exportieren, Flatten, Erstellen |
| Suche | Ja | Volle Regex-Unterstützung |
| Verschlüsselung | Ja | AES-256 Lesen und Schreiben |
| Annotationen | Ja | Lesen, Flatten, Schwärzen, Sanitisieren |
| PDFs zusammenführen / aufteilen | Ja | Seiten zusammenführen und nach Lesezeichen aufteilen |
| Eingebettete Dateien | Ja | Dateien an PDFs anhängen |
| Seitenbeschriftungen / XMP | Ja | Seitenbeschriftungen und XMP-Metadaten lesen |
| Office-Round-Trip | Ja | DOCX/PPTX/XLSX importieren und exportieren |
| Validierung | Ja | PDF/A, PDF/UA, PDF/X |
| Barcodes | Ja (barcodes) |
1D + QR als SVG oder Seitenbilder |
| Rendering | Ja (rendering) |
Seite → PNG, zu Bildern zusammenführen |
| Digitale Signaturen | Ja (signatures) |
Signieren, PAdES B-LT, Verifizieren, Zeitstempel |
| OCR | wasm-ocr-Build |
In-WASM-tract-OCR; Modelle host-seitig geladen |
Fehlerbehandlung
Alle Methoden, die fehlschlagen können, werfen JavaScript-Error-Objekte:
try {
const doc = new WasmPdfDocument(new Uint8Array([0, 1, 2]));
} catch (e) {
console.error(`Failed to open: ${e.message}`);
}
TypeScript
Vollständige Typdefinitionen sind im Paket enthalten:
import { WasmPdfDocument, WasmPdf } from "pdf-oxide-wasm";
const doc: WasmPdfDocument = new WasmPdfDocument(bytes);
const text: string = doc.extractText(0);
const pdf: WasmPdf = WasmPdf.fromMarkdown("# Hello");
Other Language Bindings
PDF Oxide bietet native Bindings für jedes wichtige Ökosystem: Rust, Python, Node.js, C#, Golang, Java, PHP, Ruby, C++, Swift, Kotlin, Dart, R, Julia, Zig, Scala, Clojure, Objective-C und Elixir.
Nächste Schritte
- Typen & Enums — alle gemeinsamen Typen und Enums
- Page-API-Referenz — konsistente Iteration pro Seite über alle Bindings hinweg
- Erste Schritte mit WASM — Tutorial