Skip to content

Scala API Reference

PDF Oxide ships idiomatic Scala 3 bindings as a thin, pure-JVM facade over the mature fyi.oxide:pdf-oxide Java binding, which owns the single JNI native bridge (the pdf_oxide_jni crate). The Scala module adds zero native code: it uses the Java types (Pdf, PdfDocument, PdfPage, DocumentEditor, AutoExtractor, PdfSigner, PdfValidator, and the geometry/text/table/search value types) directly, and layers Scala 3 extension methods that turn java.util.Optional[T] into Option[T] and java.util.List[T] into Seq[T]. scala.util.Using works out of the box on every AutoCloseable handle.

// build.sbt — cross-versioned for Scala 3 (resolves pdf-oxide-scala_3)
libraryDependencies += "fyi.oxide" %% "pdf-oxide-scala" % "0.3.69"

The JNI native library (libpdf_oxide_jni) is not bundled. Make it loadable via System.loadLibrary("pdf_oxide_jni") on your java.library.path, or point the Java NativeLoader at it with -Dfyi.oxide.pdf.lib.path=<path>.

import fyi.oxide.pdf.{Pdf, PdfDocument, producerOption, wordsSeq}
import scala.util.Using

Using.resource(Pdf.fromMarkdown("# Hello\n\nbody\n")): pdf =>
  Using.resource(PdfDocument.open(pdf.save())): doc =>
    println(doc.pageCount())
    println(doc.extractText(0))
    println(doc.toMarkdown())
    println(doc.page(0).wordsSeq.map(_.text))       // List -> Seq
    println(doc.producerOption.getOrElse("(none)")) // Optional -> Option

For the Java API, see the Java API Reference. For the Rust API, see the Rust API Reference. For type details, see Types & Enums.


Pdf

fyi.oxide.pdf.Pdf — create new PDFs from source formats and split existing ones. Implements AutoCloseable.

Factory Methods

def fromMarkdown(markdown: String): Pdf

Create a PDF from Markdown content.

def fromHtml(html: String): Pdf

Create a PDF from HTML content.

def fromImages(images: java.util.List[Array[Byte]]): Pdf

Create a multi-page PDF, one page per image (JPEG/PNG bytes).

Splitting

def planSplitByBookmarks(opts: SplitByBookmarksOptions): java.util.List[BookmarkSegment]

Plan a bookmark-based split without producing bytes; returns the segments that would be created.

def splitByBookmarks(opts: SplitByBookmarksOptions): java.util.List[Array[Byte]]

Split the document at bookmark boundaries, returning one PDF byte array per segment.

def planSplitByBookmarksCount(sourcePdf: Array[Byte], level: Int): Int

Static helper: count the segments a bookmark split at the given outline level would produce.

def splitByBookmarksFromBytes(sourcePdf: Array[Byte], level: Int): Array[Array[Byte]]

Static helper: split source PDF bytes at the given outline level into per-segment byte arrays.

Saving & Lifecycle

def save(): Array[Byte]
def saveTo(out: java.nio.file.Path): Unit
def isOpen(): Boolean
def close(): Unit

Serialize the PDF to bytes or to a file path, check whether the native handle is live, and release it.


PdfDocument

fyi.oxide.pdf.PdfDocument — open, extract, render, and query a PDF. Implements AutoCloseable.

Opening

def open(path: java.nio.file.Path): PdfDocument
def open(path: String): PdfDocument
def open(bytes: Array[Byte]): PdfDocument
def open(path: java.nio.file.Path, password: String): PdfDocument
def open(path: String, password: String): PdfDocument
def open(bytes: Array[Byte], password: String): PdfDocument
def open(stream: java.io.InputStream): PdfDocument

Open a PDF from a file path, in-memory bytes, or an input stream. Password overloads decrypt encrypted documents in one step.

Static Extraction

def extractText(path: String): String
def extractText(path: java.nio.file.Path): String

