Skip to content

Dart API Reference

PDF Oxide ships idiomatic Dart/Flutter bindings built with dart:ffi over the native C ABI. The package loads the prebuilt libpdf_oxide.{so,dylib,dll} at runtime and exposes the full surface — extraction, editing, creation, rendering, forms, OCR, barcodes, digital signatures and conformance validation.

dart pub add pdf_oxide
import 'package:pdf_oxide/pdf_oxide.dart';

Native handles are freed automatically by a NativeFinalizer, but every handle-owning class also exposes an idempotent close() you should call when done (or use addTearDown/try/finally). C-ABI error codes are thrown as PdfOxideError. All page indices are zero-based.

For other languages, see the Python API Reference, the Node.js API Reference or WASM API Reference, the Rust API Reference, and Types & Enums.


PdfDocument

The primary class for opening, extracting from, rendering, validating and inspecting a PDF.

Constructors / Factories

static PdfDocument open(String path)
static PdfDocument openFromBytes(Uint8List data)
static PdfDocument openWithPassword(String path, String password)
static PdfDocument openFromDocxBytes(Uint8List data)
static PdfDocument openFromPptxBytes(Uint8List data)
static PdfDocument openFromXlsxBytes(Uint8List data)
  • open — open a PDF from a filesystem path.
  • openFromBytes — open a PDF from in-memory bytes.
  • openWithPassword — open a password-protected PDF.
  • openFromDocxBytes / openFromPptxBytes / openFromXlsxBytes — open a document directly from DOCX/PPTX/XLSX bytes.

Document Info

int get pageCount
PdfVersion get version
bool isEncrypted()
bool hasStructureTree()
bool authenticate(String password)
  • pageCount — number of pages.
  • version — PDF version as a PdfVersion(major, minor).
  • isEncrypted — whether the document is encrypted.
  • hasStructureTree — whether this is a Tagged PDF with a structure tree.
  • authenticate — authenticate an encrypted PDF; returns true on success, false for a wrong password.

Text & Conversion

String extractText(int page)
String toPlainText(int page)
String toMarkdown(int page)
String toHtml(int page)
String extractStructuredJson(int page)
String toMarkdownAll()
String toHtmlAll()
String toPlainTextAll()
  • extractText — plain extracted text for a single page.
  • toPlainText / toMarkdown / toHtml — convert a single page to plain text, Markdown or HTML.
  • extractStructuredJson — structured page content (spans, layout) serialized to JSON.
  • toMarkdownAll / toHtmlAll / toPlainTextAll — convert the whole document.

Element Extraction

List<Char> extractChars(int page)
List<Word> extractWords(int page)
List<TextLine> extractTextLines(int page)
List<Table> extractTables(int page)
List<Font> embeddedFonts(int page)
String embeddedFontsJson(int page)
List<double> embeddedFontSizes(int page)
List<Image> embeddedImages(int page)
List<Annotation> pageAnnotations(int page)
List<AnnotationDetails> pageAnnotationDetails(int page)
String annotationsToJson(int page)
List<Path> extractPaths(int page)
  • extractChars / extractWords / extractTextLines — per-glyph, per-word and per-line geometry.
  • extractTables — detected tables with lazily-read cells (Table.cell).
  • embeddedFonts / embeddedFontsJson / embeddedFontSizes — embedded font metadata for a page.
  • embeddedImages — embedded images with raw bytes.
  • pageAnnotations — annotations on a page.
  • pageAnnotationDetails — extended annotation attributes (flags, dates, colour, link URIs, icon names, quad points).
  • annotationsToJson — annotations serialized to JSON.
  • extractPaths — vector path (graphics) elements.

In-Rect Extraction

String extractTextInRect(int page, double x, double y, double w, double h)
List<Word> extractWordsInRect(int page, double x, double y, double w, double h)
List<TextLine> extractLinesInRect(int page, double x, double y, double w, double h)
List<Table> extractTablesInRect(int page, double x, double y, double w, double h)
List<Image> extractImagesInRect(int page, double x, double y, double w, double h)

Extract text, words, lines, tables or images restricted to a rectangle (PDF user-space points) on a page.

Auto Extraction & Classification

String extractTextAuto(int page)
String extractPageAuto(int page, [String optionsJson = ''])
String extractAllText()
String classifyPage(int page)
String classifyDocument()
  • extractTextAuto — native + image-OCR extraction as needed for a page.
  • extractPageAuto — auto-extract a single page with optional JSON options.
  • extractAllText — all pages’ text in one string.
  • classifyPage / classifyDocument — JSON page/document classification (scanned, digital, hybrid, etc.).
List<SearchResult> search(int page, String term, bool caseSensitive)
List<SearchResult> searchAll(String term, bool caseSensitive)
String searchResultsToJson(int page, String term, bool caseSensitive)

Search a single page, the whole document, or serialize page hits to JSON.

Rendering

