Справочник Zig API
PDF Oxide поставляет идиоматичные привязки для Zig (pdf_oxide.zig), построенные напрямую поверх C ABI через @cImport — без промежуточного слоя. Дескрипторы — это структуры с методом deinit; C-строки и буферы копируются в выделенную вызывающим кодом память (вы передаёте std.mem.Allocator), а коды C ABI, отличные от успешных, отображаются в набор ошибок Error.
// build.zig.zon
.dependencies = .{
.pdf_oxide = .{ .url = "https://github.com/yfedoseev/pdf_oxide/...", .hash = "..." },
},
const pdf = @import("pdf_oxide");
Описание Rust API см. в справочнике Rust API. Описание Python API см. в справочнике Python API. Описание JavaScript API см. в справочнике Node.js API или справочнике WASM API.
Обработка ошибок
Значения ошибок в Zig не могут нести полезную нагрузку, поэтому код ошибки C ABI передаётся через потоково-локальную переменную. Считывайте его сразу после перехвата Error.PdfOxide.
pub const Error = error{ PdfOxide, OutOfMemory }; // any non-success C-ABI outcome
pub threadlocal var last_error_code: i32 = 0; // code of the most recent failure on this thread
pub fn lastErrorCode() i32; // the most recent failure code on this thread
const doc = pdf.Document.open("file.pdf") catch |err| {
std.debug.print("pdf error code: {d}\n", .{pdf.lastErrorCode()});
return err;
};
Типы данных
Простые структуры-значения, возвращаемые при извлечении. Поля-срезы (text, fontName, data, …) принадлежат аллокатору — освобождайте их парным помощником freeXxx.
pub const Version = struct { major: u8, minor: u8 };
pub const Bbox = struct { x: f32, y: f32, width: f32, height: f32 };
pub const Char = struct { character: u32, bbox: Bbox, fontName: []u8, fontSize: f32 };
pub const Word = struct { text: []u8, bbox: Bbox, fontName: []u8, fontSize: f32, bold: bool };
pub const TextLine = struct { text: []u8, bbox: Bbox, wordCount: i32 };
pub const Table = struct { rowCount: i32, colCount: i32, hasHeader: bool, cells: [][]u8 };
pub const Font = struct { name: []u8, type: []u8, encoding: []u8, embedded: bool, subset: bool };
pub const Image = struct { width: i32, height: i32, bitsPerComponent: i32, format: []u8, colorspace: []u8, data: []u8 };
pub const Annotation = struct { type: []u8, subtype: []u8, content: []u8, author: []u8, rect: Bbox, borderWidth: f32 };
pub const Path = struct { bbox: Bbox, strokeWidth: f32, hasStroke: bool, hasFill: bool, operationCount: i32 };
pub const SearchResult = struct { text: []u8, page: i32, bbox: Bbox };
pub const UaStats = struct { structElements: i32, images: i32, tables: i32, forms: i32, annotations: i32, pages: i32 };
pub const DerList = struct { entries: []const []const u8 };
Методы Table
pub fn cell(self: Table, row: i32, col: i32) []const u8; // cell text at (row, col), 0-based; empty string out of range
pub fn deinit(self: *Table, alloc: std.mem.Allocator) void; // free every cell string and the backing slice
Document
Основной тип для открытия, изучения, извлечения содержимого и рендеринга PDF.
Открытие
pub fn open(path: [:0]const u8) Error!Document; // open from a filesystem path (NUL-terminated)
pub fn openFromBytes(data: []const u8) Error!Document; // open from in-memory bytes
pub fn openWithPassword(path: [:0]const u8, password: [:0]const u8) Error!Document; // open a password-protected PDF
pub fn openFromDocxBytes(data: []const u8) Error!Document; // open a PDF rendered from DOCX bytes
pub fn openFromPptxBytes(data: []const u8) Error!Document; // open a PDF rendered from PPTX bytes
pub fn openFromXlsxBytes(data: []const u8) Error!Document; // open a PDF rendered from XLSX bytes
pub fn deinit(self: *Document) void; // free the native handle
Сведения о документе
pub fn pageCount(self: Document) Error!i32; // number of pages
pub fn version(self: Document) Version; // PDF version as (major, minor)
pub fn isEncrypted(self: Document) bool; // whether the document is encrypted
pub fn hasStructureTree(self: Document) bool; // whether the document is a Tagged PDF
pub fn hasXfa(self: Document) bool; // whether the document carries an XFA form
pub fn authenticate(self: Document, password: [:0]const u8) Error!bool; // authenticate an encrypted PDF after opening
pub fn pageGetWidth(self: Document, page_index: i32) Error!f32; // page width in PDF points
pub fn pageGetHeight(self: Document, page_index: i32) Error!f32; // page height in PDF points
pub fn pageGetRotation(self: Document, page_index: i32) Error!i32; // page rotation in degrees
pub fn sourceBytes(self: Document, alloc: std.mem.Allocator) Error![]u8; // a copy of the document's current source bytes
Извлечение текста
pub fn extractText(self: Document, alloc: std.mem.Allocator, page_index: i32) Error![]u8; // plain text of one page
pub fn extractTextAuto(self: Document, alloc: std.mem.Allocator, page_index: i32) Error![]u8; // one-shot auto text extraction for a page
pub fn extractAllText(self: Document, alloc: std.mem.Allocator) Error![]u8; // whole-document auto text extraction
pub fn extractStructuredJson(self: Document, alloc: std.mem.Allocator, page_index: i32) Error![]u8; // structured page content as a JSON string
pub fn extractPageAuto(self: Document, alloc: std.mem.Allocator, page_index: i32, options_json: ?[:0]const u8) Error![]u8; // configurable one-shot page extraction (JSON in/out)
Структурированное извлечение
Каждый метод возвращает срез, которым владеет аллокатор; освобождайте его парным помощником freeXxx.
pub fn extractChars(self: Document, alloc: std.mem.Allocator, page_index: i32) Error![]Char; // per-glyph positions and fonts
pub fn extractWords(self: Document, alloc: std.mem.Allocator, page_index: i32) Error![]Word; // word boxes with font metadata
pub fn extractTextLines(self: Document, alloc: std.mem.Allocator, page_index: i32) Error![]TextLine; // text lines with word counts
pub fn extractTables(self: Document, alloc: std.mem.Allocator, page_index: i32) Error![]Table; // detected tables (row-major cells)
pub fn embeddedFonts(self: Document, alloc: std.mem.Allocator, page_index: i32) Error![]Font; // fonts referenced on a page
pub fn embeddedImages(self: Document, alloc: std.mem.Allocator, page_index: i32) Error![]Image; // raster images on a page
pub fn pageAnnotations(self: Document, alloc: std.mem.Allocator, page_index: i32) Error![]Annotation; // annotations on a page
pub fn extractPaths(self: Document, alloc: std.mem.Allocator, page_index: i32) Error![]Path; // vector paths (lines/curves/shapes)
pub fn freeChars(alloc: std.mem.Allocator, chars: []Char) void; // free an extractChars slice
pub fn freeWords(alloc: std.mem.Allocator, words: []Word) void; // free an extractWords slice
pub fn freeTextLines(alloc: std.mem.Allocator, lines: []TextLine) void; // free an extractTextLines slice
pub fn freeTables(alloc: std.mem.Allocator, tables: []Table) void; // free an extractTables slice
pub fn freeFonts(alloc: std.mem.Allocator, fonts: []Font) void; // free an embeddedFonts slice
pub fn freeImages(alloc: std.mem.Allocator, images: []Image) void; // free an embeddedImages slice
pub fn freeAnnotations(alloc: std.mem.Allocator, annotations: []Annotation) void; // free a pageAnnotations slice
pub fn freePaths(alloc: std.mem.Allocator, paths: []Path) void; // free an extractPaths slice
pub fn freeSearchResults(alloc: std.mem.Allocator, results: []SearchResult) void; // free a search/searchAll slice
Извлечение по области
Ограничивает извлечение прямоугольником (x, y, w, h) в пользовательском пространстве страницы.
pub fn extractTextInRect(self: Document, alloc: std.mem.Allocator, page_index: i32, x: f32, y: f32, w: f32, h: f32) Error![]u8; // text within a rectangle
pub fn extractWordsInRect(self: Document, alloc: std.mem.Allocator, page_index: i32, x: f32, y: f32, w: f32, h: f32) Error![]Word; // words within a rectangle
pub fn extractLinesInRect(self: Document, alloc: std.mem.Allocator, page_index: i32, x: f32, y: f32, w: f32, h: f32) Error![]TextLine; // lines within a rectangle
pub fn extractTablesInRect(self: Document, alloc: std.mem.Allocator, page_index: i32, x: f32, y: f32, w: f32, h: f32) Error![]Table; // tables within a rectangle
pub fn extractImagesInRect(self: Document, alloc: std.mem.Allocator, page_index: i32, x: f32, y: f32, w: f32, h: f32) Error![]Image; // images within a rectangle
Конвертация
pub fn toPlainText(self: Document, alloc: std.mem.Allocator, page_index: i32) Error![]u8; // one page to plain text
pub fn toPlainTextAll(self: Document, alloc: std.mem.Allocator) Error![]u8; // all pages to plain text
pub fn toMarkdown(self: Document, alloc: std.mem.Allocator, page_index: i32) Error![]u8; // one page to Markdown
pub fn toMarkdownAll(self: Document, alloc: std.mem.Allocator) Error![]u8; // all pages to Markdown
pub fn toHtml(self: Document, alloc: std.mem.Allocator, page_index: i32) Error![]u8; // one page to HTML
pub fn toHtmlAll(self: Document, alloc: std.mem.Allocator) Error![]u8; // all pages to HTML
pub fn toDocx(self: Document, alloc: std.mem.Allocator) Error![]u8; // export the document to DOCX bytes
pub fn toPptx(self: Document, alloc: std.mem.Allocator) Error![]u8; // export the document to PPTX bytes
pub fn toXlsx(self: Document, alloc: std.mem.Allocator) Error![]u8; // export the document to XLSX bytes
Классификация и очистка
pub fn classifyPage(self: Document, alloc: std.mem.Allocator, page_index: i32) Error![]u8; // per-page text-vs-OCR classification (JSON)
pub fn classifyDocument(self: Document, alloc: std.mem.Allocator) Error![]u8; // whole-document classification (JSON)
pub fn eraseHeader(self: Document, page_index: i32) Error!i32; // erase the detected running header
pub fn eraseFooter(self: Document, page_index: i32) Error!i32; // erase the detected running footer
pub fn eraseArtifacts(self: Document, page_index: i32) Error!i32; // erase artifact content from a page
pub fn removeHeaders(self: Document, threshold: f32) Error!i32; // remove repeating headers above a threshold; returns count
pub fn removeFooters(self: Document, threshold: f32) Error!i32; // remove repeating footers above a threshold; returns count
pub fn removeArtifacts(self: Document, threshold: f32) Error!i32; // remove repeating artifacts above a threshold; returns count
Поиск
pub fn search(self: Document, alloc: std.mem.Allocator, page_index: i32, term: [:0]const u8, case_sensitive: bool) Error![]SearchResult; // search one page
pub fn searchAll(self: Document, alloc: std.mem.Allocator, term: [:0]const u8, case_sensitive: bool) Error![]SearchResult; // search the whole document
Метаданные, оглавление и формы
pub fn outline(self: Document, alloc: std.mem.Allocator) Error![]u8; // document outline (bookmarks) as JSON
pub fn pageLabels(self: Document, alloc: std.mem.Allocator) Error![]u8; // page labels as JSON
pub fn xmpMetadata(self: Document, alloc: std.mem.Allocator) Error![]u8; // XMP metadata XML packet
pub fn formFields(self: Document) Error!FormFieldList; // lazy form-field accessor list
pub fn exportFormDataToBytes(self: Document, alloc: std.mem.Allocator, format_type: i32) Error![]u8; // export form data (0=FDF, 1=XFDF)
pub fn importFormData(self: Document, data_path: [:0]const u8) Error!i32; // import form data from a file path
pub fn formImportFromFile(self: Document, filename: [:0]const u8) Error!bool; // import form data; returns success
pub fn planSplitByBookmarks(self: Document, alloc: std.mem.Allocator, options_json: ?[:0]const u8) Error![]u8; // plan a bookmark-based split (JSON)
pub fn convertToPdfA(self: Document, level: i32) Error!bool; // convert to PDF/A; returns true on success
Подписи (чтение)
pub fn sign(self: Document, cert: Certificate, reason: [:0]const u8, location: [:0]const u8) Error!i32; // apply a digital signature; returns a status
pub fn signatureCount(self: Document) Error!i32; // number of signatures present
pub fn signature(self: Document, index: i32) Error!SignatureInfo; // the index-th signature as an owned SignatureInfo
pub fn verifyAllSignatures(self: Document) Error!i32; // verify every signature; returns a status
pub fn hasTimestamp(self: Document) Error!bool; // whether a document-level timestamp is present
pub fn dss(self: Document) Error!Dss; // the Document Security Store (DSS) accessor
Ленивые списочные дескрипторы
Возвращают списки на основе дескрипторов с аксессорами по запросу (дешевле, чем «жадные» варианты extractXxx). Освобождайте каждый вызовом deinit.
pub fn annotationList(self: Document, page_index: i32) Error!AnnotationList; // lazy annotation accessor list
pub fn fontList(self: Document, page_index: i32) Error!FontList; // lazy font accessor list
pub fn elementList(self: Document, page_index: i32) Error!ElementList; // lazy page-element accessor list
pub fn pageGetElements(self: Document, page_index: i32) Error!ElementList; // lazy page-element accessor list (alias)
pub fn searchPageList(self: Document, page_index: i32, term: [:0]const u8, case_sensitive: bool) Error!SearchResultList; // lazy per-page search results
pub fn page(self: Document, index: i32) Page; // a lightweight per-page handle (borrows the Document)
Рендеринг
format: 0 = PNG, 1 = JPEG. Все методы возвращают RenderedImage, которым владеет вызывающий код.
pub fn renderPage(self: Document, alloc: std.mem.Allocator, page_index: i32, format: i32) Error!RenderedImage; // render a page at default DPI
pub fn renderPageZoom(self: Document, alloc: std.mem.Allocator, page_index: i32, zoom: f32, format: i32) Error!RenderedImage; // render a page at a zoom factor
pub fn renderPageThumbnail(self: Document, alloc: std.mem.Allocator, page_index: i32, size: i32, format: i32) Error!RenderedImage; // render a thumbnail of bounded size
pub fn renderPageFit(self: Document, alloc: std.mem.Allocator, page_index: i32, w: i32, h: i32, format: i32) Error!RenderedImage; // render scaled to fit w x h (aspect-preserving)
pub fn renderPageRaw(self: Document, alloc: std.mem.Allocator, page_index: i32, dpi: i32) Error!RenderedImage; // render to raw RGBA8 (data.len == w*h*4)
pub fn renderPageRegion(self: Document, alloc: std.mem.Allocator, page_index: i32, crop_x: f32, crop_y: f32, crop_width: f32, crop_height: f32, format: i32) Error!RenderedImage; // render a cropped region
pub fn renderPageWithOptions(self: Document, alloc: std.mem.Allocator, page_index: i32, dpi: i32, format: i32, bg_r: f32, bg_g: f32, bg_b: f32, bg_a: f32, transparent_background: bool, render_annotations: bool, jpeg_quality: i32) Error!RenderedImage; // render with DPI, background, and annotation options
pub fn renderPageWithOptionsEx(self: Document, alloc: std.mem.Allocator, page_index: i32, dpi: i32, format: i32, bg_r: f32, bg_g: f32, bg_b: f32, bg_a: f32, transparent_background: bool, render_annotations: bool, jpeg_quality: i32, excluded_layers: []const [*:0]const u8) Error!RenderedImage; // render with options plus excluded OCG layers
pub fn estimateRenderTime(self: Document, page_index: i32) Error!i32; // estimated render time (ms) for a page
Валидация
pub fn validatePdfA(self: Document, level: i32) Error!PdfAResults; // run a PDF/A conformance check
pub fn validatePdfUa(self: Document, level: i32) Error!UaResults; // run a PDF/UA accessibility check
pub fn validatePdfX(self: Document, level: i32) Error!PdfXResults; // run a PDF/X conformance check
OCR
pub fn ocrPageNeedsOcr(self: Document, page_index: i32) Error!bool; // whether a page is scanned/hybrid and needs OCR
pub fn ocrExtractText(self: Document, alloc: std.mem.Allocator, page_index: i32, engine: ?OcrEngine) Error![]u8; // OCR a page (null engine = native text only)
Page
Лёгкий постраничный дескриптор, возвращаемый Document.page(index). Он заимствует владеющий им Document, который должен жить не меньше самого дескриптора; каждый метод делегирует вызов соответствующему методу Document.
pub fn text(self: Page, alloc: std.mem.Allocator) Error![]u8; // page plain text
pub fn plainText(self: Page, alloc: std.mem.Allocator) Error![]u8; // page plain text (layout-aware)
pub fn markdown(self: Page, alloc: std.mem.Allocator) Error![]u8; // page Markdown
pub fn html(self: Page, alloc: std.mem.Allocator) Error![]u8; // page HTML
FormFieldList
Ленивый список-аксессор полей формы, возвращаемый Document.formFields(). Освобождайте вызовом deinit / close.
pub fn deinit(self: *FormFieldList) void; // free the native handle (idempotent)
pub fn close(self: *FormFieldList) void; // free the native handle (idempotent)
pub fn count(self: FormFieldList) Error!i32; // number of fields
pub fn getName(self: FormFieldList, alloc: std.mem.Allocator, index: i32) Error![]u8; // field name at index
pub fn getValue(self: FormFieldList, alloc: std.mem.Allocator, index: i32) Error![]u8; // field value at index
pub fn getType(self: FormFieldList, alloc: std.mem.Allocator, index: i32) Error![]u8; // field type string at index
pub fn isReadonly(self: FormFieldList, index: i32) Error!bool; // whether the field is read-only
pub fn isRequired(self: FormFieldList, index: i32) Error!bool; // whether the field is required
AnnotationList
Ленивый список-аксессор аннотаций, возвращаемый Document.annotationList(). Освобождайте вызовом deinit / close.
pub fn deinit(self: *AnnotationList) void; // free the native handle (idempotent)
pub fn close(self: *AnnotationList) void; // free the native handle (idempotent)
pub fn count(self: AnnotationList) Error!i32; // number of annotations
pub fn getColor(self: AnnotationList, index: i32) Error!u32; // packed RGBA color of the annotation
pub fn getCreationDate(self: AnnotationList, index: i32) Error!i64; // creation date (Unix epoch seconds)
pub fn getModificationDate(self: AnnotationList, index: i32) Error!i64; // modification date (Unix epoch seconds)
pub fn isHidden(self: AnnotationList, index: i32) Error!bool; // whether the annotation is hidden
pub fn isMarkedDeleted(self: AnnotationList, index: i32) Error!bool; // whether the annotation is marked deleted
pub fn isPrintable(self: AnnotationList, index: i32) Error!bool; // whether the annotation is printable
pub fn isReadOnly(self: AnnotationList, index: i32) Error!bool; // whether the annotation is read-only
pub fn highlightQuadPointsCount(self: AnnotationList, index: i32) Error!i32; // number of quad-point quads on a highlight
pub fn highlightQuadPoint(self: AnnotationList, index: i32, quad_index: i32) Error![8]f32; // the four corners of a highlight quad
pub fn linkUri(self: AnnotationList, alloc: std.mem.Allocator, index: i32) Error![]u8; // the URI of a link annotation
pub fn textIconName(self: AnnotationList, alloc: std.mem.Allocator, index: i32) Error![]u8; // the icon name of a text annotation
pub fn toJson(self: AnnotationList, alloc: std.mem.Allocator) Error![]u8; // serialize the whole list to JSON
FontList
Ленивый список-аксессор шрифтов, возвращаемый Document.fontList(). Освобождайте вызовом deinit / close.
pub fn deinit(self: *FontList) void; // free the native handle (idempotent)
pub fn close(self: *FontList) void; // free the native handle (idempotent)
pub fn count(self: FontList) Error!i32; // number of fonts
pub fn getSize(self: FontList, index: i32) Error!f32; // nominal point size of the font at index
pub fn toJson(self: FontList, alloc: std.mem.Allocator) Error![]u8; // serialize the whole list to JSON
SearchResultList
Ленивый список результатов поиска по странице, возвращаемый Document.searchPageList(). Освобождайте вызовом deinit / close.
pub fn deinit(self: *SearchResultList) void; // free the native handle (idempotent)
pub fn close(self: *SearchResultList) void; // free the native handle (idempotent)
pub fn count(self: SearchResultList) Error!i32; // number of results
pub fn toJson(self: SearchResultList, alloc: std.mem.Allocator) Error![]u8; // serialize the result set to JSON
ElementList
Ленивый список-аксессор элементов страницы, возвращаемый Document.elementList() / pageGetElements(). Освобождайте вызовом deinit / close.
pub fn deinit(self: *ElementList) void; // free the native handle (idempotent)
pub fn close(self: *ElementList) void; // free the native handle (idempotent)
pub fn count(self: ElementList) Error!i32; // number of elements
pub fn getType(self: ElementList, alloc: std.mem.Allocator, index: i32) Error![]u8; // element type string at index
pub fn getText(self: ElementList, alloc: std.mem.Allocator, index: i32) Error![]u8; // element text at index
pub fn getRect(self: ElementList, index: i32) Error!Bbox; // element bounding box at index
pub fn toJson(self: ElementList, alloc: std.mem.Allocator) Error![]u8; // serialize the whole list to JSON
RenderedImage
Владеет закодированными байтами и нативным дескриптором, полученным в результате вызова renderPageXxx.
pub const RenderedImage = struct { handle: *c.FfiRenderedImage, alloc: std.mem.Allocator, width: i32, height: i32, data: []u8 };
pub fn save(self: RenderedImage, file_path: [:0]const u8) Error!void; // write the encoded image to a file path
pub fn deinit(self: *RenderedImage) void; // free the copied bytes and the native handle
PDF, созданный из исходного формата. Используйте фабричные функции для построения, затем save / toBytes.
pub fn fromMarkdown(md: [:0]const u8) Error!Pdf; // build a PDF from Markdown
pub fn fromHtml(html: [:0]const u8) Error!Pdf; // build a PDF from HTML
pub fn fromText(text: [:0]const u8) Error!Pdf; // build a PDF from plain text
pub fn fromImage(path: [:0]const u8) Error!Pdf; // single-page PDF wrapping the image at a path
pub fn fromImageBytes(data: []const u8) Error!Pdf; // single-page PDF wrapping image bytes
pub fn fromHtmlCss(html: [:0]const u8, css: [:0]const u8, font_bytes: []const u8) Error!Pdf; // build from HTML + CSS with one embedded font
pub fn fromHtmlCssWithFonts(alloc: std.mem.Allocator, html: [:0]const u8, css: [:0]const u8, families: []const [*:0]const u8, fonts: []const []const u8) Error!Pdf; // build from HTML + CSS with multiple named fonts
pub fn deinit(self: *Pdf) void; // free the native handle
pub fn save(self: Pdf, path: [:0]const u8) Error!void; // save to a file path
pub fn toBytes(self: Pdf, alloc: std.mem.Allocator) Error![]u8; // serialize to bytes
pub fn pageCount(self: Pdf) Error!i32; // page count of the built PDF
DocumentEditor
Открывает существующий PDF для редактирования на месте: метаданные, страницы, геометрия, стирание/редактирование с удалением (redaction), аннотации, формы и штрихкоды.
Открытие и сохранение
pub fn openEditor(path: [:0]const u8) Error!DocumentEditor; // open a PDF for editing from a path
pub fn openFromBytes(data: []const u8) Error!DocumentEditor; // open a PDF for editing from bytes
pub fn deinit(self: *DocumentEditor) void; // free the native handle (idempotent)
pub fn close(self: *DocumentEditor) void; // free the native handle (idempotent)
pub fn isModified(self: DocumentEditor) Error!bool; // whether the document has unsaved edits
pub fn getSourcePath(self: DocumentEditor, alloc: std.mem.Allocator) Error![]u8; // the source path the editor was opened from
pub fn save(self: DocumentEditor, path: [:0]const u8) Error!void; // save the edited document to a path
pub fn saveToBytes(self: DocumentEditor, alloc: std.mem.Allocator) Error![]u8; // serialize the edited document to bytes
pub fn saveToBytesWithOptions(self: DocumentEditor, alloc: std.mem.Allocator, compress: bool, garbage_collect: bool, linearize: bool) Error![]u8; // serialize with compression/GC/linearization
pub fn extractPagesToBytes(self: DocumentEditor, alloc: std.mem.Allocator, pages: []const i32) Error![]u8; // extract selected pages to a new PDF
pub fn convertToPdfA(self: DocumentEditor, level: i32) Error!void; // convert to PDF/A in-place (level 0=A1b … 7=A3u)
pub fn saveEncryptedToBytes(self: DocumentEditor, alloc: std.mem.Allocator, user_password: [:0]const u8, owner_password: [:0]const u8) Error![]u8; // save with AES-256 encryption to bytes
pub fn saveEncrypted(self: DocumentEditor, path: [:0]const u8, user_password: [:0]const u8, owner_password: [:0]const u8) Error!void; // save with AES-256 encryption to a path
Метаданные
pub fn version(self: DocumentEditor) Error!Version; // PDF version
pub fn pageCount(self: DocumentEditor) Error!i32; // number of pages
pub fn getProducer(self: DocumentEditor, alloc: std.mem.Allocator) Error![]u8; // /Producer metadata
pub fn setProducer(self: DocumentEditor, value: [:0]const u8) Error!void; // set /Producer metadata
pub fn getCreationDate(self: DocumentEditor, alloc: std.mem.Allocator) Error![]u8; // /CreationDate metadata
pub fn setCreationDate(self: DocumentEditor, date_str: [:0]const u8) Error!void; // set /CreationDate metadata
Страницы и геометрия
pub fn deletePage(self: DocumentEditor, page_index: i32) Error!void; // delete a page
pub fn movePage(self: DocumentEditor, from: i32, to: i32) Error!void; // move a page
pub fn getPageRotation(self: DocumentEditor, page_index: i32) Error!i32; // page rotation in degrees
pub fn setPageRotation(self: DocumentEditor, page_index: i32, degrees: i32) Error!void; // set absolute page rotation
pub fn rotatePageBy(self: DocumentEditor, page_index: usize, degrees: i32) Error!void; // rotate one page additively
pub fn rotateAllPages(self: DocumentEditor, degrees: i32) Error!void; // rotate all pages additively
pub fn getPageMediaBox(self: DocumentEditor, page_index: usize) Error!Bbox; // get a page MediaBox
pub fn setPageMediaBox(self: DocumentEditor, page_index: usize, x: f64, y: f64, w: f64, hgt: f64) Error!void; // set a page MediaBox
pub fn getPageCropBox(self: DocumentEditor, page_index: usize) Error!Bbox; // get a page CropBox
pub fn setPageCropBox(self: DocumentEditor, page_index: usize, x: f64, y: f64, w: f64, hgt: f64) Error!void; // set a page CropBox
pub fn cropMargins(self: DocumentEditor, left: f32, right: f32, top: f32, bottom: f32) Error!void; // crop uniform margins on every page
Стирание и редактирование с удалением (redaction)
pub fn eraseRegion(self: DocumentEditor, page_index: i32, x: f32, y: f32, w: f32, hgt: f32) Error!void; // erase one rectangular region
pub fn eraseRegions(self: DocumentEditor, page_index: usize, rects: []const [4]f64) Error!void; // erase multiple (x,y,w,h) regions
pub fn clearEraseRegions(self: DocumentEditor, page_index: usize) Error!void; // clear pending erase regions on a page
pub fn redactionAdd(self: DocumentEditor, page_no: usize, x1: f64, y1: f64, x2: f64, y2: f64, r: f64, g: f64, b: f64) Error!void; // queue a redaction box with an overlay color
pub fn redactionCount(self: DocumentEditor, page_no: usize) Error!i32; // queued redaction regions on a page
pub fn redactionApply(self: DocumentEditor, scrub_metadata: bool, r: f64, g: f64, b: f64) Error!i32; // burn in redactions; returns glyphs removed
pub fn redactionScrubMetadata(self: DocumentEditor) Error!i32; // scrub metadata; returns constructs removed
pub fn applyPageRedactions(self: DocumentEditor, page_index: usize) Error!void; // apply redactions on one page
pub fn applyAllRedactions(self: DocumentEditor) Error!void; // apply all pending redactions
pub fn isPageMarkedForRedaction(self: DocumentEditor, page_index: usize) Error!bool; // whether a page is marked for redaction
pub fn unmarkPageForRedaction(self: DocumentEditor, page_index: usize) Error!void; // unmark a page for redaction
Аннотации и уплощение
pub fn flattenAnnotations(self: DocumentEditor, page_index: i32) Error!void; // flatten annotations on one page
pub fn flattenAllAnnotations(self: DocumentEditor) Error!void; // flatten annotations across the document
pub fn isPageMarkedForFlatten(self: DocumentEditor, page_index: usize) Error!bool; // whether a page is marked for flatten
pub fn unmarkPageForFlatten(self: DocumentEditor, page_index: usize) Error!void; // unmark a page for flatten
Формы
pub fn setFormFieldValue(self: DocumentEditor, name: [:0]const u8, value: [:0]const u8) Error!void; // set a form field value (UTF-8)
pub fn flattenForms(self: DocumentEditor) Error!void; // flatten all forms into page content
pub fn flattenFormsOnPage(self: DocumentEditor, page_index: i32) Error!void; // flatten forms on one page
pub fn flattenWarningsCount(self: DocumentEditor) Error!i32; // warnings from the last form-flatten save
pub fn flattenWarning(self: DocumentEditor, alloc: std.mem.Allocator, index: i32) Error![]u8; // the index-th flatten warning
pub fn importFdfBytes(self: DocumentEditor, data: []const u8) Error!i32; // import form values from FDF bytes
pub fn importXfdfBytes(self: DocumentEditor, data: []const u8) Error!i32; // import form values from XFDF bytes
Объединение, встраивание и штрихкоды
pub fn mergeFromBytes(self: DocumentEditor, data: []const u8) Error!void; // merge pages from a PDF byte buffer
pub fn mergeFrom(self: DocumentEditor, source_path: [:0]const u8) Error!void; // merge pages from a PDF at a path
pub fn embedFile(self: DocumentEditor, name: [:0]const u8, data: []const u8) Error!void; // embed a file attachment
pub fn addBarcodeToPage(self: DocumentEditor, page_index: i32, barcode: Barcode, x: f32, y: f32, width: f32, height: f32) Error!void; // stamp a Barcode onto a page
EmbeddedFont
Шрифт TTF/OTF для регистрации в DocumentBuilder.
pub fn fromFile(path: [:0]const u8) Error!EmbeddedFont; // load a font from a path
pub fn fromBytes(data: []const u8, name: ?[:0]const u8) Error!EmbeddedFont; // load a font from bytes (null name = use the face's PostScript name)
pub fn deinit(self: *EmbeddedFont) void; // free a font not consumed by registerEmbeddedFont
DocumentBuilder
Fluent-сборщик для создания новых PDF. Задайте метаданные, зарегистрируйте шрифты, затем откройте страницы методами a4Page / letterPage / page.
pub fn create() Error!DocumentBuilder; // create a new document builder
pub fn deinit(self: *DocumentBuilder) void; // free the native handle (idempotent)
pub fn close(self: *DocumentBuilder) void; // free the native handle (idempotent)
pub fn setTitle(self: DocumentBuilder, title: [:0]const u8) Error!void; // set document title
pub fn setAuthor(self: DocumentBuilder, author: [:0]const u8) Error!void; // set document author
pub fn setSubject(self: DocumentBuilder, subject: [:0]const u8) Error!void; // set document subject
pub fn setKeywords(self: DocumentBuilder, keywords: [:0]const u8) Error!void; // set document keywords
pub fn setCreator(self: DocumentBuilder, creator: [:0]const u8) Error!void; // set document creator
pub fn onOpen(self: DocumentBuilder, script: [:0]const u8) Error!void; // run JavaScript on document open (/OpenAction)
pub fn taggedPdfUa1(self: DocumentBuilder) Error!void; // enable PDF/UA-1 tagged-PDF mode
pub fn language(self: DocumentBuilder, lang: [:0]const u8) Error!void; // set the natural-language tag (e.g. "en-US")
pub fn roleMap(self: DocumentBuilder, custom: [:0]const u8, standard: [:0]const u8) Error!void; // add a structure-type role-map entry
pub fn registerEmbeddedFont(self: DocumentBuilder, name: [:0]const u8, font: *EmbeddedFont) Error!void; // register an EmbeddedFont under a name
pub fn a4Page(self: DocumentBuilder) Error!PageBuilder; // start an A4 page
pub fn letterPage(self: DocumentBuilder) Error!PageBuilder; // start a US Letter page
pub fn page(self: DocumentBuilder, width: f32, height: f32) Error!PageBuilder; // start a custom-size page (points)
pub fn build(self: DocumentBuilder, alloc: std.mem.Allocator) Error![]u8; // build the PDF to bytes
pub fn save(self: DocumentBuilder, path: [:0]const u8) Error!void; // build and save to a path
pub fn saveEncrypted(self: DocumentBuilder, path: [:0]const u8, user_password: [:0]const u8, owner_password: [:0]const u8) Error!void; // build and save with AES-256 encryption
pub fn toBytesEncrypted(self: DocumentBuilder, alloc: std.mem.Allocator, user_password: [:0]const u8, owner_password: [:0]const u8) Error![]u8; // build encrypted bytes
PageBuilder
Возвращается методами DocumentBuilder.a4Page() / letterPage() / page(). Буферизует содержимое; вызовите done(), чтобы зафиксировать страницу.
Жизненный цикл и компоновка
pub fn deinit(self: *PageBuilder) void; // drop an uncommitted page handle (idempotent)
pub fn close(self: *PageBuilder) void; // drop an uncommitted page handle (idempotent)
pub fn done(self: *PageBuilder) Error!void; // commit the page to the document
pub fn font(self: PageBuilder, name: [:0]const u8, size: f32) Error!void; // select the current font and size
pub fn at(self: PageBuilder, x: f32, y: f32) Error!void; // set the cursor position
pub fn text(self: PageBuilder, txt: [:0]const u8) Error!void; // draw text at the cursor
pub fn heading(self: PageBuilder, level: u8, txt: [:0]const u8) Error!void; // draw a heading
pub fn paragraph(self: PageBuilder, txt: [:0]const u8) Error!void; // draw a wrapped paragraph
pub fn space(self: PageBuilder, points: f32) Error!void; // advance vertical space
pub fn horizontalRule(self: PageBuilder) Error!void; // draw a horizontal rule
pub fn columns(self: PageBuilder, column_count: u32, gap_pt: f32, txt: [:0]const u8) Error!void; // lay text out in columns
pub fn footnote(self: PageBuilder, ref_mark: [:0]const u8, note_text: [:0]const u8) Error!void; // add a footnote
pub fn newPageSameSize(self: PageBuilder) Error!void; // start a new page of the same size
Inline-фрагменты
pub fn inlineText(self: PageBuilder, txt: [:0]const u8) Error!void; // append an inline text run
pub fn inlineBold(self: PageBuilder, txt: [:0]const u8) Error!void; // append a bold inline run
pub fn inlineItalic(self: PageBuilder, txt: [:0]const u8) Error!void; // append an italic inline run
pub fn inlineColor(self: PageBuilder, r: f32, g: f32, b: f32, txt: [:0]const u8) Error!void; // append a colored inline run
pub fn newline(self: PageBuilder) Error!void; // break the current inline line
Ссылки и скрипты документа
pub fn linkUrl(self: PageBuilder, url: [:0]const u8) Error!void; // attach a URL link to the last content
pub fn linkPage(self: PageBuilder, page_index: usize) Error!void; // attach an internal page link
pub fn linkNamed(self: PageBuilder, destination: [:0]const u8) Error!void; // attach a named-destination link
pub fn linkJavascript(self: PageBuilder, script: [:0]const u8) Error!void; // attach a JavaScript-action link
pub fn onOpen(self: PageBuilder, script: [:0]const u8) Error!void; // run JavaScript when the page opens
pub fn onClose(self: PageBuilder, script: [:0]const u8) Error!void; // run JavaScript when the page closes
pub fn fieldKeystroke(self: PageBuilder, script: [:0]const u8) Error!void; // set the field keystroke script
pub fn fieldFormat(self: PageBuilder, script: [:0]const u8) Error!void; // set the field format script
pub fn fieldValidate(self: PageBuilder, script: [:0]const u8) Error!void; // set the field validate script
pub fn fieldCalculate(self: PageBuilder, script: [:0]const u8) Error!void; // set the field calculate script
Аннотации-разметки
pub fn highlight(self: PageBuilder, r: f32, g: f32, b: f32) Error!void; // highlight the last content with an RGB color
pub fn underline(self: PageBuilder, r: f32, g: f32, b: f32) Error!void; // underline the last content
pub fn strikeout(self: PageBuilder, r: f32, g: f32, b: f32) Error!void; // strike out the last content
pub fn squiggly(self: PageBuilder, r: f32, g: f32, b: f32) Error!void; // squiggly-underline the last content
pub fn stickyNote(self: PageBuilder, txt: [:0]const u8) Error!void; // add a sticky note at the cursor
pub fn stickyNoteAt(self: PageBuilder, x: f32, y: f32, txt: [:0]const u8) Error!void; // add a sticky note at a position
pub fn watermark(self: PageBuilder, txt: [:0]const u8) Error!void; // add a text watermark
pub fn watermarkConfidential(self: PageBuilder) Error!void; // add a CONFIDENTIAL watermark
pub fn watermarkDraft(self: PageBuilder) Error!void; // add a DRAFT watermark
pub fn stamp(self: PageBuilder, type_name: [:0]const u8) Error!void; // add a rubber-stamp annotation
pub fn freetext(self: PageBuilder, x: f32, y: f32, w: f32, height: f32, txt: [:0]const u8) Error!void; // add a free-text annotation box
Виджеты форм
pub fn textField(self: PageBuilder, name: [:0]const u8, x: f32, y: f32, w: f32, height: f32, default_value: ?[:0]const u8) Error!void; // add a text field
pub fn checkbox(self: PageBuilder, name: [:0]const u8, x: f32, y: f32, w: f32, height: f32, checked: bool) Error!void; // add a checkbox
pub fn comboBox(self: PageBuilder, name: [:0]const u8, x: f32, y: f32, w: f32, height: f32, options: []const [*:0]const u8, selected: ?[:0]const u8) Error!void; // add a combo box
pub fn radioGroup(self: PageBuilder, name: [:0]const u8, values: []const [*:0]const u8, xs: []const f32, ys: []const f32, ws: []const f32, hs: []const f32, selected: ?[:0]const u8) Error!void; // add a radio-button group
pub fn pushButton(self: PageBuilder, name: [:0]const u8, x: f32, y: f32, w: f32, height: f32, caption: [:0]const u8) Error!void; // add a push button
pub fn signatureField(self: PageBuilder, name: [:0]const u8, x: f32, y: f32, w: f32, height: f32) Error!void; // add a signature field
Штрихкоды, изображения и графика
pub fn barcode1d(self: PageBuilder, barcode_type: i32, data: [:0]const u8, x: f32, y: f32, w: f32, height: f32) Error!void; // draw a 1-D barcode (0=Code128 … 7=Codabar)
pub fn barcodeQr(self: PageBuilder, data: [:0]const u8, x: f32, y: f32, size: f32) Error!void; // draw a QR code
pub fn image(self: PageBuilder, bytes: []const u8, x: f32, y: f32, w: f32, height: f32) Error!void; // draw an image
pub fn imageWithAlt(self: PageBuilder, bytes: []const u8, x: f32, y: f32, w: f32, height: f32, alt_text: [:0]const u8) Error!void; // draw an image with alt text
pub fn imageArtifact(self: PageBuilder, bytes: []const u8, x: f32, y: f32, w: f32, height: f32) Error!void; // draw an image tagged as an artifact
pub fn rect(self: PageBuilder, x: f32, y: f32, w: f32, height: f32) Error!void; // draw a rectangle outline
pub fn filledRect(self: PageBuilder, x: f32, y: f32, w: f32, height: f32, r: f32, g: f32, b: f32) Error!void; // draw a filled rectangle
pub fn line(self: PageBuilder, x1: f32, y1: f32, x2: f32, y2: f32) Error!void; // draw a line
pub fn strokeRect(self: PageBuilder, x: f32, y: f32, w: f32, height: f32, width: f32, r: f32, g: f32, b: f32) Error!void; // draw a stroked rectangle
pub fn strokeLine(self: PageBuilder, x1: f32, y1: f32, x2: f32, y2: f32, width: f32, r: f32, g: f32, b: f32) Error!void; // draw a stroked line
pub fn strokeRectDashed(self: PageBuilder, x: f32, y: f32, w: f32, height: f32, width: f32, r: f32, g: f32, b: f32, dash_array: []const f32, phase: f32) Error!void; // draw a dashed rectangle
pub fn strokeLineDashed(self: PageBuilder, x1: f32, y1: f32, x2: f32, y2: f32, width: f32, r: f32, g: f32, b: f32, dash_array: []const f32, phase: f32) Error!void; // draw a dashed line
pub fn textInRect(self: PageBuilder, x: f32, y: f32, w: f32, height: f32, txt: [:0]const u8, align_mode: i32) Error!void; // draw text in a box (align 0=Left 1=Center 2=Right)
Таблицы и потоковые таблицы
pub fn table(self: PageBuilder, n_columns: usize, widths: []const f32, aligns: []const i32, n_rows: usize, cells: []const [*:0]const u8, has_header: bool) Error!void; // draw a complete table
pub fn streamingTableBegin(self: PageBuilder, n_columns: usize, headers: []const [*:0]const u8, widths: []const f32, aligns: []const i32, repeat_header: bool) Error!void; // begin a row-streamed table
pub fn streamingTableBeginV2(self: PageBuilder, n_columns: usize, headers: []const [*:0]const u8, widths: []const f32, aligns: []const i32, repeat_header: bool, mode: i32, sample_rows: usize, min_col_width_pt: f32, max_col_width_pt: f32, max_rowspan: usize) Error!void; // begin a streamed table with auto-width options
pub fn streamingTableSetBatchSize(self: PageBuilder, batch_size: usize) Error!void; // set the streaming-table batch size
pub fn streamingTablePendingRowCount(self: PageBuilder) Error!usize; // pending buffered rows
pub fn streamingTableBatchCount(self: PageBuilder) Error!usize; // number of flushed batches
pub fn streamingTableFlush(self: PageBuilder) Error!void; // flush buffered rows
pub fn streamingTablePushRow(self: PageBuilder, cells: []const [*:0]const u8) Error!void; // push one streamed row
pub fn streamingTablePushRowV2(self: PageBuilder, cells: []const [*:0]const u8, rowspans: []const usize) Error!void; // push a streamed row with per-cell rowspans
pub fn streamingTableFinish(self: PageBuilder) Error!void; // finish the streamed table
Certificate
Учётные данные для подписания (либо разобранный сертификат из SignatureInfo.certificate).
pub fn loadFromBytes(data: []const u8, password: [:0]const u8) Error!Certificate; // load a PKCS#12/PFX blob (empty password if unprotected)
pub fn loadFromPem(cert_pem: [:0]const u8, key_pem: [:0]const u8) Error!Certificate; // load PEM certificate + private-key strings
pub fn deinit(self: *Certificate) void; // free the native handle (idempotent)
pub fn close(self: *Certificate) void; // free the native handle (idempotent)
pub fn subject(self: Certificate, alloc: std.mem.Allocator) Error![]u8; // subject distinguished name
pub fn issuer(self: Certificate, alloc: std.mem.Allocator) Error![]u8; // issuer distinguished name
pub fn serial(self: Certificate, alloc: std.mem.Allocator) Error![]u8; // serial number (decimal string)
pub fn validity(self: Certificate) Error!struct { notBefore: i64, notAfter: i64 }; // validity window (Unix epoch seconds)
pub fn isValid(self: Certificate) Error!bool; // whether the certificate is currently within its validity window
Timestamp
Разобранный токен метки времени RFC 3161.
pub fn parse(bytes: []const u8) Error!Timestamp; // parse a DER-encoded TimeStampToken (or bare TSTInfo)
pub fn deinit(self: *Timestamp) void; // free the native handle (idempotent)
pub fn close(self: *Timestamp) void; // free the native handle (idempotent)
pub fn token(self: Timestamp, alloc: std.mem.Allocator) Error![]u8; // the raw DER token bytes
pub fn messageImprint(self: Timestamp, alloc: std.mem.Allocator) Error![]u8; // the hashed message imprint
pub fn time(self: Timestamp) Error!i64; // timestamp time (Unix epoch seconds)
pub fn serial(self: Timestamp, alloc: std.mem.Allocator) Error![]u8; // TSA-assigned serial number
pub fn tsaName(self: Timestamp, alloc: std.mem.Allocator) Error![]u8; // name of the issuing TSA
pub fn policyOid(self: Timestamp, alloc: std.mem.Allocator) Error![]u8; // TSA policy OID
pub fn hashAlgorithm(self: Timestamp) Error!i32; // message-imprint hash algorithm identifier
pub fn verify(self: Timestamp) Error!bool; // cryptographically verify the token
TsaClient
Клиент удостоверяющего центра меток времени (TSA) RFC 3161 (доступен под флагом сборки tsa-client).
pub fn create(url: [:0]const u8, username: [:0]const u8, password: [:0]const u8, timeout: i32, hash_algo: i32, use_nonce: bool, cert_req: bool) Error!TsaClient; // configure a TSA client
pub fn deinit(self: *TsaClient) void; // free the native handle (idempotent)
pub fn close(self: *TsaClient) void; // free the native handle (idempotent)
pub fn requestTimestamp(self: TsaClient, data: []const u8) Error!Timestamp; // request a timestamp over data bytes
pub fn requestTimestampHash(self: TsaClient, hash: []const u8, hash_algo: i32) Error!Timestamp; // request a timestamp over a precomputed digest
Dss
Аксессор хранилища данных безопасности документа (Document Security Store), возвращаемый Document.dss().
pub fn deinit(self: *Dss) void; // free the native handle (idempotent)
pub fn close(self: *Dss) void; // free the native handle (idempotent)
pub fn certCount(self: Dss) Error!i32; // number of embedded certificates
pub fn crlCount(self: Dss) Error!i32; // number of embedded CRLs
pub fn ocspCount(self: Dss) Error!i32; // number of embedded OCSP responses
pub fn vriCount(self: Dss) Error!i32; // number of VRI (validation-related info) entries
pub fn getCert(self: Dss, alloc: std.mem.Allocator, index: i32) Error![]u8; // DER bytes of the index-th certificate
pub fn getCrl(self: Dss, alloc: std.mem.Allocator, index: i32) Error![]u8; // DER bytes of the index-th CRL
pub fn getOcsp(self: Dss, alloc: std.mem.Allocator, index: i32) Error![]u8; // DER bytes of the index-th OCSP response
SignatureInfo
Одна подпись, возвращаемая Document.signature(index).
pub fn deinit(self: *SignatureInfo) void; // free the native handle (idempotent)
pub fn close(self: *SignatureInfo) void; // free the native handle (idempotent)
pub fn signerName(self: SignatureInfo, alloc: std.mem.Allocator) Error![]u8; // signer common name
pub fn signingReason(self: SignatureInfo, alloc: std.mem.Allocator) Error![]u8; // stated signing reason
pub fn signingLocation(self: SignatureInfo, alloc: std.mem.Allocator) Error![]u8; // stated signing location
pub fn signingTime(self: SignatureInfo) Error!i64; // claimed signing time (Unix epoch seconds)
pub fn certificate(self: SignatureInfo) Error!Certificate; // the signer's certificate
pub fn padesLevel(self: SignatureInfo) Error!i32; // the PAdES baseline level
pub fn hasTimestamp(self: SignatureInfo) Error!bool; // whether an embedded RFC 3161 timestamp is present
pub fn timestamp(self: SignatureInfo) Error!Timestamp; // the embedded timestamp
pub fn addTimestamp(self: SignatureInfo, ts: Timestamp) Error!bool; // attach a timestamp; returns true on success
pub fn verify(self: SignatureInfo) Error!i32; // verify (1=valid 0=invalid -1=unknown)
pub fn verifyDetached(self: SignatureInfo, pdf_data: []const u8) Error!i32; // verify against external bytes (adds messageDigest check)
PdfAResults
Результат проверки соответствия PDF/A из Document.validatePdfA().
pub fn deinit(self: *PdfAResults) void; // free the native handle (idempotent)
pub fn close(self: *PdfAResults) void; // free the native handle (idempotent)
pub fn isCompliant(self: PdfAResults) Error!bool; // whether the document conforms
pub fn errorCount(self: PdfAResults) Error!i32; // number of errors
pub fn warningCount(self: PdfAResults) Error!i32; // number of warnings
pub fn getError(self: PdfAResults, alloc: std.mem.Allocator, index: i32) Error![]u8; // the index-th error message
pub fn errors(self: PdfAResults, alloc: std.mem.Allocator) Error![][]u8; // collect every error message
pub fn freeStrings(alloc: std.mem.Allocator, list: [][]u8) void; // free a slice returned by errors
PdfXResults
Результат проверки соответствия PDF/X из Document.validatePdfX().
pub fn deinit(self: *PdfXResults) void; // free the native handle (idempotent)
pub fn close(self: *PdfXResults) void; // free the native handle (idempotent)
pub fn isCompliant(self: PdfXResults) Error!bool; // whether the document conforms
pub fn errorCount(self: PdfXResults) Error!i32; // number of errors
pub fn getError(self: PdfXResults, alloc: std.mem.Allocator, index: i32) Error![]u8; // the index-th error message
pub fn errors(self: PdfXResults, alloc: std.mem.Allocator) Error![][]u8; // collect every error message
pub fn freeStrings(alloc: std.mem.Allocator, list: [][]u8) void; // free a slice returned by errors
UaResults
Результат проверки доступности PDF/UA из Document.validatePdfUa().
pub fn deinit(self: *UaResults) void; // free the native handle (idempotent)
pub fn close(self: *UaResults) void; // free the native handle (idempotent)
pub fn isAccessible(self: UaResults) Error!bool; // whether the document is accessible
pub fn errorCount(self: UaResults) Error!i32; // number of errors
pub fn warningCount(self: UaResults) Error!i32; // number of warnings
pub fn getError(self: UaResults, alloc: std.mem.Allocator, index: i32) Error![]u8; // the index-th error message
pub fn getWarning(self: UaResults, alloc: std.mem.Allocator, index: i32) Error![]u8; // the index-th warning message
pub fn errors(self: UaResults, alloc: std.mem.Allocator) Error![][]u8; // collect every error message
pub fn warnings(self: UaResults, alloc: std.mem.Allocator) Error![][]u8; // collect every warning message
pub fn uaStats(self: UaResults) Error!UaStats; // accessibility statistics (tagged-structure counts)
pub fn freeStrings(alloc: std.mem.Allocator, list: [][]u8) void; // free a slice returned by errors/warnings
Barcode
Создаёт или хранит изображение штрихкода для нанесения на страницу (DocumentEditor.addBarcodeToPage).
pub fn generateQrCode(data: [:0]const u8, error_correction: i32, size_px: i32) Error!Barcode; // generate a QR code
pub fn generateBarcode(data: [:0]const u8, format: i32, size_px: i32) Error!Barcode; // generate a barcode (0=Code128 … 7=Codabar)
pub fn deinit(self: *Barcode) void; // free the native handle (idempotent)
pub fn close(self: *Barcode) void; // free the native handle (idempotent)
pub fn getData(self: Barcode, alloc: std.mem.Allocator) Error![]u8; // the barcode's payload string
pub fn getFormat(self: Barcode) Error!i32; // the barcode's format code
pub fn getConfidence(self: Barcode) Error!f32; // the decode confidence (1.0 when freshly generated)
pub fn getImagePng(self: Barcode, alloc: std.mem.Allocator, size_px: i32) Error![]u8; // render the barcode to PNG bytes
pub fn getSvg(self: Barcode, alloc: std.mem.Allocator, size_px: i32) Error![]u8; // render the barcode to SVG
OcrEngine
Движок OCR, построенный из файлов модели и словаря (передаётся в Document.ocrExtractText).
pub fn create(det_model_path: [:0]const u8, rec_model_path: [:0]const u8, dict_path: [:0]const u8) Error!OcrEngine; // build an engine from model/dictionary paths
pub fn deinit(self: *OcrEngine) void; // free the native handle (idempotent)
pub fn close(self: *OcrEngine) void; // free the native handle (idempotent)
Renderer
Переиспользуемый дескриптор конфигурации рендерера.
pub fn create(dpi: i32, format: i32, quality: i32, anti_alias: bool) Error!Renderer; // create a renderer (format 0=PNG 1=JPEG)
pub fn deinit(self: *Renderer) void; // free the native handle (idempotent)
pub fn close(self: *Renderer) void; // free the native handle (idempotent)
Функции уровня модуля
Свободные функции модуля pdf_oxide: объединение, отсоединённое подписание, метки времени, логирование, лимиты и утилиты для работы с криптографией/моделями.
pub fn merge(alloc: std.mem.Allocator, paths: []const [*:0]const u8) Error![]u8; // merge several PDFs (by path) into one byte buffer
pub fn signBytes(alloc: std.mem.Allocator, pdf_data: []const u8, cert: Certificate, reason: [:0]const u8, location: [:0]const u8) Error![]u8; // sign raw PDF bytes (basic)
pub fn signBytesPades(alloc: std.mem.Allocator, pdf_data: []const u8, cert: Certificate, level: i32, tsa_url: ?[:0]const u8, reason: [:0]const u8, location: [:0]const u8, certs: []const []const u8, crls: []const []const u8, ocsps: []const []const u8) Error![]u8; // PAdES-sign raw PDF bytes (B-B/B-T/B-LT)
pub fn signBytesPadesOpts(alloc: std.mem.Allocator, pdf_data: []const u8, cert: Certificate, level: i32, tsa_url: ?[:0]const u8, reason: [:0]const u8, location: [:0]const u8, certs: []const []const u8, crls: []const []const u8, ocsps: []const []const u8) Error![]u8; // PAdES-sign via the options-struct C ABI
pub fn addTimestamp(alloc: std.mem.Allocator, pdf_data: []const u8, sig_index: i32, tsa_url: [:0]const u8) Error![]u8; // add a document timestamp to an existing signature
pub fn setLogLevel(level: i32) void; // set the global log level (0=Off … 5=Trace)
pub fn getLogLevel() i32; // get the current global log level (0-5)
pub fn setMaxOpsPerStream(limit: i64) i64; // global cap on content-stream operators (anti-DoS); returns the previous cap
pub fn setPreserveUnmappedGlyphs(preserve: bool) i32; // toggle preservation of unmapped glyphs; returns the new setting
pub fn cryptoActiveProvider(alloc: std.mem.Allocator) Error![]u8; // name of the active crypto provider
pub fn cryptoFipsAvailable() i32; // whether a FIPS-validated module is available (1/0)
pub fn cryptoUseFips() i32; // switch to the FIPS crypto provider; returns a status
pub fn cryptoSetPolicy(spec: [:0]const u8) i32; // set the crypto policy from a spec string; returns a status
pub fn cryptoPolicy(alloc: std.mem.Allocator) Error![]u8; // the active crypto policy as a string
pub fn cryptoInventory(alloc: std.mem.Allocator) Error![]u8; // crypto inventory (algorithms/providers) as JSON
pub fn cryptoCbom(alloc: std.mem.Allocator) Error![]u8; // a Cryptographic Bill of Materials (CBOM) JSON
pub fn prefetchModels(alloc: std.mem.Allocator, languages_csv: ?[:0]const u8) Error![]u8; // prefetch OCR models; returns the model cache dir
pub fn prefetchAvailable() i32; // whether this build can download models (1=yes, 0=cache-dir only)
pub fn modelManifest(alloc: std.mem.Allocator) Error![]u8; // the air-gapped OCR model manifest as JSON
Полный пример
const std = @import("std");
const pdf = @import("pdf_oxide");
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
defer _ = gpa.deinit();
const alloc = gpa.allocator();
// --- Extraction ---
var doc = try pdf.Document.open("input.pdf");
defer doc.deinit();
const pages = try doc.pageCount();
std.debug.print("Pages: {d}\n", .{pages});
const text = try doc.extractText(alloc, 0);
defer alloc.free(text);
std.debug.print("Page 1: {d} bytes\n", .{text.len});
// Render page 0 to PNG
var img = try doc.renderPage(alloc, 0, 0);
defer img.deinit();
try img.save("page0.png");
// --- Creation ---
var pdf_doc = try pdf.Pdf.fromMarkdown("# Report\n\nGenerated by PDF Oxide.");
defer pdf_doc.deinit();
try pdf_doc.save("report.pdf");
// --- Editing ---
var editor = try pdf.DocumentEditor.openEditor("document.pdf");
defer editor.deinit();
try editor.rotateAllPages(90);
try editor.setFormFieldValue("name", "John Doe");
try editor.save("output.pdf");
}
Other Language Bindings
PDF Oxide предоставляет нативные привязки для всех основных экосистем: Rust, Python, Node.js, WASM, C#, Golang, Java, PHP, Ruby, C++, Swift, Kotlin, Dart, R, Julia, Scala, Clojure, Objective-C, и Elixir.
Дальнейшие шаги
- Типы и перечисления — все общие типы и перечисления
- Справочник Page API — единообразная постраничная итерация для всех привязок
- Начало работы с Zig — учебное руководство