One-shot convenience: open the file, extract all text, and close it.

Document Info & Auth

def pageCount(): Int
def authenticate(password: String): Boolean
def authenticate(password: Array[Byte]): Boolean
def isOpen(): Boolean
def close(): Unit

Page count, post-open authentication for encrypted PDFs (string or raw bytes), handle liveness, and disposal.

Metadata

def producer(): java.util.Optional[String]
def creator(): java.util.Optional[String]

Document producer / creator strings. Use the facade producerOption / creatorOption for idiomatic Option[String].

Text Extraction

def extractText(pageIndex: Int): String
def extractTextAuto(pageIndex: Int): String
def extractStructured(page: Int): String

Extract plain text for a page, text with automatic OCR fallback for scanned pages, or a structured JSON representation. Pages are zero-indexed.

Conversion

def toMarkdown(): String
def toMarkdown(pageIndex: Int): String
def toHtml(): String
def toHtml(pageIndex: Int): String

Convert the whole document or a single page to Markdown or HTML.

Rendering

def render(pageIndex: Int): Array[Byte]
def render(pageIndex: Int, dpi: Int): Array[Byte]

Rasterize a page to PNG bytes, optionally at a chosen DPI.

def page(index: Int): PdfPage
def pages(): java.util.List[PdfPage]
def pagesStream(): java.util.stream.Stream[PdfPage]
def formFields(): java.util.List[FormField]
def search(query: String): java.util.List[SearchMatch]
def search(query: String, caseInsensitive: Boolean, regex: Boolean, maxResults: Int): java.util.List[SearchMatch]

Get a single page handle, all pages (as a list or stream), all AcroForm fields, and search matches across the document. maxResults = 0 means unlimited. Use the facade pagesSeq, formFieldsSeq, and searchSeq for Scala Seq results.


PdfPage

fyi.oxide.pdf.PdfPage — a single page handle returned by PdfDocument.page / pages.

Geometry

def parent(): PdfDocument
def index(): Int
def mediaBox(): BBox
def cropBox(): BBox
def width(): Double
def height(): Double
def rotation(): Int

Owning document, zero-based index, MediaBox / CropBox rectangles, page dimensions in points, and rotation in degrees.

Content Extraction

def text(): String
def text(region: BBox): String
def words(): java.util.List[TextWord]
def lines(): java.util.List[TextLine]
def chars(): java.util.List[TextChar]
def images(): java.util.List[ExtractedImage]
def tables(): java.util.List[Table]
def annotations(): java.util.List[Annotation]

Full-page or region-clipped text, plus structured words, lines, characters, images, tables, and annotations. Use the facade wordsSeq, linesSeq, charsSeq, imagesSeq, tablesSeq, and annotationsSeq for Scala Seq.


DocumentEditor

fyi.oxide.pdf.DocumentEditor — fill forms, redact, scrub metadata, and save (incrementally or fully). Implements AutoCloseable. Setter methods are fluent and return this.

Opening

def open(path: java.nio.file.Path): DocumentEditor
def open(path: String): DocumentEditor
def open(bytes: Array[Byte]): DocumentEditor

Forms

def setFormField(name: String, value: String): DocumentEditor
def setFormField(name: String, checked: Boolean): DocumentEditor

Set a text/choice field value or toggle a checkbox/radio field.

Redaction

def addRedaction(pageIndex: Int, region: BBox): DocumentEditor
def redactionCount(pageIndex: Int): Int
def redactionCount(): Int
def applyRedactionsDestructive(): RedactResult

Queue a redaction rectangle, count pending redactions per page or total, and apply them destructively (removing the underlying content), returning a RedactResult.

Metadata & Saving

def scrubMetadata(): DocumentEditor
def save(): Array[Byte]
def saveTo(out: java.nio.file.Path): Unit
def saveIncremental(): Array[Byte]
def saveIncrementalTo(out: java.nio.file.Path): Unit
def isOpen(): Boolean
def close(): Unit