RenderedImage renderPage(int pageIndex, [int format = 0])
RenderedImage renderPageZoom(int pageIndex, double zoom, [int format = 0])
RenderedImage renderPageThumbnail(int pageIndex, int size, [int format = 0])
RenderedImage renderPageWithOptions(int pageIndex, {int dpi = 150, int format = 0, double backgroundR = 1.0, double backgroundG = 1.0, double backgroundB = 1.0, double backgroundA = 1.0, bool transparentBackground = false, bool renderAnnotations = true, int jpegQuality = 90})
RenderedImage renderPageWithOptionsEx(int pageIndex, {int dpi = 150, int format = 0, double backgroundR = 1.0, double backgroundG = 1.0, double backgroundB = 1.0, double backgroundA = 1.0, bool transparentBackground = false, bool renderAnnotations = true, int jpegQuality = 90, List<String> excludedLayers = const []})
RenderedImage renderPageRegion(int pageIndex, double cropX, double cropY, double cropWidth, double cropHeight, [int format = 0])
RenderedImage renderPageFit(int pageIndex, int width, int height, [int format = 0])
RenderedImage renderPageRaw(int pageIndex, [int dpi = 150])
int estimateRenderTime(int pageIndex)
  • renderPage — render a page to a RenderedImage (format 0=PNG, 1=JPEG).
  • renderPageZoom — render at a zoom factor.
  • renderPageThumbnail — render a thumbnail fitting within size pixels.
  • renderPageWithOptions — full RenderOptions surface (dpi, background, annotations, JPEG quality).
  • renderPageWithOptionsEx — adds suppression of named OCG layers via excludedLayers.
  • renderPageRegion — render a rectangular region.
  • renderPageFit — render to fit inside width×height preserving aspect ratio.
  • renderPageRaw — render to a raw premultiplied RGBA8888 buffer at dpi.
  • estimateRenderTime — estimate render time (ms) for a page.

Page Geometry & Elements

double pageWidth(int pageIndex)
double pageHeight(int pageIndex)
int pageRotation(int pageIndex)
ElementList pageElements(int pageIndex)
Page page(int index)
  • pageWidth / pageHeight — page dimensions in PDF points.
  • pageRotation — page rotation in degrees.
  • pageElements — layout elements of a page as an ElementList.
  • page — a lightweight Page view for chained per-page extraction.

OCR

bool pageNeedsOcr(int pageIndex)
String ocrExtractText(int pageIndex, [OcrEngine? engine])
  • pageNeedsOcr — whether a page is scanned/hybrid and needs OCR.
  • ocrExtractText — extract text via OCR; engine may be null for native extraction only.

Conformance Validation & Conversion

PdfAResults validatePdfA(int level)
UaResults validatePdfUa(int level)
PdfXResults validatePdfX(int level)
bool convertToPdfA(int level)
  • validatePdfA / validatePdfUa / validatePdfX — validate against PDF/A, PDF/UA accessibility, or PDF/X.
  • convertToPdfA — convert this document in place to PDF/A at the given level.

Office Export

Uint8List toDocx()
Uint8List toPptx()
Uint8List toXlsx()
Uint8List sourceBytes()
  • toDocx / toPptx / toXlsx — export the document to DOCX/PPTX/XLSX bytes.
  • sourceBytes — the original source bytes this document was loaded from.
int eraseHeader(int page)
int eraseFooter(int page)
int eraseArtifacts(int page)
int removeHeaders([double threshold = 0.5])
int removeFooters([double threshold = 0.5])
int removeArtifacts([double threshold = 0.5])
  • eraseHeader / eraseFooter / eraseArtifacts — erase the header, footer or marked artifacts on a page; returns items erased.
  • removeHeaders / removeFooters / removeArtifacts — remove repeating furniture document-wide using a detection threshold.

Forms

List<FormField> getFormFields()
Uint8List exportFormDataToBytes([int formatType = 0])
void importFormData(String dataPath)
bool importFormFromFile(String filename)
  • getFormFields — interactive AcroForm fields.
  • exportFormDataToBytes — export form data (formatType 0=FDF, 1=XFDF, 2=JSON).
  • importFormData — import form data from an FDF/XFDF/JSON file path.
  • importFormFromFile — import field values from a file; returns whether anything was imported.

Document Structure & Metadata

String getOutline()
String getPageLabels()
String getXmpMetadata()
bool hasXfa()
String planSplitByBookmarks([String optionsJson = ''])
  • getOutline — document outline (bookmarks) as JSON.
  • getPageLabels — page label ranges as JSON.
  • getXmpMetadata — XMP metadata (XML) if present.
  • hasXfa — whether the document contains an XFA form.
  • planSplitByBookmarks — produce a JSON split-by-bookmarks plan.

Digital Signatures

int sign(Certificate certificate, {String reason = '', String location = ''})
int getSignatureCount()
SignatureInfo getSignature(int index)
int verifyAllSignatures()
bool hasTimestamp()
Dss getDss()
  • sign — digitally sign the document with a Certificate.
  • getSignatureCount — number of signatures present.
  • getSignature — the SignatureInfo at an index.
  • verifyAllSignatures — verify all signatures (aggregate status).
  • hasTimestamp — whether any signature carries a timestamp.
  • getDss — the document security store (Dss).

