Довідник JavaScript API
PDF Oxide надає прив’язки WebAssembly для JavaScript і TypeScript. npm-пакет pdf-oxide-wasm працює в Node.js, браузерах, бандлерах, Deno та Cloudflare Workers.
npm install pdf-oxide-wasm
Багатоцільове пакування (v0.3.38)
pdf-oxide-wasm тепер постачається з трьома збірками одночасно через умовні експорти package.json. Оберіть підшлях, що відповідає вашому рантайму — автоматично маршрутизований імпорт верхнього рівня також коректно резолвиться через поле exports для більшості середовищ.
| Підшлях | Ціль |
|---|---|
pdf-oxide-wasm/nodejs |
Node.js (CommonJS + ESM) |
pdf-oxide-wasm/bundler |
Vite, webpack, Rollup, esbuild, Bun |
pdf-oxide-wasm/web |
Браузери, 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();
Це усуває помилку ReferenceError: Can't find variable: __dirname, яку браузерні бандлери видавали до версії v0.3.38.
Про Rust API див. Довідник Rust API. Про Python API див. Довідник Python API. Деталі типів — у розділі Типи та enum’и.
Деякі методи закриті за збірковими можливостями Rust (
rendering,signatures,barcodes,ocr-tract). Стандартний пакетpdf-oxide-wasmвмикає поширений набір; OCR постачається в окремій збірціwasm-ocr. Див. Доступність можливостей.
Module Functions
Вільні функції, що експортуються на верхньому рівні пакета.
import {
setLogLevel, disableLogging,
generateBarcodeSvg, generateQrSvg,
planSplitByBookmarks, splitByBookmarks,
setCryptoPolicy, cryptoPolicy, cryptoInventory, cryptoCbom,
modelManifest, prefetchAvailable,
signPdfBytes, signPdfBytesPades, hasDocumentTimestamp,
} from "pdf-oxide-wasm";
Логування
setLogLevel(level) // Set log verbosity: "off" | "error" | "warn" | "info" | "debug" | "trace"
disableLogging() // Silence all log output
Штрихкоди
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
Розбиття за закладками
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)
Криптополітика
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)
Постачання OCR-моделей
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)
Підписування (вільні функції)
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
Головний клас для відкриття, видобування, редагування та збереження PDF.
import { WasmPdfDocument } from "pdf-oxide-wasm";
Конструктор
new WasmPdfDocument(data, password?)
Завантажує PDF-документ із сирих байтів.
| Параметр | Тип | Опис |
|---|---|---|
data |
Uint8Array |
Вміст PDF-файлу |
password |
string | undefined |
Необов’язковий пароль для зашифрованих PDF |
Кидає: Error, якщо PDF недійсний або його не вдається розібрати.
const bytes = new Uint8Array(readFileSync("document.pdf"));
const doc = new WasmPdfDocument(bytes);
Статичні конструктори
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
Базове читання (тільки для читання)
pageCount() -> number
Повертає кількість сторінок у документі.
version() -> Uint8Array
Повертає версію PDF у вигляді [major, minor].
const [major, minor] = doc.version();
console.log(`PDF ${major}.${minor}`);
authenticate(password) -> boolean
Розшифровує зашифрований PDF. Повертає true, якщо автентифікація успішна.
| Параметр | Тип | Опис |
|---|---|---|
password |
string |
Рядок пароля |
hasStructureTree() -> boolean
Перевіряє, чи є документ тегованим PDF зі структурним деревом.
Інспекція підписів
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
Видобування тексту
extractText(pageIndex, region?) -> string
Видобуває звичайний текст з однієї сторінки. Передайте необов’язкову область [x, y, w, h], щоб обмежити видобування.
| Параметр | Тип | Опис |
|---|---|---|
pageIndex |
number |
Номер сторінки, починаючи з нуля |
region |
number[] | undefined |
Необов’язкове обрізання [x, y, width, height] |
const text = doc.extractText(0);
extractAllText() -> string
Видобуває звичайний текст з усіх сторінок, розділений символами переведення сторінки (form feed).
extractStructured(pageIndex) -> string
Видобуває структуроване JSON-представлення сторінки (блоки, рядки, стилізація).
extractChars(pageIndex, region?) -> Array
Видобуває окремі символи з точним позиціонуванням та метаданими шрифту.
| Параметр | Тип | Опис |
|---|---|---|
pageIndex |
number |
Номер сторінки, починаючи з нуля |
region |
number[] | undefined |
Необов’язкове обрізання [x, y, width, height] |
Повертає: масив об’єктів з полями:
| Поле | Тип | Опис |
|---|---|---|
char |
string |
Символ |
bbox |
{x, y, width, height} |
Обмежувальний прямокутник |
fontName |
string |
Назва шрифту |
fontSize |
number |
Розмір шрифту в пунктах |
fontWeight |
string |
Насиченість (Normal, Bold тощо) |
isItalic |
boolean |
Ознака курсиву |
color |
{r, g, b} |
Колір RGB (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
Повертає спани, символи та розміри сторінки за один прохід видобування. Ефективніше, ніж окремі виклики extractSpans() + extractChars(). Передайте "column_aware" для багатоколонкових PDF.
| Параметр | Тип | Опис |
|---|---|---|
pageIndex |
number |
Номер сторінки, починаючи з нуля |
readingOrder |
string | undefined |
"column_aware" або "top_to_bottom" (за замовчуванням) |
Повертає: об’єкт з полями:
| Поле | Тип | Опис |
|---|---|---|
spans |
Array |
Масив об’єктів-спанів |
chars |
Array |
Масив об’єктів-символів |
pageWidth |
number |
Ширина сторінки в пунктах PDF |
pageHeight |
number |
Висота сторінки в пунктах PDF |
text |
string |
Повний текстовий вміст |
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
Видобуває стилізовані текстові спани з метаданими шрифту. Передайте "column_aware" як readingOrder для багатоколонкових PDF.
| Параметр | Тип | Опис |
|---|---|---|
pageIndex |
number |
Номер сторінки, починаючи з нуля |
region |
number[] | undefined |
Необов’язкове обрізання [x, y, width, height] |
readingOrder |
string | undefined |
"column_aware" або "top_to_bottom" (за замовчуванням) |
Повертає: масив об’єктів з полями:
| Поле | Тип | Опис |
|---|---|---|
text |
string |
Текстовий вміст |
bbox |
{x, y, width, height} |
Обмежувальний прямокутник |
fontName |
string |
Назва шрифту |
fontSize |
number |
Розмір шрифту в пунктах |
fontWeight |
string |
Насиченість (Normal, Bold тощо) |
isItalic |
boolean |
Ознака курсиву |
isMonospace |
boolean |
Чи є шрифт моноширинним |
charWidths |
number[] |
Ширина просування для кожного гліфа |
color |
{r, g, b} |
Колір RGB (0.0–1.0) |
const spans = doc.extractSpans(0);
for (const span of spans) {
console.log(`"${span.text}" size=${span.fontSize}`);
}
Слова, рядки, таблиці
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)
Колонтитули та артефакти
Виявляйте та видаляйте чи стирайте наскрізні верхні й нижні колонтитули та артефакти оформлення сторінки.
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
Видобування за областю
within(pageIndex, region) -> WasmPdfPageRegion
Обмежує подальше видобування прямокутною областю сторінки. region — це [x, y, width, height]. Див. WasmPdfPageRegion.
const region = doc.within(0, [50, 600, 400, 150]);
const text = region.extractText();
Конвертація форматів
toMarkdown(pageIndex, detectHeadings?, includeImages?, includeFormFields?) -> string
Конвертує одну сторінку в Markdown.
| Параметр | Тип | За замовчуванням | Опис |
|---|---|---|---|
pageIndex |
number |
– | Номер сторінки, починаючи з нуля |
detectHeadings |
boolean |
true |
Виявляти заголовки за розміром шрифту |
includeImages |
boolean |
true |
Включати зображення |
includeFormFields |
boolean |
true |
Включати значення полів форми |
toMarkdownAll(detectHeadings?, includeImages?, includeFormFields?) -> string
Конвертує всі сторінки в Markdown.
toHtml(pageIndex, preserveLayout?, detectHeadings?, includeFormFields?) -> string
Конвертує одну сторінку в HTML.
| Параметр | Тип | За замовчуванням | Опис |
|---|---|---|---|
pageIndex |
number |
– | Номер сторінки, починаючи з нуля |
preserveLayout |
boolean |
false |
Зберігати візуальну розмітку |
detectHeadings |
boolean |
true |
Виявляти заголовки |
includeFormFields |
boolean |
true |
Включати значення полів форми |
toHtmlAll(preserveLayout?, detectHeadings?, includeFormFields?) -> string
Конвертує всі сторінки в HTML.
toPlainText(pageIndex) -> string
Конвертує одну сторінку у звичайний текст.
toPlainTextAll() -> string
Конвертує всі сторінки у звичайний текст.
Двостороння конвертація Office
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
Пошук
search(pattern, caseInsensitive?, literal?, wholeWord?, maxResults?) -> Array
Шукає текст по всіх сторінках.
| Параметр | Тип | За замовчуванням | Опис |
|---|---|---|---|
pattern |
string |
– | Шаблон пошуку (рядок або regex) |
caseInsensitive |
boolean |
false |
Пошук без урахування регістру |
literal |
boolean |
false |
Трактувати шаблон як буквальний рядок |
wholeWord |
boolean |
false |
Збігатися лише з цілими словами |
maxResults |
number |
0 |
Максимум результатів (0 = без обмежень) |
Повертає: масив об’єктів з полями:
| Поле | Тип | Опис |
|---|---|---|
page |
number |
Номер сторінки |
text |
string |
Знайдений текст |
bbox |
object |
Обмежувальний прямокутник |
startIndex |
number |
Початковий індекс у тексті сторінки |
endIndex |
number |
Кінцевий індекс у тексті сторінки |
searchPage(pageIndex, pattern, caseInsensitive?, literal?, wholeWord?, maxResults?) -> Array
Шукає текст у межах однієї сторінки.
Інформація про зображення
extractImages(pageIndex) -> Array
Повертає метадані зображень сторінки.
| Поле | Тип | Опис |
|---|---|---|
width |
number |
Ширина зображення в пікселях |
height |
number |
Висота зображення в пікселях |
colorSpace |
string |
Колірний простір (напр. DeviceRGB) |
bitsPerComponent |
number |
Біт на колірний канал |
bbox |
object |
Позиція на сторінці |
extractImageBytes(pageIndex) -> Array
Видобуває сирі байти зображень зі сторінки. Повертає масив об’єктів:
| Поле | Тип | Опис |
|---|---|---|
width |
number |
Ширина зображення в пікселях |
height |
number |
Висота зображення в пікселях |
data |
Uint8Array |
Сирі байти зображення |
format |
string |
Формат зображення |
pageImages(pageIndex) -> Array
Повертає назви та межі зображень для операцій позиціонування.
| Поле | Тип | Опис |
|---|---|---|
name |
string |
Назва XObject |
bounds |
number[] |
[x, y, width, height] |
matrix |
number[] |
Матриця перетворення [a, b, c, d, e, f] |
Векторний вміст
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
Структура документа
getOutline() -> Array | null
Повертає закладки документа / зміст. Повертає null, якщо схеми (outline) немає.
getAnnotations(pageIndex) -> Array
Повертає метадані анотацій (тип, прямокутник, вміст тощо) для сторінки.
pageLabels() -> Array
Повертає діапазони міток сторінок. Повертає масив об’єктів:
| Поле | Тип | Опис |
|---|---|---|
startPage |
number |
Перша сторінка в цьому діапазоні |
style |
string |
Стиль нумерації |
prefix |
string |
Префікс мітки |
startValue |
number |
Початкове число |
xmpMetadata() -> object | null
Повертає метадані XMP. Повертає null, якщо їх немає. Поля об’єкта включають:
| Поле | Тип | Опис |
|---|---|---|
dcTitle |
string | null |
Назва документа |
dcCreator |
string[] | null |
Список авторів |
dcDescription |
string | null |
Опис |
xmpCreatorTool |
string | null |
Інструмент-творець |
xmpCreateDate |
string | null |
Дата створення |
xmpModifyDate |
string | null |
Дата зміни |
pdfProducer |
string | null |
Виробник PDF |
Поля форм
getFormFields() -> Array
Повертає всі поля форми з назвою, типом, значенням і прапорцями.
| Поле | Тип | Опис |
|---|---|---|
name |
string |
Назва поля |
fieldType |
string |
Тип поля (text, checkbox тощо) |
value |
string |
Поточне значення |
flags |
number |
Прапорці поля |
const fields = doc.getFormFields();
for (const f of fields) {
console.log(`${f.name} (${f.fieldType}) = ${f.value}`);
}
hasXfa() -> boolean
Перевіряє, чи містить документ форми XFA.
getFormFieldValue(name) -> any
Повертає значення поля форми за назвою. Повертає string, boolean чи null залежно від типу поля.
setFormFieldValue(name, value) -> void
Встановлює значення поля форми за назвою.
| Параметр | Тип | Опис |
|---|---|---|
name |
string |
Назва поля |
value |
string | boolean |
Нове значення поля |
exportFormData(format?) -> Uint8Array
Експортує дані форми у форматі FDF (за замовчуванням) або XFDF.
| Параметр | Тип | За замовчуванням | Опис |
|---|---|---|---|
format |
string |
"fdf" |
Формат експорту: "fdf" або "xfdf" |
Розплющення форм
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
Редагування
Метадані
| Метод | Параметри | Опис |
|---|---|---|
setTitle(title) |
string |
Встановити назву документа |
setAuthor(author) |
string |
Встановити автора документа |
setSubject(subject) |
string |
Встановити тему документа |
setKeywords(keywords) |
string |
Встановити ключові слова документа |
Поворот сторінки
| Метод | Параметри | Опис |
|---|---|---|
pageRotation(pageIndex) |
number |
Отримати поточний поворот (0, 90, 180, 270) |
setPageRotation(pageIndex, degrees) |
number, number |
Встановити абсолютний поворот |
rotatePage(pageIndex, degrees) |
number, number |
Додати до поточного повороту |
rotateAllPages(degrees) |
number |
Повернути всі сторінки |
Розміри сторінки
| Метод | Параметри | Опис |
|---|---|---|
pageMediaBox(pageIndex) |
number |
Отримати MediaBox [llx, lly, urx, ury] |
setPageMediaBox(pageIndex, llx, lly, urx, ury) |
number, ... |
Встановити MediaBox |
pageCropBox(pageIndex) |
number |
Отримати CropBox (може бути null) |
setPageCropBox(pageIndex, llx, lly, urx, ury) |
number, ... |
Встановити CropBox |
cropMargins(left, right, top, bottom) |
number, ... |
Обрізати всі поля сторінки |
Операції зі сторінками
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
Стирання / забілювання
| Метод | Параметри | Опис |
|---|---|---|
eraseRegion(pageIndex, llx, lly, urx, ury) |
number, ... |
Стерти область |
eraseRegions(pageIndex, rects) |
number, Float32Array |
Стерти кілька областей |
clearEraseRegions(pageIndex) |
number |
Очистити заплановані стирання |
Анотації та редагування (redaction)
| Метод | Параметри | Опис |
|---|---|---|
flattenPageAnnotations(pageIndex) |
number |
Розплющити анотації на сторінці |
flattenAllAnnotations() |
– | Розплющити всі анотації |
applyPageRedactions(pageIndex) |
number |
Застосувати редагування на сторінці |
applyAllRedactions() |
– | Застосувати всі редагування |
addRedaction(page, x0, y0, x1, y1, fill?) |
number, ... |
Запланувати прямокутник редагування (необов’язкова заливка [r,g,b]) |
redactionCount(page) |
number |
Підрахувати редагування, заплановані для сторінки |
applyRedactionsDestructive(scrubMetadata?) |
boolean |
Деструктивно видалити вміст; повертає звіт про редагування |
sanitizeDocument(scrubMetadata?, removeJavascript?, removeEmbeddedFiles?) |
boolean, ... |
Видалити метадані, скрипти, вбудовані файли; повертає звіт |
Злиття та вбудовування
mergeFrom(data) -> number
Зливає сторінки з іншого PDF. Повертає кількість злитих сторінок.
| Параметр | Тип | Опис |
|---|---|---|
data |
Uint8Array |
Байти вихідного PDF-файлу |
embedFile(name, data) -> void
Прикріплює файл до PDF.
| Параметр | Тип | Опис |
|---|---|---|
name |
string |
Ім’я файлу для вкладення |
data |
Uint8Array |
Вміст файлу |
Маніпуляції із зображеннями
| Метод | Параметри | Опис |
|---|---|---|
repositionImage(pageIndex, name, x, y) |
number, string, number, number |
Перемістити зображення |
resizeImage(pageIndex, name, w, h) |
number, string, number, number |
Змінити розмір зображення |
setImageBounds(pageIndex, name, x, y, w, h) |
number, string, ... |
Встановити межі зображення |
Класифікація та автовидобування
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
Валідація
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.
| Метод | Параметри | Повертає | Опис |
|---|---|---|---|
renderPage(pageIndex, dpi?) |
number, number |
Uint8Array |
Відрендерити сторінку в байти PNG (за замовчуванням 150 dpi) |
flattenToImages(dpi?) |
number |
Uint8Array |
Розплющити всі сторінки в PDF на основі зображень |
OCR
Потребує збірки wasm-ocr. Див. WasmOcrEngine.
extractTextOcr(pageIndex, engine) -> string
Запускає вбудований у WASM конвеєр OCR на сторінці за допомогою побудованого на стороні хоста WasmOcrEngine. Повертає розпізнаний текст у порядку читання.
const text = doc.extractTextOcr(0, engine);
Збереження
save() -> Uint8Array
Зберігає відредагований PDF у вигляді байтів. Доступний псевдонім saveToBytes().
saveWithOptions(compress?, garbageCollect?, linearize?) -> Uint8Array
Зберігає з явними параметрами серіалізації.
| Параметр | Тип | За замовчуванням | Опис |
|---|---|---|---|
compress |
boolean |
true |
Стискати потоки об’єктів |
garbageCollect |
boolean |
true |
Відкидати об’єкти без посилань |
linearize |
boolean |
false |
Створити лінеаризований PDF («fast web view») |
saveEncryptedToBytes(password, ownerPassword?, allowPrint?, allowCopy?, allowModify?, allowAnnotate?) -> Uint8Array
Зберігає із шифруванням AES-256.
| Параметр | Тип | За замовчуванням | Опис |
|---|---|---|---|
password |
string |
– | Пароль користувача |
ownerPassword |
string |
пароль користувача | Пароль власника |
allowPrint |
boolean |
true |
Дозволити друк |
allowCopy |
boolean |
true |
Дозволити копіювання |
allowModify |
boolean |
true |
Дозволити зміну |
allowAnnotate |
boolean |
true |
Дозволити анотації |
free()
Звільняє пам’ять WASM. Завжди викликайте це, коли завершили роботу з документом.
WasmPdfPageRegion
Дескриптор області, що повертається WasmPdfDocument.within(pageIndex, region). Методи видобування обмежені прямокутником.
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
Фабричний клас для створення нових PDF.
import { WasmPdf } from "pdf-oxide-wasm";
Статичні методи
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
| Параметр | Тип | Опис |
|---|---|---|
content |
string |
Вихідний вміст (Markdown / HTML / текст) |
title |
string | undefined |
Назва документа |
author |
string | undefined |
Автор документа |
data |
Uint8Array |
Байти PDF- чи файлу зображення |
imagesArray |
Uint8Array[] |
Масив байтів файлів зображень |
pdfs |
Uint8Array[] |
Масив байтів PDF-файлів для злиття |
Методи екземпляра
toBytes() -> Uint8Array
Повертає PDF у вигляді байтів.
size -> number
Розмір PDF у байтах (геттер тільки для читання).
const pdf = WasmPdf.fromMarkdown("# Hello World\n\nThis is a PDF.");
console.log(`PDF size: ${pdf.size} bytes`);
writeFileSync("output.pdf", pdf.toBytes());
WasmDocumentBuilder
Текучий (fluent) низькорівневий конструктор розмітки сторінок для покрокового складання PDF. Поєднуйте з WasmFluentPageBuilder.
import { WasmDocumentBuilder } from "pdf-oxide-wasm";
const builder = new WasmDocumentBuilder();
Налаштування документа
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
Створення сторінок та вивід
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
Постраничний конструктор, що повертається a4Page() / letterPage() / page(). Поставте операції в чергу, а потім зафіксуйте через done(builder) (або builder.commitPage(page)).
Текст і потік
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)
Дії посилань і форм
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
Анотації розмітки
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
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
Штрихкоди та зображення
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
Графічні примітиви
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)
Помічники розмітки та завершення
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
Об’єкт-специфікація table(spec) використовує { columns: [{ header, width, align }], rows: [[...]], hasHeader }. Специфікація streamingTable(spec) додає { repeatHeader, mode, sampleRows, minColWidthPt, maxColWidthPt, maxRowspan, batchSize }.
WasmStreamingTable
Дескриптор таблиці з потоковим додаванням рядків, що повертається WasmFluentPageBuilder.streamingTable(spec). Додавайте рядки поступово, а потім викличте finish().
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
Шрифт, зареєстрований для вбудовування через WasmDocumentBuilder.registerEmbeddedFont.
WasmEmbeddedFont.fromBytes(data, name?) -> WasmEmbeddedFont // Load a TTF/OTF font from bytes
font.name -> string // The font's resolved name (getter)
Шаблони сторінок
Багаторазове оформлення колонтитулів, що застосовується до всіх сторінок.
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
Цифрові підписи
Потребує можливості signatures.
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
Повертається WasmPdfDocument.signatures().
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
Офлайн-матеріал валідації PAdES-B-LT для 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
Розібраний Document Security Store, що повертається WasmPdfDocument.dss().
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 виконується повністю всередині WASM через бекенд tract на чистому Rust в окремій збірці wasm-ocr. Моделі доставляються на стороні хоста — завантажте ONNX-файли детектора/розпізнавача та словник (див. modelManifest()), а потім передайте байти в конструктор.
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}
| Параметр | Тип | Опис |
|---|---|---|
detModel |
Uint8Array |
Байти ONNX-детектора DBNet |
recModel |
Uint8Array |
Байти ONNX-розпізнавача SVTR |
dict |
string |
Символьний словник розпізнавача, по одному символу на рядок |
config |
WasmOcrConfig | undefined |
Зарезервовано (використовуються налаштовані значення за замовчуванням) |
WasmOcrConfig
new WasmOcrConfig() // OCR configuration object (reserved for future tuning)
Enum’и
Align
Дискримінант вирівнювання тексту/комірки, що використовується textInRect та специфікаціями колонок таблиці.
Align.Left // 0
Align.Center // 1
Align.Right // 2
PadesLevel
Базовий рівень PAdES, що використовується signPdfBytesPades та 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
Доступність можливостей
Деякі можливості закриті за збірковими можливостями Rust. Стандартний пакет pdf-oxide-wasm вмикає поширений набір; OCR постачається в окремій збірці wasm-ocr.
| Можливість | WASM | Примітки |
|---|---|---|
| Видобування тексту | Так | Повна підтримка |
| Структуроване видобування | Так | Символи, спани, слова, рядки, таблиці |
| Створення PDF | Так | Markdown, HTML, текст, зображення, DocumentBuilder |
| Редагування PDF | Так | Метадані, поворот, розміри, стирання, сторінки |
| Поля форм | Так | Читання, запис, експорт, розплющення, побудова |
| Пошук | Так | Повна підтримка regex |
| Шифрування | Так | Читання й запис AES-256 |
| Анотації | Так | Читання, розплющення, редагування, санітизація |
| Злиття / розбиття PDF | Так | Злиття сторінок і розбиття за закладками |
| Вбудовані файли | Так | Прикріплення файлів до PDF |
| Мітки сторінок / XMP | Так | Читання міток сторінок і метаданих XMP |
| Двостороння конвертація Office | Так | Імпорт та експорт DOCX/PPTX/XLSX |
| Валідація | Так | PDF/A, PDF/UA, PDF/X |
| Штрихкоди | Так (barcodes) |
1D + QR як SVG чи зображення сторінки |
| Рендеринг | Так (rendering) |
Сторінка → PNG, розплющення в зображення |
| Цифрові підписи | Так (signatures) |
Підписування, PAdES B-LT, перевірка, мітки часу |
| OCR | збірка wasm-ocr |
OCR на tract всередині WASM; моделі завантажуються на стороні хоста |
Обробка помилок
Усі методи, що можуть завершитися невдало, кидають об’єкти JavaScript Error:
try {
const doc = new WasmPdfDocument(new Uint8Array([0, 1, 2]));
} catch (e) {
console.error(`Failed to open: ${e.message}`);
}
TypeScript
Повні визначення типів включені до пакета:
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 надає нативні прив’язки для всіх основних екосистем: Rust, Python, Node.js, C#, Golang, Java, PHP, Ruby, C++, Swift, Kotlin, Dart, R, Julia, Zig, Scala, Clojure, Objective-C та Elixir.
Наступні кроки
- Типи та переліки — усі спільні типи та переліки
- Довідник API сторінки — узгоджена ітерація по сторінках для всіх прив’язок
- Початок роботи з WASM — посібник