Strip identifying metadata, then save either a fully rewritten or incrementally-appended PDF to bytes or disk.


AutoExtractor

fyi.oxide.pdf.AutoExtractor — intelligent extraction that classifies pages and falls back to OCR where needed.

Construction

def of(doc: PdfDocument): AutoExtractor
def of(doc: PdfDocument, config: AutoExtractConfig): AutoExtractor
def fast(doc: PdfDocument): AutoExtractor
def balanced(doc: PdfDocument): AutoExtractor
def highFidelity(doc: PdfDocument): AutoExtractor

Build an extractor with default, custom, or preset (fast / balanced / high-fidelity) configuration.

Extraction

def extractText(): String
def extractTextForPage(pageIndex: Int): String
def extractDocument(): AutoResult
def extractPage(pageIndex: Int): AutoResult
def extractAutoDocument(): AutoResult
def extractAutoPage(pageIndex: Int): AutoResult
def extractDocumentJson(): String
def extractPageJson(pageIndex: Int): String

Extract plain text or rich AutoResult records (text, optional Markdown/HTML, confidence, OCR usage, regions) for the whole document or a single page, plus JSON variants.

Classification & Accessors

def classifyDocument(): ClassifyResult
def classifyPage(pageIndex: Int): ClassifyResult
def document(): PdfDocument
def config(): AutoExtractConfig

Classify pages (text-layer / scanned / mixed, plus OCR/chart/encrypted page lists) without extracting, and read back the source document and config.


MarkdownConverter

fyi.oxide.pdf.MarkdownConverter — static Markdown/HTML conversion helpers.

def toMarkdown(doc: PdfDocument): String
def toMarkdown(doc: PdfDocument, pageIndex: Int): String
def toHtml(doc: PdfDocument): String
def toHtml(doc: PdfDocument, pageIndex: Int): String

Convert a whole document or a single page to Markdown or HTML.


PdfSigner

fyi.oxide.pdf.PdfSigner — PAdES / CMS digital signing and verification.

def fromPkcs12(keystore: java.nio.file.Path, password: String): PdfSigner
def fromPkcs12(keystoreBytes: Array[Byte], password: String): PdfSigner
def sign(pdf: Array[Byte], opts: SignOptions): Array[Byte]
def verify(pdf: Array[Byte]): Boolean
def classifyLevel(pdf: Array[Byte]): SignatureLevel

Load a signer from a PKCS#12 keystore (file or bytes), sign a PDF with the given SignOptions, verify an existing signature, and statically classify a signed PDF’s PAdES level.


PdfValidator

fyi.oxide.pdf.PdfValidator — PDF/A, PDF/X, and PDF/UA compliance checks.

def isPdfA(doc: PdfDocument, level: PdfALevel): Boolean
def isPdfUa(doc: PdfDocument, level: PdfUaLevel): Boolean
def validatePdfA(doc: PdfDocument, level: PdfALevel): ValidationResult
def validatePdfX(doc: PdfDocument, level: PdfXLevel): ValidationResult
def validatePdfUa(doc: PdfDocument, level: PdfUaLevel): ValidationResult

Boolean quick-checks plus full ValidationResult reports (with per-rule violations) for PDF/A, PDF/X, and PDF/UA.


PdfPolicy

fyi.oxide.pdf.PdfPolicy — global cryptographic policy mode.

def current(): PolicyMode
def set(mode: PolicyMode): Unit
def compat(): PolicyMode
def strict(): PolicyMode
def fipsStrict(): PolicyMode

Read or set the process-wide policy mode, and access the COMPAT / STRICT / FIPS_STRICT presets.


Result & Value Types

AutoResult

def text(): String
def markdown(): java.util.Optional[String]   // facade: markdownOption
def html(): java.util.Optional[String]       // facade: htmlOption
def reason(): ExtractReason
def confidence(): Double
def ocrUsed(): Boolean
def regions(): java.util.List[RegionResult]
def pagesNeedingOcr(): java.util.List[Integer]  // facade: pagesNeedingOcrSeq