Lifecycle

void close()

Free the native handle now (idempotent).


Page

A lightweight, zero-based view of a single page returned by PdfDocument.page(index). Holds a strong reference to its document and delegates to the document’s per-page methods.

Member Type Description
index int Zero-based page index
String text()
String markdown()
String html()
String plainText()

Extracted text, Markdown, HTML or plain text for this page.


Pdf

A PDF produced (or loaded) for the simple builder/save flow.

Factories

static Pdf fromMarkdown(String md)
static Pdf fromHtml(String html)
static Pdf fromText(String text)
static Pdf fromImage(String path)
static Pdf fromImageBytes(Uint8List data)
static Pdf fromHtmlCss(String html, String css, [Uint8List? fontBytes])
static Pdf fromHtmlCssWithFonts(String html, String css, List<String> families, List<Uint8List> fonts)
  • fromMarkdown / fromHtml / fromText — create a PDF from Markdown, HTML or plain text.
  • fromImage / fromImageBytes — wrap an image file or image bytes in a single-page PDF.
  • fromHtmlCss — build from HTML + CSS with one optional embedded font.
  • fromHtmlCssWithFonts — build from HTML + CSS with a parallel families/fonts font cascade.

Methods

int get pageCount
void save(String path)
Uint8List toBytes()
void close()
  • pageCount — page count via the pdf_get_page_count entry point.
  • save — save to a file.
  • toBytes — the PDF content as bytes.
  • close — free the native handle (idempotent).

DocumentEditor

An opened PDF for in-place editing: page operations, metadata, forms, redaction, flatten, merge and encrypted saves.

Constructors

static DocumentEditor open(String path)
static DocumentEditor openFromBytes(Uint8List data)

Document Info & Metadata

int get pageCount
PdfVersion get version
bool isModified()
String getSourcePath()
String getProducer()
void setProducer(String value)
String getCreationDate()
void setCreationDate(String dateStr)
  • isModified — whether there are unsaved modifications.
  • getSourcePath — the path the editor was opened from.
  • getProducer / setProducer — the Producer metadata field.
  • getCreationDate / setCreationDate — the CreationDate metadata field.

Page Operations

void deletePage(int pageIndex)
void movePage(int from, int to)
void rotatePageBy(int page, int degrees)
void rotateAllPages(int degrees)
void setPageRotation(int page, int degrees)
int getPageRotation(int page)
void cropMargins(double left, double right, double top, double bottom)
Bbox getPageCropBox(int page)
void setPageCropBox(int page, Bbox box)
Bbox getPageMediaBox(int page)
void setPageMediaBox(int page, Bbox box)
  • deletePage / movePage — delete or reorder pages.
  • rotatePageBy — additive rotation; rotateAllPages — relative rotation of all pages; setPageRotation — absolute; getPageRotation — current.
  • cropMargins — crop margins on every page.
  • getPageCropBox / setPageCropBox / getPageMediaBox / setPageMediaBox — read/write the CropBox/MediaBox.

Redaction & Erase

void applyAllRedactions()
void applyPageRedactions(int page)
void eraseRegion(int page, double x, double y, double w, double h)
void eraseRegions(int page, List<List<double>> rects)
void clearEraseRegions(int page)
bool isPageMarkedForRedaction(int page)
void unmarkPageForRedaction(int page)
void redactionAdd(int page, double x1, double y1, double x2, double y2, {double r = 0.0, double g = 0.0, double b = 0.0})
int redactionCount(int page)
int redactionApply({bool scrubMetadata = false, double r = 0.0, double g = 0.0, double b = 0.0})
int redactionScrubMetadata()
  • applyAllRedactions / applyPageRedactions — apply queued redactions.
  • eraseRegion / eraseRegions / clearEraseRegions — erase one, many, or clear pending erase rectangles.
  • isPageMarkedForRedaction / unmarkPageForRedaction — query/clear a page’s redaction mark.
  • redactionAdd — queue a redaction rectangle with an overlay fill colour.
  • redactionCount — queued redaction regions for a page.
  • redactionApply — destructively apply all redactions; returns glyphs removed.
  • redactionScrubMetadata — strip metadata / JavaScript / embedded files; returns constructs removed.

Flatten

void flattenForms()
void flattenFormsOnPage(int pageIndex)
void flattenAnnotations(int page)
void flattenAllAnnotations()
int flattenWarningsCount()
String flattenWarning(int index)
bool isPageMarkedForFlatten(int page)
void unmarkPageForFlatten(int page)
  • flattenForms / flattenFormsOnPage — flatten all form fields, or those on one page.
  • flattenAnnotations / flattenAllAnnotations — flatten annotations on a page or document-wide.
  • flattenWarningsCount / flattenWarning — warnings from the last flatten save.
  • isPageMarkedForFlatten / unmarkPageForFlatten — query/clear a page’s flatten mark.

Forms

void setFormFieldValue(String name, String value)
void importFdfBytes(Uint8List data)
void importXfdfBytes(Uint8List data)
  • setFormFieldValue — set a field value by name.
  • importFdfBytes / importXfdfBytes — import AcroForm values from FDF/XFDF bytes.

