Offline OCR Model Management
PDF Oxide’s OCR uses ONNX detection + recognition models that live in a local cache directory. For Docker builds, CI, and air-gapped / offline deployments you want those models present before the first OCR call — never fetched at request time. PDF Oxide gives you three primitives for that:
prefetch_models— download the shared detector plus per-language recognition model + dictionary into the model cache dir (build-time provisioning).model_manifest— a network-free JSON manifest of every model file and its source URL, for mirroring/verification on an air-gapped host.prefetch_available— whether this build can actually download (compiled with theocrfeature).
The cache dir is $PDF_OXIDE_MODEL_DIR if set, otherwise the platform cache (~/.cache/pdf_oxide/models on Linux). Once the files are there, OCR runs fully offline.
Binding coverage. Model provisioning is exposed in Rust, Go, C#, and Swift.
model_manifestandprefetch_availableare also exposed in WASM/JavaScript (whereprefetchAvailable()always returnsfalse— WASM has no network fetcher, so you provision host-side using the manifest). The Python and Node N-API bindings do not expose these in v0.3.69.
How do I prefetch OCR models for offline use?
prefetch_models takes comma-separated language codes (empty → English), downloads the shared detector + each language’s recognition model and dictionary into the cache dir, and returns that directory path. It is idempotent — files that already exist are skipped.
Rust
use pdf_oxide::extractors::auto::{AutoExtractor, OcrLanguage};
fn main() -> pdf_oxide::Result<()> {
// AutoExtractor::prefetch_models(langs: &[OcrLanguage])
// -> Result<std::path::PathBuf>
let dir = AutoExtractor::prefetch_models(&[
OcrLanguage::English,
OcrLanguage::Chinese,
OcrLanguage::Arabic,
])?;
println!("models cached in {}", dir.display());
// One-shot English (the common case):
let _ = AutoExtractor::prefetch_models_default()?;
Ok(())
}
Go
package main
import (
"fmt"
"log"
pdfoxide "github.com/yfedoseev/pdf_oxide/go"
)
func main() {
if !pdfoxide.PrefetchAvailable() {
log.Fatal("this build cannot download models (built without the ocr feature)")
}
// func PrefetchModels(langs ...string) (string, error)
dir, err := pdfoxide.PrefetchModels("english", "chinese", "arabic")
if err != nil {
log.Fatal(err)
}
fmt.Println("models cached in", dir)
}
C#
using System;
using PdfOxide.Core;
if (!PdfDocument.PrefetchAvailable())
throw new InvalidOperationException("built without the ocr feature; cannot download models");
// static string PdfDocument.PrefetchModels(params string[] languages)
string dir = PdfDocument.PrefetchModels("english", "chinese", "arabic");
Console.WriteLine($"models cached in {dir}");
Swift
import PdfOxide
guard PdfOxide.prefetchAvailable() == 1 else {
fatalError("built without the ocr feature; cannot download models")
}
// static func prefetchModels(languagesCsv: String) throws -> String
let dir = try PdfOxide.prefetchModels(languagesCsv: "english,chinese,arabic")
print("models cached in \(dir)")
PHP
use PdfOxide\Pdf;
if (!Pdf::prefetchAvailable()) {
throw new RuntimeException('built without the ocr feature; cannot download models');
}
// static Pdf::prefetchModels(array $languages): string
$dir = Pdf::prefetchModels(['english', 'chinese', 'arabic']);
echo "models cached in {$dir}\n";
Ruby
require 'pdf_oxide'
unless PdfOxide::Pdf.prefetch_available?
raise 'built without the ocr feature; cannot download models'
end
# PdfOxide::Pdf.prefetch_models(languages) -> String (cache dir)
dir = PdfOxide::Pdf.prefetch_models(%w[english chinese arabic])
puts "models cached in #{dir}"
C++
#include <pdf_oxide/pdf_oxide.hpp>
#include <iostream>
if (pdf_oxide::prefetch_available() == 0)
throw std::runtime_error("built without the ocr feature; cannot download models");
// std::string pdf_oxide::prefetch_models(const std::string& languages_csv)
auto dir = pdf_oxide::prefetch_models("english,chinese,arabic");
std::cout << "models cached in " << dir << "\n";
Dart
import 'package:pdf_oxide/pdf_oxide.dart' as pdf_oxide;
if (pdf_oxide.prefetchAvailable() == 0) {
throw StateError('built without the ocr feature; cannot download models');
}
// String prefetchModels(String languagesCsv)
final dir = pdf_oxide.prefetchModels('english,chinese,arabic');
print('models cached in $dir');
R
library(pdfoxide)
if (pdf_prefetch_available() == 0)
stop("built without the ocr feature; cannot download models")
# pdf_prefetch_models(languages_csv = NULL) -> cache directory path
dir <- pdf_prefetch_models("english,chinese,arabic")
cat("models cached in", dir, "\n")
Julia
using PdfOxide
prefetch_available() != 0 || error("built without the ocr feature; cannot download models")
# prefetch_models(languages_csv::AbstractString) -> cache directory path
dir = prefetch_models("english,chinese,arabic")
println("models cached in ", dir)
Zig
const pdf_oxide = @import("pdf_oxide");
const a = std.heap.page_allocator;
if (pdf_oxide.prefetchAvailable() == 0) return error.OcrFeatureMissing;
// prefetchModels(alloc, languages_csv) -> []u8 (cache dir; caller frees)
const dir = try pdf_oxide.prefetchModels(a, "english,chinese,arabic");
defer a.free(dir);
std.debug.print("models cached in {s}\n", .{dir});
Objective-C
#import "POXPdfOxide.h"
NSError *err = nil;
if ([POXModels prefetchAvailable] <= 0) {
@throw [NSException exceptionWithName:@"PdfOxide" reason:@"no ocr feature" userInfo:nil];
}
// + prefetchModels:error: returns a status JSON (nil on error)
NSString *status = [POXModels prefetchModels:@"english,chinese,arabic" error:&err];
NSLog(@"prefetch status: %@", status);
Elixir
unless PdfOxide.prefetch_available() != 0 do
raise "built without the ocr feature; cannot download models"
end
# prefetch_models(languages_csv \\ "") -> JSON status string
status = PdfOxide.prefetch_models("english,chinese,arabic")
IO.puts("prefetch status: #{status}")
Language codes
prefetch_models accepts these codes (unknown codes are skipped; empty input defaults to English):
english, chinese, chinese_cht, japan, korean, arabic, cyrillic, latin, devanagari, ta (Tamil), te (Telugu), ka (Kannada).
How do I provision models on an air-gapped host?
On a machine with no internet (or a WASM target with no fetcher), you can’t call prefetch_models. Instead, read model_manifest — a static, network-free JSON listing of every model file and its upstream URL — mirror those URLs through your artifact store, and drop the files into $PDF_OXIDE_MODEL_DIR.
Rust
use pdf_oxide::extractors::auto::AutoExtractor;
fn main() {
// AutoExtractor::model_manifest() -> String (JSON, never errors)
let manifest = AutoExtractor::model_manifest();
println!("{manifest}");
}
Go
// func ModelManifest() string (JSON, never errors)
fmt.Println(pdfoxide.ModelManifest())
C#
// static string PdfDocument.ModelManifest()
Console.WriteLine(PdfDocument.ModelManifest());
Swift
// static func modelManifest() -> String (JSON)
print(PdfOxide.modelManifest())
JavaScript (WASM)
import init, { modelManifest, prefetchAvailable } from "pdf-oxide-wasm";
await init();
// prefetchAvailable() is always false in WASM — provision host-side.
console.log("can download here?", prefetchAvailable()); // false
console.log(modelManifest()); // JSON manifest
PHP
use PdfOxide\FFI\FunctionBindings;
// (new FunctionBindings())->pdfOxideModelManifest(): string (JSON, never errors)
$manifest = (new FunctionBindings())->pdfOxideModelManifest();
echo $manifest, "\n";
C++
#include <pdf_oxide/pdf_oxide.hpp>
#include <iostream>
// std::string pdf_oxide::model_manifest() (JSON, never errors)
std::cout << pdf_oxide::model_manifest() << "\n";
Dart
import 'package:pdf_oxide/pdf_oxide.dart' as pdf_oxide;
// String modelManifest() (JSON)
print(pdf_oxide.modelManifest());
R
library(pdfoxide)
# pdf_model_manifest() -> JSON string
cat(pdf_model_manifest(), "\n")
Julia
using PdfOxide
# model_manifest() -> JSON String
println(model_manifest())
Zig
const pdf_oxide = @import("pdf_oxide");
const a = std.heap.page_allocator;
// modelManifest(alloc) -> []u8 (JSON; caller frees)
const manifest = try pdf_oxide.modelManifest(a);
defer a.free(manifest);
std.debug.print("{s}\n", .{manifest});
Objective-C
#import "POXPdfOxide.h"
NSError *err = nil;
// + manifestWithError: -> JSON string (nil on error)
NSString *manifest = [POXModels manifestWithError:&err];
NSLog(@"%@", manifest);
Elixir
# model_manifest() -> JSON string
IO.puts(PdfOxide.model_manifest())
What does the manifest look like?
{
"detector": {
"file": "det.onnx",
"url": "https://.../det.onnx"
},
"languages": [
{
"language": "english",
"rec_file": "rec.onnx",
"dict_file": "en_dict.txt",
"rec_url": "https://.../rec.onnx",
"dict_url": "https://.../en_dict.txt"
}
],
"note": "Hebrew has no upstream PaddleOCR recognition model; the loader is ready if one is provided."
}
Mirror detector.url and each language’s rec_url / dict_url, then place det.onnx plus each rec_file / dict_file into your PDF_OXIDE_MODEL_DIR. After that, OCR runs with zero network access.
Does this build support downloading models?
prefetch_available reports whether the native library was compiled with the ocr feature (which pulls in the HTTP fetcher). When it returns false, prefetch_models still creates the cache dir but performs no download — so check it before relying on a fetch.
Rust
use pdf_oxide::extractors::auto::AutoExtractor;
// AutoExtractor::prefetch_available() -> bool
if AutoExtractor::prefetch_available() {
let _ = AutoExtractor::prefetch_models_default();
} else {
eprintln!("OCR feature not compiled in — provision via model_manifest()");
}
Go — pdfoxide.PrefetchAvailable() bool
C# — PdfDocument.PrefetchAvailable() -> bool
Swift — PdfOxide.prefetchAvailable() -> Int32 (1 == yes)
Dockerfile example
Bake the models into the image at build time so the running container never reaches out:
FROM rust:1 AS models
WORKDIR /app
COPY . .
# Build the CLI / your binary with the `ocr` feature, then prefetch.
ENV PDF_OXIDE_MODEL_DIR=/models
RUN cargo run --features ocr --bin prefetch -- english chinese
FROM debian:stable-slim
ENV PDF_OXIDE_MODEL_DIR=/models
COPY --from=models /models /models
# OCR now runs fully offline against /models
Global engine configuration
Two process-global setters tune the extraction engine. Both are exposed across the C-ABI bindings, both return the previous value, and both have no error channel (they cannot fail). Because they are process-global, setting them on one thread affects every concurrent extraction.
How do I raise the content-stream operator cap?
PDF Oxide caps content-stream operators per stream (default 1,000,000) to bound the cost of adversarial inputs. Large legitimate technical PDFs (textbooks, ISO standards) can exceed that. set_max_ops_per_stream raises (or lowers) the cap and returns the previous one.
Rust
// pdf_oxide::content::parser::set_max_ops_per_stream(limit: Option<usize>)
// -> Option<usize> (None restores the 1,000,000 default)
use pdf_oxide::content::parser::set_max_ops_per_stream;
let prev = set_max_ops_per_stream(Some(5_000_000));
// ... extract a huge trusted PDF ...
set_max_ops_per_stream(prev); // restore
Go
// func SetMaxOpsPerStream(limit int64) int64 (returns previous cap)
prev := pdfoxide.SetMaxOpsPerStream(5_000_000)
defer pdfoxide.SetMaxOpsPerStream(prev)
C#
// static long CAbi.SetMaxOpsPerStream(long limit) (returns previous cap)
long prev = PdfOxide.Core.CAbi.SetMaxOpsPerStream(5_000_000);
try { /* extract huge trusted PDF */ }
finally { PdfOxide.Core.CAbi.SetMaxOpsPerStream(prev); }
Swift
// static func setMaxOpsPerStream(_ limit: Int64) -> Int64
let prev = PdfOxide.setMaxOpsPerStream(5_000_000)
defer { _ = PdfOxide.setMaxOpsPerStream(prev) }
PHP
use PdfOxide\FFI\FunctionBindings;
$bindings = new FunctionBindings();
// pdfOxideSetMaxOpsPerStream(int $limit): int (returns previous cap; -1 = default was active)
$prev = $bindings->pdfOxideSetMaxOpsPerStream(5_000_000);
try { /* extract huge trusted PDF */ }
finally { $bindings->pdfOxideSetMaxOpsPerStream($prev); }
Ruby
require 'pdf_oxide'
# PdfOxide.set_max_ops_per_stream(limit) -> previous cap (-1 = default was active)
prev = PdfOxide.set_max_ops_per_stream(5_000_000)
begin
# ... extract a huge trusted PDF ...
ensure
PdfOxide.set_max_ops_per_stream(prev)
end
C++
#include <pdf_oxide/pdf_oxide.hpp>
// std::int64_t pdf_oxide::set_max_ops_per_stream(std::int64_t limit) -> previous cap
auto prev = pdf_oxide::set_max_ops_per_stream(5'000'000);
// ... extract a huge trusted PDF ...
pdf_oxide::set_max_ops_per_stream(prev); // restore
Dart
import 'package:pdf_oxide/pdf_oxide.dart' as pdf_oxide;
// int setMaxOpsPerStream(int limit) -> previous cap
final prev = pdf_oxide.setMaxOpsPerStream(5000000);
// ... extract a huge trusted PDF ...
pdf_oxide.setMaxOpsPerStream(prev); // restore
R
library(pdfoxide)
# pdf_set_max_ops_per_stream(limit) -> previous cap (negative limit restores default)
prev <- pdf_set_max_ops_per_stream(5000000)
# ... extract a huge trusted PDF ...
pdf_set_max_ops_per_stream(prev) # restore
Julia
using PdfOxide
# set_max_ops_per_stream(limit::Integer) -> previous cap
prev = set_max_ops_per_stream(5_000_000)
# ... extract a huge trusted PDF ...
set_max_ops_per_stream(prev) # restore
Zig
const pdf_oxide = @import("pdf_oxide");
// setMaxOpsPerStream(limit: i64) i64 (returns previous cap)
const prev = pdf_oxide.setMaxOpsPerStream(5_000_000);
// ... extract a huge trusted PDF ...
_ = pdf_oxide.setMaxOpsPerStream(prev); // restore
Objective-C
#import "POXPdfOxide.h"
// + setMaxOpsPerStream: -> previous cap
int64_t prev = [POXConfig setMaxOpsPerStream:5000000];
// ... extract a huge trusted PDF ...
[POXConfig setMaxOpsPerStream:prev]; // restore
Elixir
# set_max_ops_per_stream(limit) -> previous cap (-1 = default was active)
prev = PdfOxide.set_max_ops_per_stream(5_000_000)
# ... extract a huge trusted PDF ...
PdfOxide.set_max_ops_per_stream(prev)
At the C ABI, pdf_oxide_set_max_ops_per_stream(limit) treats a negative limit as “restore the default” and returns -1 when the default was previously active.
How do I preserve unmapped (U+FFFD) glyphs?
By default, the high-level accessors (extract_text / extract_words / extract_spans) filter glyphs that have no Unicode mapping (they would surface as U+FFFD �). On pages whose visible glyphs all map to U+FFFD — e.g. a math-symbol font like MSAM10 — that can produce empty output. set_preserve_unmapped_glyphs(true) makes those accessors keep the replacement characters so you can see and post-process them; it returns the previous setting.
Rust
// pdf_oxide::extractors::text::set_preserve_unmapped_glyphs(preserve: bool)
// -> bool (returns previous value)
use pdf_oxide::extractors::text::set_preserve_unmapped_glyphs;
let prev = set_preserve_unmapped_glyphs(true);
// ... extract a math-heavy PDF; U+FFFD glyphs are now kept ...
set_preserve_unmapped_glyphs(prev);
Go
// func SetPreserveUnmappedGlyphs(preserve int) int (1 = preserve; returns previous)
prev := pdfoxide.SetPreserveUnmappedGlyphs(1)
defer pdfoxide.SetPreserveUnmappedGlyphs(prev)
C#
// static int CAbi.SetPreserveUnmappedGlyphs(bool preserve) (returns previous, 0/1)
int prev = PdfOxide.Core.CAbi.SetPreserveUnmappedGlyphs(true);
try { /* extract math-heavy PDF */ }
finally { PdfOxide.Core.CAbi.SetPreserveUnmappedGlyphs(prev != 0); }
Swift
// static func setPreserveUnmappedGlyphs(_ preserve: Int32) -> Int32
let prev = PdfOxide.setPreserveUnmappedGlyphs(1)
defer { _ = PdfOxide.setPreserveUnmappedGlyphs(prev) }
PHP
use PdfOxide\FFI\FunctionBindings;
$bindings = new FunctionBindings();
// pdfOxideSetPreserveUnmappedGlyphs(int $preserve): int (1 = preserve; returns previous, 0/1)
$prev = $bindings->pdfOxideSetPreserveUnmappedGlyphs(1);
try { /* extract math-heavy PDF */ }
finally { $bindings->pdfOxideSetPreserveUnmappedGlyphs($prev); }
Ruby
require 'pdf_oxide'
# PdfOxide.set_preserve_unmapped_glyphs(preserve) -> previous value (0 or 1)
prev = PdfOxide.set_preserve_unmapped_glyphs(true)
begin
# ... extract a math-heavy PDF; U+FFFD glyphs are now kept ...
ensure
PdfOxide.set_preserve_unmapped_glyphs(prev)
end
C++
#include <pdf_oxide/pdf_oxide.hpp>
// int pdf_oxide::set_preserve_unmapped_glyphs(int preserve) -> previous value
int prev = pdf_oxide::set_preserve_unmapped_glyphs(1);
// ... extract a math-heavy PDF; U+FFFD glyphs are now kept ...
pdf_oxide::set_preserve_unmapped_glyphs(prev); // restore
Dart
import 'package:pdf_oxide/pdf_oxide.dart' as pdf_oxide;
// int setPreserveUnmappedGlyphs(int preserve) -> previous value
final prev = pdf_oxide.setPreserveUnmappedGlyphs(1);
// ... extract a math-heavy PDF; U+FFFD glyphs are now kept ...
pdf_oxide.setPreserveUnmappedGlyphs(prev); // restore
R
library(pdfoxide)
# pdf_set_preserve_unmapped_glyphs(preserve) -> previous value (0 or 1)
prev <- pdf_set_preserve_unmapped_glyphs(1L)
# ... extract a math-heavy PDF; U+FFFD glyphs are now kept ...
pdf_set_preserve_unmapped_glyphs(prev) # restore
Julia
using PdfOxide
# set_preserve_unmapped_glyphs(preserve::Integer) -> previous value (0 or 1)
prev = set_preserve_unmapped_glyphs(1)
# ... extract a math-heavy PDF; U+FFFD glyphs are now kept ...
set_preserve_unmapped_glyphs(prev) # restore
Zig
const pdf_oxide = @import("pdf_oxide");
// setPreserveUnmappedGlyphs(preserve: bool) i32 (returns previous value)
const prev = pdf_oxide.setPreserveUnmappedGlyphs(true);
// ... extract a math-heavy PDF; U+FFFD glyphs are now kept ...
_ = pdf_oxide.setPreserveUnmappedGlyphs(prev != 0); // restore
Objective-C
#import "POXPdfOxide.h"
// + setPreserveUnmappedGlyphs: -> previous value (0 or 1)
int32_t prev = [POXConfig setPreserveUnmappedGlyphs:1];
// ... extract a math-heavy PDF; U+FFFD glyphs are now kept ...
[POXConfig setPreserveUnmappedGlyphs:prev]; // restore
Elixir
# set_preserve_unmapped_glyphs(preserve) -> previous value (0 or 1)
prev = PdfOxide.set_preserve_unmapped_glyphs(1)
# ... extract a math-heavy PDF; U+FFFD glyphs are now kept ...
PdfOxide.set_preserve_unmapped_glyphs(prev)
At the C ABI, pdf_oxide_set_preserve_unmapped_glyphs(preserve) takes 1 to preserve / 0 to filter and returns the previous value as 0 or 1.
FAQ
Where are OCR models stored?
In $PDF_OXIDE_MODEL_DIR if set, otherwise the platform cache (~/.cache/pdf_oxide/models on Linux). The path is also what prefetch_models returns.
Is prefetch_models safe to call repeatedly?
Yes — it is idempotent. Existing files are skipped, so it is cheap to call on every startup as a safety net.
Why does prefetch_available return false even though I called prefetch?
The build was compiled without the ocr feature, so there is no HTTP fetcher. prefetch_models still creates the cache dir but downloads nothing — provision the files out of band using model_manifest.
Do the global setters need to be reset? They are process-global and persist until changed, so restore the previous value (which every setter returns) when you only want the override for a specific document. Both setters cannot fail and have no error channel.
Related Pages
- OCR Scanned PDFs — drive OCR once the models are provisioned
- Page Classification — decide which pages actually need OCR
- Logging and Debug Output — other process-global library controls
- Extract Text from a PDF — the high-level accessors
set_preserve_unmapped_glyphsaffects