Довідник JavaScript API
PDF Oxide надає WebAssembly-обгортки для JavaScript та TypeScript. npm-пакет pdf-oxide-wasm працює як у Node.js, так і в браузерах.
npm install pdf-oxide-wasm
Для API Rust дивіться Довідник API Rust. Для API Python дивіться Довідник Python API. Для деталей типів дивіться Типи та Enum.
WasmPdfDocument
Основний клас для відкриття, вилучення, редагування та збереження PDF.
import { WasmPdfDocument } from "pdf-oxide-wasm";
Конструктор
new WasmPdfDocument(data)
Завантаження PDF-документа з необроблених байтів.
| Параметр | Тип | Опис |
|---|---|---|
data |
Uint8Array |
The PDF file contents |
Throws: Error if the PDF is invalid or cannot be parsed.
const bytes = new Uint8Array(readFileSync("document.pdf"));
const doc = new WasmPdfDocument(bytes);
Тільки читання
pageCount() -> number
Отримати кількість сторінок у документі.
version() -> Uint8Array
Отримати версію PDF як [major, minor].
const [major, minor] = doc.version();
console.log(`PDF ${major}.${minor}`);
authenticate(password) -> boolean
Дешифрування зашифрованого PDF. Повертає true, якщо автентифікація пройшла успішно.
| Параметр | Тип | Опис |
|---|---|---|
password |
string |
The password string |
hasStructureTree() -> boolean
Перевірити, чи є документ тегованим PDF з деревом структури.
Вилучення тексту
extractText(pageIndex) -> string
Вилучити простий текст з однієї сторінки.
| Параметр | Тип | Опис |
|---|---|---|
pageIndex |
number |
Zero-based page number |
const text = doc.extractText(0);
extractAllText() -> string
Вилучити простий текст з усіх сторінок, розділений символами зміни сторінки.
extractChars(pageIndex) -> Array
Вилучити окремі символи з точним позиціонуванням та метаданими шрифту.
| Параметр | Тип | Опис |
|---|---|---|
pageIndex |
number |
Zero-based page number |
Повертає: Array of objects with fields:
| Поле | Тип | Опис |
|---|---|---|
char |
string |
The character |
bbox |
{x, y, width, height} |
Обмежувальна рамка |
font_name |
string |
Назва шрифту |
font_size |
number |
Розмір шрифту у пунктах |
font_weight |
string |
Weight (Normal, Bold, etc.) |
is_italic |
boolean |
Italic flag |
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})`);
}
extractSpans(pageIndex) -> Array
Вилучити стилізовані текстові спани з метаданими шрифту.
| Параметр | Тип | Опис |
|---|---|---|
pageIndex |
number |
Zero-based page number |
Повертає: Array of objects with fields:
| Поле | Тип | Опис |
|---|---|---|
text |
string |
The text content |
bbox |
{x, y, width, height} |
Обмежувальна рамка |
font_name |
string |
Назва шрифту |
font_size |
number |
Розмір шрифту у пунктах |
font_weight |
string |
Weight (Normal, Bold, etc.) |
is_italic |
boolean |
Italic flag |
color |
{r, g, b} |
RGB-колір (0.0–1.0) |
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}`);
}
const spans = doc.extractSpans(0);
for (const span of spans) {
console.log(`"${span.text}" size=${span.fontSize}`);
}
Конвертація формату
toMarkdown(pageIndex, detectHeadings?, includeImages?, includeFormFields?) -> string
Конвертувати одну сторінку у Markdown.
| Параметр | Тип | За замовчуванням | Опис |
|---|---|---|---|
pageIndex |
number |
– | Zero-based page number |
detectHeadings |
boolean |
true |
Detect headings from font size |
includeImages |
boolean |
true |
Include images |
includeFormFields |
boolean |
true |
Include form field values |
toMarkdownAll(detectHeadings?, includeImages?, includeFormFields?) -> string
Конвертувати всі сторінки у Markdown.
toHtml(pageIndex, preserveLayout?, detectHeadings?, includeFormFields?) -> string
Конвертувати одну сторінку у HTML.
| Параметр | Тип | За замовчуванням | Опис |
|---|---|---|---|
pageIndex |
number |
– | Zero-based page number |
preserveLayout |
boolean |
false |
Preserve visual layout |
detectHeadings |
boolean |
true |
Detect headings |
includeFormFields |
boolean |
true |
Include form field values |
toHtmlAll(preserveLayout?, detectHeadings?, includeFormFields?) -> string
Конвертувати всі сторінки у HTML.
toPlainText(pageIndex) -> string
Конвертувати одну сторінку у простий текст.
toPlainTextAll() -> string
Конвертувати всі сторінки у простий текст.
Пошук
search(pattern, caseInsensitive?, literal?, wholeWord?, maxResults?) -> Array
Пошук тексту на всіх сторінках.
| Параметр | Тип | За замовчуванням | Опис |
|---|---|---|---|
pattern |
string |
– | Search pattern (string or regex) |
caseInsensitive |
boolean |
false |
Пошук без урахування регістру |
literal |
boolean |
false |
Treat pattern as literal string |
wholeWord |
boolean |
false |
Шукати лише цілі слова |
maxResults |
number |
– | Maximum results to return |
Повертає: Array of objects with fields:
| Поле | Тип | Опис |
|---|---|---|
page |
number |
Номер сторінки |
text |
string |
Знайдений текст |
bbox |
object |
Обмежувальна рамка |
start_index |
number |
Start index in page text |
end_index |
number |
End index in page text |
searchPage(pageIndex, pattern, caseInsensitive?, literal?, wholeWord?, maxResults?) -> Array
Пошук тексту на одній сторінці.
Інформація про зображення
extractImages(pageIndex) -> Array
Отримати метадані зображення для сторінки.
| Поле | Тип | Опис |
|---|---|---|
width |
number |
Ширина зображення у пікселях |
height |
number |
Висота зображення у пікселях |
color_space |
string |
Колірний простір (e.g. DeviceRGB) |
bits_per_component |
number |
Bits per color channel |
bbox |
object |
Position on page |
extractImageBytes(pageIndex) -> Array
Вилучити необроблені байти зображень зі сторінки. Returns an array of objects:
| Поле | Тип | Опис |
|---|---|---|
width |
number |
Ширина зображення у пікселях |
height |
number |
Висота зображення у пікселях |
data |
Uint8Array |
Raw image bytes |
format |
string |
Формат зображення |
pageImages(pageIndex) -> Array
Отримати імена зображень та межі для операцій позиціонування.
| Поле | Тип | Опис |
|---|---|---|
name |
string |
XObject name |
bounds |
number[] |
[x, y, width, height] |
matrix |
number[] |
Transform matrix [a, b, c, d, e, f] |
Структура документа
getOutline() -> Array | null
Отримати закладки документа / зміст. Повертає null, якщо контур відсутній.
getAnnotations(pageIndex) -> Array
Отримати метадані анотацій (тип, прямокутник, вміст тощо) для сторінки.
extractPaths(pageIndex) -> Array
Отримати векторні шляхи (лінії, криві, фігури) зі сторінки.
pageLabels() -> Array
Отримати діапазони міток сторінок. Returns an array of objects:
| Поле | Тип | Опис |
|---|---|---|
start_page |
number |
First page in this range |
style |
string |
Numbering style |
prefix |
string |
Label prefix |
start_value |
number |
Starting number |
xmpMetadata() -> object | null
Отримати метадані XMP. Повертає null, якщо відсутній. Object fields include:
| Поле | Тип | Опис |
|---|---|---|
dc_title |
string | null |
Назва документа |
dc_creator |
string[] | null |
Creator list |
dc_description |
string | null |
Description |
xmp_creator_tool |
string | null |
Creator tool |
xmp_create_date |
string | null |
Дата створення |
xmp_modify_date |
string | null |
Дата модифікації |
pdf_producer |
string | null |
PDF producer |
Поля форми
getFormFields() -> Array
Отримати всі поля форми with name, type, value, and flags.
| Поле | Тип | Опис |
|---|---|---|
name |
string |
Назва поля |
field_type |
string |
Тип поля (text, checkbox, etc.) |
value |
string |
Поточне значення |
flags |
number |
Прапорці поля |
const fields = doc.getFormFields();
for (const f of fields) {
console.log(`${f.name} (${f.field_type}) = ${f.value}`);
}
hasXfa() -> boolean
Перевірити, чи містить документ форми XFA.
getFormFieldValue(name) -> any
Отримати значення поля форми за іменем. Повертає string, boolean або null залежно від типу поля.
| Параметр | Тип | Опис |
|---|---|---|
name |
string |
Назва поля |
setFormFieldValue(name, value) -> void
Встановити значення поля форми за іменем.
| Параметр | Тип | Опис |
|---|---|---|
name |
string |
Назва поля |
value |
string | boolean |
New field value |
exportFormData(format?) -> Uint8Array
Експортувати дані форми як FDF (default) or XFDF.
| Параметр | Тип | За замовчуванням | Опис |
|---|---|---|---|
format |
string |
"fdf" |
Export format: "fdf" or "xfdf" |
Редагування
Метадані
| Method | Parameters | Description |
|---|---|---|
setTitle(title) |
string |
Встановити назву документа |
setAuthor(author) |
string |
Встановити автора документа |
setSubject(subject) |
string |
Встановити тему документа |
setKeywords(keywords) |
string |
Встановити ключові слова документа |
Сторінка Rotation
| Method | Parameters | Description |
|---|---|---|
pageRotation(pageIndex) |
number |
Get current rotation (0, 90, 180, 270) |
setPageRotation(pageIndex, degrees) |
number, number |
Встановити абсолютне обертання |
rotatePage(pageIndex, degrees) |
number, number |
Add to current rotation |
rotateAllPages(degrees) |
number |
Обернути всі сторінки |
Розміри сторінки
| Method | Parameters | Description |
|---|---|---|
pageMediaBox(pageIndex) |
number |
Get MediaBox [llx, lly, urx, ury] |
setPageMediaBox(pageIndex, llx, lly, urx, ury) |
number, ... |
Встановити MediaBox |
pageCropBox(pageIndex) |
number |
Get CropBox (may be null) |
setPageCropBox(pageIndex, llx, lly, urx, ury) |
number, ... |
Встановити CropBox |
cropMargins(left, right, top, bottom) |
number, ... |
Crop all page margins |
Стирання / Вибілювання
| Method | Parameters | Description |
|---|---|---|
eraseRegion(pageIndex, llx, lly, urx, ury) |
number, ... |
Erase a region |
eraseRegions(pageIndex, rects) |
number, Float32Array |
Erase multiple regions |
clearEraseRegions(pageIndex) |
number |
Clear pending erases |
Анотації та затирання
| Method | Parameters | Description |
|---|---|---|
flattenPageAnnotations(pageIndex) |
number |
Flatten annotations on page |
flattenAllAnnotations() |
– | Вирівняти всі анотації |
applyPageRedactions(pageIndex) |
number |
Apply redactions on page |
applyAllRedactions() |
– | Apply all redactions |
Вирівнювання форм
| Method | Parameters | Description |
|---|---|---|
flattenForms() |
– | Вирівняти всі поля форми into page content |
flattenFormsOnPage(pageIndex) |
number |
Згладити форми on a specific page |
Об’єднання та вбудовування
mergeFrom(data) -> number
Об’єднати сторінки з іншого PDF. Повертає кількість об’єднаних сторінок.
| Параметр | Тип | Опис |
|---|---|---|
data |
Uint8Array |
The source PDF file bytes |
embedFile(name, data) -> void
Прикріпити файл to the PDF.
| Параметр | Тип | Опис |
|---|---|---|
name |
string |
Filename for the attachment |
data |
Uint8Array |
File contents |
Image Manipulation
| Method | Parameters | Description |
|---|---|---|
repositionImage(pageIndex, name, x, y) |
number, string, number, number |
Move image |
resizeImage(pageIndex, name, w, h) |
number, string, number, number |
Resize image |
setImageBounds(pageIndex, name, x, y, w, h) |
number, string, ... |
Set image bounds |
Рендеринг
| Метод | Параметри | Повернення | Опис |
|---|---|---|---|
renderPage(pageIndex, dpi?) |
number, number |
Uint8Array |
Рендеринг сторінки в PNG байти |
flattenToImages(dpi?) |
number |
Uint8Array |
Перетворення всіх сторінок у PDF на основі зображень |
Збереження
saveToBytes() -> Uint8Array
Зберегти відредагований PDF як байти.
saveEncryptedToBytes(password, ownerPassword?, allowPrint?, allowCopy?, allowModify?, allowAnnotate?) -> Uint8Array
Зберегти з шифруванням AES-256.
| Параметр | Тип | За замовчуванням | Опис |
|---|---|---|---|
password |
string |
– | Пароль користувача |
ownerPassword |
string |
user password | Пароль власника |
allowPrint |
boolean |
true |
Дозволити друк |
allowCopy |
boolean |
true |
Дозволити копіювання |
allowModify |
boolean |
false |
Дозволити редагування |
allowAnnotate |
boolean |
true |
Дозволити анотації |
free()
Звільнити пам’ять WASM. Завжди викликайте після завершення роботи з документом.
WasmPdf
Фабричний клас для створення нових PDF.
import { WasmPdf } from "pdf-oxide-wasm";
Статичні методи
WasmPdf.fromMarkdown(content, title?, author?) -> WasmPdf
Створити PDF з Markdown-тексту.
| Параметр | Тип | За замовчуванням | Опис |
|---|---|---|---|
content |
string |
– | Markdown content |
title |
string |
– | Назва документа |
author |
string |
– | Автор документа |
WasmPdf.fromHtml(content, title?, author?) -> WasmPdf
Створити PDF з HTML.
WasmPdf.fromText(content, title?, author?) -> WasmPdf
Створити PDF з простого тексту.
WasmPdf.fromImageBytes(data) -> WasmPdf
Створити односторінковий PDF з байтів зображення.
| Параметр | Тип | Опис |
|---|---|---|
data |
Uint8Array |
Image file bytes (JPEG, PNG) |
WasmPdf.fromMultipleImageBytes(imagesArray) -> WasmPdf
Створити багатосторінковий PDF з кількох зображень, одна сторінка на зображення.
| Параметр | Тип | Опис |
|---|---|---|
imagesArray |
Uint8Array[] |
Array of image file bytes |
Методи екземпляра
toBytes() -> Uint8Array
Отримати PDF як байти.
size -> number
PDF size in bytes (readonly property).
const pdf = WasmPdf.fromMarkdown("# Hello World\n\nThis is a PDF.");
console.log(`PDF size: ${pdf.size} bytes`);
writeFileSync("output.pdf", pdf.toBytes());
Доступність функцій
Деякі функції потребують нативних залежностей та недоступні у WebAssembly:
| Функція | WASM | Примітки |
|---|---|---|
| Text extraction | Yes | Full support |
| Structured extraction | Yes | Chars, spans |
| PDF creation | Yes | Markdown, HTML, text, images |
| PDF editing | Yes | Metadata, rotation, dimensions, erase |
| Form fields | Yes | Read, write, export, flatten |
| Search | Yes | Full regex support |
| Encryption | Yes | AES-256 read and write |
| Annotations | Yes | Read, flatten, redact |
| Merge PDFs | Yes | Об’єднати сторінки з іншого PDF |
| Embedded files | Yes | Attach files to PDFs |
| Page labels | Yes | Read page label ranges |
| XMP metadata | Yes | Read XMP metadata |
| OCR | No | Requires native ONNX Runtime |
| Digital signatures | No | Requires native crypto libraries |
| Page rendering | No | Requires native tiny-skia |
| Barcodes | No | Requires native rendering |
| Office conversion | No | Requires native LibreOffice |
Обробка помилок
Усі методи, які можуть завершитися невдачею, генерують об’єкти 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");