Merge / Convert / Embed / Extract

void mergeFrom(String sourcePath)
void mergeFromBytes(Uint8List data)
void convertToPdfA(int level)
void embedFile(String name, Uint8List data)
Uint8List extractPagesToBytes(List<int> pages)
  • mergeFrom / mergeFromBytes — append pages from a PDF on disk or in memory.
  • convertToPdfA — convert in place to PDF/A (level 0=A1b … 7=A3u).
  • embedFile — attach a named file.
  • extractPagesToBytes — extract a subset of pages to a new in-memory PDF.

Barcodes

void addBarcodeToPage(int pageIndex, BarcodeImage barcode, double x, double y, double width, double height)

Stamp a generated BarcodeImage onto a page at the given rectangle.

Saving

void save(String path)
Uint8List saveToBytes()
Uint8List saveToBytesWithOptions(bool compress, bool garbageCollect, bool linearize)
void saveEncrypted(String path, String userPassword, String ownerPassword)
Uint8List saveEncryptedToBytes(String userPassword, String ownerPassword)
void close()
  • save / saveToBytes — save to a file or byte buffer.
  • saveToBytesWithOptions — save with explicit compression / garbage-collect / linearize options.
  • saveEncrypted / saveEncryptedToBytes — AES-256 encrypted save to file or bytes.
  • close — free the native handle (idempotent).

DocumentBuilder

A fluent builder for assembling a brand-new PDF document.

Create

static DocumentBuilder create()

Metadata (fluent)

DocumentBuilder setTitle(String value)
DocumentBuilder setAuthor(String value)
DocumentBuilder setSubject(String value)
DocumentBuilder setKeywords(String value)
DocumentBuilder setCreator(String value)
DocumentBuilder onOpen(String script)
DocumentBuilder language(String lang)
DocumentBuilder taggedPdfUa1()
DocumentBuilder roleMap(String custom, String standard)
DocumentBuilder registerEmbeddedFont(String name, EmbeddedFont font)
  • setTitle/setAuthor/setSubject/setKeywords/setCreator — document metadata.
  • onOpen — document-open JavaScript.
  • language — document language.
  • taggedPdfUa1 — enable PDF/UA-1 tagged mode.
  • roleMap — map a custom structure type to a standard PDF type.
  • registerEmbeddedFont — register a font under a name (consumes the EmbeddedFont on success).

Pages

PageBuilder a4Page()
PageBuilder letterPage()
PageBuilder page(double width, double height)

Open an A4, US Letter, or custom-sized page as a PageBuilder.

Build / Save

Uint8List build()
void save(String path)
void saveEncrypted(String path, String userPassword, String ownerPassword)
Uint8List toBytesEncrypted(String userPassword, String ownerPassword)
void close()
  • build — build the PDF and return its bytes.
  • save — build and save to a path.
  • saveEncrypted / toBytesEncrypted — AES-256 encrypted build to file or bytes.
  • close — free the native handle (idempotent).

PageBuilder

A fluent builder for a single page, returned by DocumentBuilder.page / letterPage / a4Page. Every op returns this for chaining. Call done() to commit the page or close() to discard it.

Text & Layout

PageBuilder font(String name, double size)
PageBuilder at(double x, double y)
PageBuilder text(String value)
PageBuilder heading(int level, String value)
PageBuilder paragraph(String value)
PageBuilder space(double points)
PageBuilder horizontalRule()
PageBuilder columns(int columnCount, double gapPt, String value)
PageBuilder inline(String value)
PageBuilder inlineBold(String value)
PageBuilder inlineItalic(String value)
PageBuilder inlineColor(double r, double g, double b, String value)
PageBuilder newline()
PageBuilder footnote(String refMark, String noteText)
PageBuilder textInRect(double x, double y, double w, double h, String value, int align)
PageBuilder newPageSameSize()
  • font / at — set the active font/size and cursor position.
  • text / heading / paragraph — emit text, a heading at a level, or a wrapped paragraph.
  • space / horizontalRule / newline — vertical spacing, a rule, a line break.
  • columns — multi-column text with a gap.
  • inline / inlineBold / inlineItalic / inlineColor — inline text runs.
  • footnote — a reference mark plus note text.
  • textInRect — text laid out inside a rectangle with an alignment code (0=Left, 1=Center, 2=Right).
  • newPageSameSize — start a new page of the same size.
PageBuilder linkUrl(String url)
PageBuilder linkPage(int page)
PageBuilder linkNamed(String destination)
PageBuilder linkJavascript(String script)

Attach a URL link, internal page link, named-destination link, or JavaScript link to the last content.

Actions & Field Scripts

PageBuilder onOpen(String script)
PageBuilder onClose(String script)
PageBuilder fieldKeystroke(String script)
PageBuilder fieldFormat(String script)
PageBuilder fieldValidate(String script)
PageBuilder fieldCalculate(String script)

Page open/close actions and AcroForm field keystroke/format/validate/calculate scripts.