RegionResult

def pageIndex(): Int
def bbox(): BBox
def text(): String
def reason(): ExtractReason
def confidence(): Double
def ocrUsed(): Boolean
def table(): java.util.Optional[Table]

ClassifyResult

def pages(): java.util.List[PageClass]
def pagesNeedingOcr(): java.util.List[Integer]
def pagesWithChart(): java.util.List[Integer]
def pagesEncrypted(): java.util.List[Integer]

AutoExtractConfig

Immutable config built via AutoExtractConfig.builder() (or .toBuilder()). Accessors return Optional:

def builder(): AutoExtractConfig.Builder
def toBuilder(): AutoExtractConfig.Builder
def mode(): java.util.Optional[ExtractMode]
def forceOcrPages(): java.util.Optional[java.util.List[Integer]]
def minOcrConfidence(): java.util.Optional[Double]
def ocrLanguages(): java.util.Optional[java.util.List[String]]
def passwords(): java.util.Optional[java.util.List[String]]
def topMarginFraction(): java.util.Optional[Double]
def bottomMarginFraction(): java.util.Optional[Double]
def allowSingleColumnTables(): java.util.Optional[Boolean]
def ocrInlineImages(): java.util.Optional[Boolean]
def cancelToken(): java.util.Optional[String]

AutoExtractConfig.Builder:

def withMode(m: ExtractMode): Builder
def withForceOcrPages(p: java.util.List[Integer]): Builder
def withMinOcrConfidence(c: Double): Builder
def withOcrLanguages(l: java.util.List[String]): Builder
def withOcrLanguages(l: String*): Builder
def withPasswords(p: java.util.List[String]): Builder
def withPasswords(p: String*): Builder
def withTopMarginFraction(f: Double): Builder
def withBottomMarginFraction(f: Double): Builder
def withAllowSingleColumnTables(b: Boolean): Builder
def withOcrInlineImages(b: Boolean): Builder
def withCancelToken(t: String): Builder
def build(): AutoExtractConfig

ValidationResult / ValidationViolation

// ValidationResult
def valid(): Boolean
def violations(): java.util.List[ValidationViolation]

// ValidationViolation
def ruleId(): String
def description(): String
def pageIndex(): java.util.Optional[Integer]  // facade: pageIndexOption

RedactResult

def regionsApplied(): Int
def oracleVerified(): Boolean

SearchResult / SearchMatch / SearchOptions

// SearchResult
def query(): String
def matches(): java.util.List[SearchMatch]
def count(): Int
def isEmpty(): Boolean

// SearchMatch
def pageIndex(): Int
def bbox(): BBox
def text(): String

// SearchOptions (builder via SearchOptions.builder())
def caseSensitive(): Boolean
def wholeWord(): Boolean
def regex(): Boolean
def maxResults(): java.util.Optional[Integer]

SearchOptions.Builder: withCaseSensitive(b: Boolean), withWholeWord(b: Boolean), withRegex(b: Boolean), withMaxResults(m: Int), build().

FormField

def name(): String
def type(): FormFieldType
def value(): java.util.Optional[String]   // facade: valueOption
def bbox(): java.util.Optional[BBox]       // facade: bboxOption
def pageIndex(): Int

Annotation

def `type`(): AnnotationType
def pageIndex(): Int
def bbox(): BBox
def contents(): java.util.Optional[String]  // facade: contentsOption
def uri(): java.util.Optional[String]        // facade: uriOption

ExtractedImage

def bytes(): Array[Byte]
def format(): ImageFormat
def bbox(): BBox
def width(): Int
def height(): Int

Table / TableCell

// Table
def bbox(): BBox
def rows(): Int
def cols(): Int
def cells(): java.util.List[TableCell]