Text Markup

PageBuilder highlight(double r, double g, double b)
PageBuilder underline(double r, double g, double b)
PageBuilder strikeout(double r, double g, double b)
PageBuilder squiggly(double r, double g, double b)

Markup annotations over the last text in an RGB colour.

Annotations / Watermark / Stamp

PageBuilder stickyNote(String value)
PageBuilder stickyNoteAt(double x, double y, String value)
PageBuilder watermark(String value)
PageBuilder watermarkConfidential()
PageBuilder watermarkDraft()
PageBuilder stamp(String typeName)
PageBuilder freetext(double x, double y, double w, double h, String value)
  • stickyNote / stickyNoteAt — a sticky note at the cursor or explicit position.
  • watermark / watermarkConfidential / watermarkDraft — custom or preset watermarks.
  • stamp — a named rubber stamp.
  • freetext — a free-text annotation in a rectangle.

Images & Barcodes

PageBuilder image(Uint8List bytes, double x, double y, double w, double h)
PageBuilder imageArtifact(Uint8List bytes, double x, double y, double w, double h)
PageBuilder imageWithAlt(Uint8List bytes, double x, double y, double w, double h, String altText)
PageBuilder barcode1d(int barcodeType, String data, double x, double y, double w, double h)
PageBuilder barcodeQr(String data, double x, double y, double size)
  • image — place an image; imageArtifact — place a non-content (artifact) image; imageWithAlt — place an image with alt text for accessibility.
  • barcode1d / barcodeQr — draw a 1-D barcode or QR code directly on the page.

Vector Graphics

PageBuilder rect(double x, double y, double w, double h)
PageBuilder filledRect(double x, double y, double w, double h, double r, double g, double b)
PageBuilder line(double x1, double y1, double x2, double y2)
PageBuilder strokeRect(double x, double y, double w, double h, double width, double r, double g, double b)
PageBuilder strokeLine(double x1, double y1, double x2, double y2, double width, double r, double g, double b)
PageBuilder strokeRectDashed(double x, double y, double w, double h, double width, double r, double g, double b, List<double> dashArray, [double phase = 0])
PageBuilder strokeLineDashed(double x1, double y1, double x2, double y2, double width, double r, double g, double b, List<double> dashArray, [double phase = 0])

Filled and stroked rectangles and lines, including dashed strokes with a dash array and phase.

Form Fields

PageBuilder textField(String name, double x, double y, double w, double h, [String? defaultValue])
PageBuilder checkbox(String name, double x, double y, double w, double h, bool checked)
PageBuilder comboBox(String name, double x, double y, double w, double h, List<String> options, int count, [String? selected])
PageBuilder radioGroup(String name, List<String> values, List<double> xs, List<double> ys, List<double> ws, List<double> hs, int count, [String? selected])
PageBuilder pushButton(String name, double x, double y, double w, double h, String caption)
PageBuilder signatureField(String name, double x, double y, double w, double h)

Add AcroForm widgets: text fields, checkboxes, combo boxes, radio groups, push buttons and signature fields.

Tables

PageBuilder table(int nCols, List<double> widths, List<int> aligns, int nRows, List<String> cellStrings, bool hasHeader)
PageBuilder streamingTableBegin(List<String> headers, List<double> widths, List<int> aligns, bool repeatHeader)
PageBuilder streamingTableBeginV2(List<String> headers, List<double> widths, List<int> aligns, bool repeatHeader, {int mode = 0, int sampleRows = 0, double minColWidthPt = 0, double maxColWidthPt = 0, int maxRowspan = 1})
PageBuilder streamingTablePushRow(List<String> cells)
PageBuilder streamingTablePushRowV2(List<String> cells, List<int> rowspans)
PageBuilder streamingTableFlush()
PageBuilder streamingTableFinish()
PageBuilder streamingTableSetBatchSize(int batchSize)
int streamingTableBatchCount()
int streamingTablePendingRowCount()
  • table — buffer a static, row-major table.
  • streamingTableBegin / streamingTableBeginV2 — begin a streaming table (v2 adds column-width mode, sample rows, min/max column widths and rowspan).
  • streamingTablePushRow / streamingTablePushRowV2 — push a row (v2 with per-cell rowspans).
  • streamingTableFlush / streamingTableFinish — flush pending rows / close the table.
  • streamingTableSetBatchSize — rows buffered before each flush.
  • streamingTableBatchCount / streamingTablePendingRowCount — batches flushed / rows pending.

Lifecycle

void done()
void close()
  • done — commit the buffered ops to the parent builder (consumes the handle).
  • close — discard the page and free the handle (idempotent).

EmbeddedFont

A loaded TTF/OTF font for embedding via DocumentBuilder.registerEmbeddedFont.

static EmbeddedFont fromFile(String path)
static EmbeddedFont fromBytes(Uint8List data, [String? name])
void close()
  • fromFile — load a font from a file path.
  • fromBytes — load from bytes; name defaults to the font’s PostScript name.
  • close — free the native handle (idempotent).

RenderedImage