// TableCell
def text(): String
def bbox(): BBox
def row(): Int
def col(): Int
def rowSpan(): Int
def colSpan(): Int

Text Types

// TextWord
def text(): String
def bbox(): BBox
def confidence(): Float

// TextLine
def text(): String
def bbox(): BBox
def words(): java.util.List[TextWord]

// TextChar
def codepoint(): Int
def bbox(): BBox
def confidence(): Float
def asString(): String

// TextSpan
def text(): String
def bbox(): BBox
def style(): TextStyle

// TextStyle
def size(): Double
def color(): Color
def bold(): Boolean
def italic(): Boolean

Geometry

// BBox(x0, y0, x1, y1)
def x0(): Double
def y0(): Double
def x1(): Double
def y1(): Double
def width(): Double
def height(): Double

// Color(r, g, b[, a])
def r(): Int
def g(): Int
def b(): Int
def a(): Int

// Point(x, y)
def x(): Double
def y(): Double

// Rect(x, y, width, height)
def x(): Double
def y(): Double
def width(): Double
def height(): Double
def toBBox(): BBox

Metadata

// DocumentInfo — all accessors return Optional[String]
def title(); def author(); def subject(); def keywords()
def creator(); def producer(); def creationDate(); def modificationDate()

// XmpMetadata(xml: String)
def xml(): String
def isEmpty(): Boolean

Signing & Splitting Options

// SignOptions (builder via SignOptions.builder())
def level(): SignatureLevel
def reason(): java.util.Optional[String]
def location(): java.util.Optional[String]
def contactInfo(): java.util.Optional[String]
def tsaUrl(): java.util.Optional[String]
// Builder: withLevel, withReason, withLocation, withContactInfo, withTsaUrl, build

// SplitByBookmarksOptions (builder via SplitByBookmarksOptions.builder())
def level(): Int
def filenamePrefix(): java.util.Optional[String]
// Builder: withLevel(l: Int), withFilenamePrefix(p: String), build

// BookmarkSegment
def title(): String
def firstPage(): Int
def lastPage(): Int
def filename(): String

SecurityPolicy

def mode(): PolicyMode
def additionalAllow(): java.util.List[String]
def additionalDeny(): java.util.List[String]
def builder(): SecurityPolicy.Builder
// Builder: withMode(m: PolicyMode), allow(algId: String), deny(algId: String), build

Enums

Enum Constants
AnnotationType HIGHLIGHT, TEXT, LINK, STAMP, UNDERLINE, STRIKEOUT, SQUIGGLY, FREE_TEXT, LINE, SQUARE, CIRCLE, FILE_ATTACHMENT
FormFieldType TEXT, CHECKBOX, RADIO, CHOICE, SIGNATURE
ImageFormat JPEG, PNG, JBIG2, JPEG2000, CCITT, RAW
ExtractMode TEXT_ONLY, AUTO
ExtractReason OK, SCANNED_NO_TEXT_LAYER, GLYPH_MAPPING_MISSING, ENCRYPTED_NO_EXTRACT_PERMISSION, IMAGE_TABLE_NO_STRUCTURE, CHART_NOT_TRANSCRIBED, OCR_REQUESTED_BUT_UNAVAILABLE, OCR_LOW_CONFIDENCE, EMPTY
PageClass TEXT_LAYER, SCANNED, MIXED
PdfALevel A_1B, A_1A, A_2B, A_2A, A_2U, A_3B, A_3A, A_3U, A_4, A_4E
PdfUaLevel UA_1, UA_2 (each exposes code(): Int)
PdfXLevel X_1A_2001, X_1A_2003, X_3_2002, X_3_2003, X_4, X_4P, X_5G, X_5N, X_5PG, X_6, X_6P
PolicyMode COMPAT, STRICT, FIPS_STRICT
PixelFormat RGBA_8888, RGB_888, GRAY_8
SignatureLevel B_B, B_T, B_LT

Scala Facade Extensions

The Scala module adds these extension methods on top of the Java types so callers get Option/Seq instead of java.util.Optional/java.util.List. Import the ones you need from fyi.oxide.pdf.

// Generic — any java.util.Optional[T]
extension [T](o: java.util.Optional[T]) def toOption: Option[T]

// PdfDocument
extension (doc: PdfDocument)
  def producerOption: Option[String]
  def creatorOption: Option[String]
  def formFieldsSeq: Seq[FormField]
  def pagesSeq: Seq[PdfPage]
  def searchSeq(query: String): Seq[SearchMatch]

// PdfPage
extension (page: PdfPage)
  def wordsSeq: Seq[TextWord]
  def linesSeq: Seq[TextLine]
  def charsSeq: Seq[TextChar]
  def tablesSeq: Seq[Table]
  def imagesSeq: Seq[ExtractedImage]
  def annotationsSeq: Seq[Annotation]

// FormField
extension (f: FormField)
  def valueOption: Option[String]
  def bboxOption: Option[BBox]

// Annotation
extension (a: Annotation)
  def contentsOption: Option[String]
  def uriOption: Option[String]

// AutoResult
extension (r: AutoResult)
  def markdownOption: Option[String]
  def htmlOption: Option[String]
  def pagesNeedingOcrSeq: Seq[Int]

// ValidationViolation
extension (v: ValidationViolation)
  def pageIndexOption: Option[Int]

Exceptions

All errors derive from fyi.oxide.pdf.exception.PdfException:

Exception Cause
PdfException Base class for all PDF Oxide errors
PdfParseException Malformed or corrupt PDF
PdfEncryptedException Encrypted PDF opened without a password
PdfPermissionException Operation not permitted by the document’s encryption flags
PdfInvalidStateException Operation on a closed or invalid handle
PdfIoException Underlying I/O failure
PdfUnsupportedException Unsupported feature or format
PdfOcrUnavailableException OCR requested but the ocr feature is not built in
PdfSignatureException Signing or signature-verification failure

PdfErrorKind is an enum classifying the specific error category carried by a PdfException.


Complete Example

import fyi.oxide.pdf.*
import fyi.oxide.pdf.auto.AutoExtractConfig
import scala.util.Using

// --- Creation ---
Using.resource(Pdf.fromMarkdown("# Report\n\nGenerated by PDF Oxide.")): pdf =>
  pdf.saveTo(java.nio.file.Path.of("report.pdf"))

// --- Extraction ---
Using.resource(PdfDocument.open("report.pdf")): doc =>
  println(s"Pages: ${doc.pageCount()}")

  val page = doc.page(0)
  println(s"${page.width()} x ${page.height()}")
  page.wordsSeq.foreach(w => println(s"${w.text} @ ${w.bbox.x0}"))

  // Search (facade -> Seq)
  doc.searchSeq("Report").foreach(m => println(s"p${m.pageIndex}: ${m.text}"))

  // Metadata (facade -> Option)
  println(doc.producerOption.getOrElse("(none)"))

  // Auto extraction with OCR fallback
  val cfg = AutoExtractConfig.builder().withMinOcrConfidence(0.6).build()
  val result = AutoExtractor.of(doc, cfg).extractDocument()
  println(s"confidence=${result.confidence} ocr=${result.ocrUsed}")
  result.markdownOption.foreach(println)

// --- Editing: fill a form, redact, scrub ---
Using.resource(DocumentEditor.open("form.pdf")): ed =>
  ed.setFormField("name", "Jane Doe")
    .setFormField("agree", true)
    .addRedaction(0, BBox(72, 700, 272, 720))
  val redacted = ed.applyRedactionsDestructive()
  println(s"redacted ${redacted.regionsApplied} regions")
  ed.scrubMetadata().saveTo(java.nio.file.Path.of("output.pdf"))

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, Dart, R, Julia, Zig, Clojure, Objective-C, and Elixir.

Next Steps