A rasterised page image returned by PdfDocument.renderPage and friends.

int get width
int get height
Uint8List get data
void save(String path)
void close()
  • width / height — image dimensions in pixels.
  • data — encoded image bytes (e.g. PNG), copied into Dart.
  • save — write the encoded image to a path.
  • close — free the native handle (idempotent).

ElementList

The layout elements of a page, produced by PdfDocument.pageElements.

int get count
Element operator [](int index)
List<Element> toList()
String toJson()
void close()
  • count — number of elements.
  • operator [] — read the element at an index.
  • toList — all elements as a list.
  • toJson — the whole list serialized to JSON.
  • close — free the native handle (idempotent).

BarcodeImage

A generated 1-D barcode or QR code. Stamp onto a page with DocumentEditor.addBarcodeToPage.

static BarcodeImage qr(String data, {int errorCorrection = 0, int sizePx = 256})
static BarcodeImage barcode(String data, int format, {int sizePx = 256})
String get data
int get format
double get confidence
Uint8List imagePng({int sizePx = 256})
String svg({int sizePx = 256})
void close()
  • qr — generate a QR code with an error-correction level and pixel size.
  • barcode — generate a 1-D barcode in a given format code.
  • data / format / confidence — the encoded payload, format code, and decode confidence.
  • imagePng / svg — encode as PNG bytes or an SVG string.
  • close — free the native handle (idempotent).

OcrEngine

An OCR engine backed by detection/recognition model files, passed to PdfDocument.ocrExtractText.

static OcrEngine create(String detModelPath, String recModelPath, String dictPath)
void close()
  • create — create an engine from detection model, recognition model and dictionary file paths.
  • close — free the native handle (idempotent).

Renderer

A reusable page renderer configured with fixed DPI/format/quality.

static Renderer create({int dpi = 150, int format = 0, int quality = 90, bool antiAlias = true})
void close()
  • create — create a renderer (format 0=PNG, 1=JPEG; quality 1…100).
  • close — free the native handle (idempotent).

Certificate

Signing credentials / an X.509 certificate, used by the signing entry points.

static Certificate loadFromBytes(Uint8List bytes, String password)
static Certificate loadFromPem(String certPem, String keyPem)
Pointer<Void> get handle
String get subject
String get issuer
String get serial
CertificateValidity get validity
bool isValid()
void close()
  • loadFromBytes — load from a PKCS#12 (.p12/.pfx) buffer with a password.
  • loadFromPem — load from PEM certificate + private-key strings.
  • handle — the raw native handle (advanced/interop use).
  • subject / issuer / serial — distinguished names and serial number.
  • validity — the notBefore/notAfter window as a CertificateValidity.
  • isValid — whether the certificate is currently valid.
  • close — free the native handle (idempotent).

Timestamp

An RFC 3161 timestamp token.

static Timestamp parse(Uint8List bytes)
Uint8List get token
Uint8List get messageImprint
int get time
String get serial
String get tsaName
String get policyOid
int get hashAlgorithm
bool verify()
void close()
  • parse — parse a DER-encoded TimeStampToken (or bare TSTInfo).
  • token / messageImprint — the full token and hashed message-imprint bytes.
  • time — timestamp time (Unix epoch seconds).
  • serial / tsaName / policyOid / hashAlgorithm — token serial, TSA name, policy OID and hash-algorithm code.
  • verify — cryptographically verify the token.
  • close — free the native handle (idempotent).

TsaClient

An RFC 3161 TSA (timestamp authority) client.

static TsaClient create(String url, {String username = '', String password = '', int timeout = 30, int hashAlgo = 0, bool useNonce = true, bool certReq = true})
Timestamp requestTimestamp(Uint8List data)
Timestamp requestTimestampHash(Uint8List hash, int hashAlgo)
void close()
  • create — create a client for a TSA URL with optional basic-auth and request options.
  • requestTimestamp — request a timestamp over raw data (the client hashes it).
  • requestTimestampHash — request a timestamp over a precomputed hash.
  • close — free the native handle (idempotent).

SignatureInfo

Information about a digital signature embedded in a PDF, from PdfDocument.getSignature.

SignatureInfo.fromHandle(Pointer<Void> handle)
Pointer<Void> get handle
String get signerName
String get signingReason
String get signingLocation
int get signingTime
Certificate get certificate
int get padesLevel
bool hasTimestamp()
Timestamp get timestamp
bool addTimestamp(Timestamp ts)
int verify()
int verifyDetached(Uint8List pdf)
void close()
  • fromHandle — adopt a raw native handle (advanced/interop use).
  • signerName / signingReason / signingLocation / signingTime — signer metadata.
  • certificate — the signer’s Certificate.
  • padesLevel — PAdES baseline level code, or -1 if not PAdES.
  • hasTimestamp / timestamp — whether an embedded timestamp exists and the Timestamp itself.
  • addTimestamp — attach a timestamp to this signature.
  • verify — signer-attributes crypto check (1 valid / 0 invalid / -1 unknown).
  • verifyDetached — verify end-to-end against the full PDF bytes (1 valid / 0 invalid / -1 unknown).
  • close — free the native handle (idempotent).

Dss

A document /DSS (document security store), from PdfDocument.getDss.

Dss.fromHandle(Pointer<Void> handle)
int get certCount
int get crlCount
int get ocspCount
int get vriCount
Uint8List getCert(int index)
Uint8List getCrl(int index)
Uint8List getOcsp(int index)
void close()
  • fromHandle — adopt a raw DSS handle (advanced/interop use).
  • certCount / crlCount / ocspCount / vriCount — counts of certificates, CRLs, OCSP responses and VRI entries.
  • getCert / getCrl / getOcsp — the DER bytes of the certificate / CRL / OCSP response at an index.
  • close — free the native handle (idempotent).

PdfAResults

PDF/A validation results from PdfDocument.validatePdfA.

bool isCompliant()
List<String> errors()
List<String> warnings()
void close()
  • isCompliant — whether the document is PDF/A compliant.
  • errors / warnings — validation error and warning messages.
  • close — free the native handle (idempotent).

UaResults

PDF/UA accessibility validation results from PdfDocument.validatePdfUa.

bool isAccessible()
List<String> errors()
List<String> warnings()
UaStats uaStats()
void close()
  • isAccessible — whether the document is PDF/UA accessible.
  • errors / warnings — accessibility error and warning messages.
  • uaStats — element statistics gathered during validation.
  • close — free the native handle (idempotent).

PdfXResults

PDF/X validation results from PdfDocument.validatePdfX.

bool isCompliant()
List<String> errors()
void close()
  • isCompliant — whether the document is PDF/X compliant.
  • errors — validation error messages.
  • close — free the native handle (idempotent).

Top-Level Functions

These library-level functions live in the pdf_oxide namespace.

Merge & Timestamp

Uint8List pdfMerge(List<String> paths)
Uint8List addTimestamp(Uint8List pdf, int sigIndex, String tsaUrl)
  • pdfMerge — merge the PDFs at the given paths (in order) into one PDF; returns its bytes.
  • addTimestamp — apply an RFC 3161 timestamp to a signature, contacting a TSA; returns the timestamped PDF bytes.

Signing

Uint8List signBytes(Uint8List pdf, Certificate cert, {String reason = '', String location = ''})
Uint8List signBytesPades(Uint8List pdf, Certificate cert, int level, {String? tsaUrl, String reason = '', String location = '', List<Uint8List> certs = const [], List<Uint8List> crls = const [], List<Uint8List> ocsps = const []})
Uint8List signBytesPadesOpts(Uint8List pdf, Certificate cert, int level, {String? tsaUrl, String reason = '', String location = '', List<Uint8List> certs = const [], List<Uint8List> crls = const [], List<Uint8List> ocsps = const []})
  • signBytes — sign raw PDF bytes with a certificate; returns the signed bytes.
  • signBytesPades — sign at a PAdES baseline level (0=B-B, 1=B-T, 2=B-LT); tsaUrl is required for level ≥ 1 and certs/crls/ocsps carry B-LT revocation material.
  • signBytesPadesOpts — struct-options variant of signBytesPades with identical behaviour.

Logging

void setLogLevel(int level)
int getLogLevel()

Set/get the global library log level (0=Off, 1=Error, 2=Warn, 3=Info, 4=Debug, 5=Trace).

Crypto / FIPS

String cryptoActiveProvider()
String cryptoCbom()
String cryptoInventory()
String cryptoPolicy()
int cryptoFipsAvailable()
int cryptoUseFips()
int cryptoSetPolicy(String spec)
  • cryptoActiveProvider — the active cryptographic provider name.
  • cryptoCbom — the cryptographic bill of materials (CBOM) as JSON.
  • cryptoInventory — the cryptographic inventory as JSON.
  • cryptoPolicy — the active cryptographic policy as JSON.
  • cryptoFipsAvailable — whether a FIPS-validated provider is available (non-zero = yes).
  • cryptoUseFips — switch to a FIPS-validated provider; returns the status.
  • cryptoSetPolicy — set the cryptographic policy from a spec string; returns the status.

Models & Global Config

String modelManifest()
int prefetchAvailable()
String prefetchModels(String languagesCsv)
int setMaxOpsPerStream(int limit)
int setPreserveUnmappedGlyphs(int preserve)
  • modelManifest — the bundled model manifest as JSON.
  • prefetchAvailable — whether model prefetch is available in this build.
  • prefetchModels — prefetch OCR/layout models for comma-separated languages; returns a JSON report.
  • setMaxOpsPerStream — set the global per-content-stream operator limit; returns the prior value.
  • setPreserveUnmappedGlyphs — toggle preservation of unmapped glyphs; returns the prior value.

Error Handling

PdfOxideError

All non-success C-ABI error codes are thrown as PdfOxideError.

class PdfOxideError implements Exception {
  final int code;   // C-ABI error code
  final String op;  // the operation that failed
}

Calling a method on a handle after close() throws a Dart StateError. EmbeddedFont.fromBytes with invalid font data, Certificate.loadFromBytes with an invalid PKCS#12, and PdfDocument.open on a missing file all raise PdfOxideError.

import 'package:pdf_oxide/pdf_oxide.dart';

void main() {
  try {
    final doc = PdfDocument.open('input.pdf');
    print(doc.extractText(0));
    doc.close();
  } on PdfOxideError catch (e) {
    print('PDF error: $e');  // PdfOxideError: <op> failed (error code <code>)
  }
}

Value Types

Plain data classes returned by extraction and inspection methods.

PdfVersion

Field Type Description
major int Major version
minor int Minor version

Bbox

An axis-aligned bounding box in PDF user-space points.

Field Type Description
x, y double Lower-left origin
width, height double Box size

Char

Field Type Description
character int Unicode codepoint
bbox Bbox Glyph bounding box
fontName String PostScript font name
fontSize double Font size in points

Word

Field Type Description
text String Word text
bbox Bbox Bounding box
fontName String Font name
fontSize double Font size
bold bool Whether bold

TextLine

Field Type Description
text String Line text
bbox Bbox Bounding box
wordCount int Number of words

Table

Member Type Description
rowCount int Number of rows
colCount int Number of columns
hasHeader bool Whether a header row is present
cell(int row, int col) String Text of a 0-based cell

Font

Field Type Description
name String Font name
type String Font type
encoding String Encoding
embedded bool Whether embedded
subset bool Whether subset

Image

Field Type Description
width, height int Pixel dimensions
bitsPerComponent int Bits per component
format String Image format
colorspace String Colour space
data Uint8List Raw image bytes

Annotation

Field Type Description
type String Annotation type
subtype String Annotation subtype
content String Text content
author String Author
rect Bbox Position
borderWidth double Border width

Path

Field Type Description
bbox Bbox Bounding box
strokeWidth double Stroke width
hasStroke bool Whether stroked
hasFill bool Whether filled
operationCount int Number of path operations

SearchResult

Field Type Description
text String Matched text
page int Zero-based page index
bbox Bbox Match bounding box

FormField

Field Type Description
name String Fully-qualified field name
value String Current value
type String Field type (Tx, Btn, Ch, Sig)
readonly bool Whether read-only
required bool Whether required

QuadPoint

A highlight-annotation quad (four corner points): x1, y1, x2, y2, x3, y3, x4, y4 (double).

AnnotationDetails

Field Type Description
type, subtype, content String Annotation type/subtype and contents
rect Bbox Position
color int Packed ARGB colour
creationDate, modificationDate int Unix epoch seconds (0 if absent)
hidden, markedDeleted, printable, readOnly bool Annotation flags
linkUri String Link target URI (empty otherwise)
iconName String Text-annotation icon name (empty otherwise)
quadPoints List<QuadPoint> Highlight quad points (empty otherwise)

CertificateValidity

Field Type Description
notBefore int Valid-from time (Unix epoch seconds)
notAfter int Valid-until time (Unix epoch seconds)

UaStats

Field Type Description
structElements int Structure elements
images int Images
tables int Tables
forms int Form fields
annotations int Annotations
pages int Pages

Element

Field Type Description
type String Element type (e.g. Text, Image, Table)
text String Text content (may be empty)
rect Bbox Bounding box

Complete Example

import 'dart:io';
import 'package:pdf_oxide/pdf_oxide.dart';

void main() {
  // --- Creation ---
  final pdf = Pdf.fromMarkdown('# Report\n\nGenerated by PDF Oxide.');
  pdf.save('report.pdf');
  pdf.close();

  // --- Builder ---
  final db = DocumentBuilder.create()..setTitle('Invoice');
  final page = db.letterPage();
  page
      .font('Helvetica', 14)
      .heading(1, 'Invoice')
      .paragraph('Thank you for your business.')
      .done();
  File('invoice.pdf').writeAsBytesSync(db.build());
  db.close();

  // --- Extraction ---
  final doc = PdfDocument.open('report.pdf');
  print('Pages: ${doc.pageCount}');
  for (var i = 0; i < doc.pageCount; i++) {
    print('Page $i: ${doc.extractText(i).length} chars');
  }
  for (final word in doc.extractWords(0)) {
    print('${word.text} @ ${word.bbox}');
  }

  // --- Search ---
  for (final hit in doc.searchAll('PDF Oxide', false)) {
    print('Found "${hit.text}" on page ${hit.page}');
  }

  // --- Rendering ---
  final img = doc.renderPage(0);
  img.save('page0.png');
  img.close();
  doc.close();

  // --- Editing ---
  final ed = DocumentEditor.open('report.pdf');
  ed.rotateAllPages(90);
  ed.setProducer('PDF Oxide');
  ed.save('rotated.pdf');
  ed.close();
}

Other Language Bindings

PDF Oxide ships native bindings for every major ecosystem: Rust, Python, Node.js, WASM, C#, Golang, Java, PHP, Ruby, C++, Swift, Kotlin, R, Julia, Zig, Scala, Clojure, Objective-C, and Elixir.

Next Steps