Expand description
§exprim
A read-only, memory-bounded, concurrent PDF engine: open a document, extract its text, and rasterize its pages.
Every page renders against an immutable document snapshot; all execution state and scratch memory belong to the thread that renders the page. A malformed page degrades to a typed error for that page, never a panic across the API.
§Quick start
Open a document from bytes, read a page’s text, and export the page as a PNG:
use std::sync::Arc;
use exprim::{ExportOptions, RenderSession};
// Any PDF in memory; `std::fs::read("document.pdf")?` is the usual source.
let bytes: Arc<[u8]> = one_page_pdf().into();
let session = RenderSession::open(bytes, None)?;
assert_eq!(session.page_count(), 1);
// Pages are numbered from zero.
let text = exprim::page_text(&session, 0)?;
assert!(text.contains("Hello"));
// Render and encode in one call: PNG file bytes at 150 DPI.
let png = session.export_page(0, &ExportOptions::png(150.0))?;
assert!(png.starts_with(b"\x89PNG"));§What is where
| To do this | Use |
|---|---|
| Open a document | RenderSession::open |
| Check a file before opening: encrypted, damaged, per-page health | examine_document |
| Page count, page boxes and rotation | RenderSession::page_count, RenderSession::page_geometry |
| A page as a PNG or JPEG | RenderSession::export_page, ExportOptions |
| A page as raw pixels, at any size or cropped | RenderSession::compile, RenderSession::render, RasterProduct |
| Text of a page | page_text, has_text_layer |
| Words with their positions | positioned_words |
| Whether a page needs text recognition | page_text_evidence |
| Bookmarks, title and author | extract_outline, extract_metadata |
| Encode pixels you already rendered | encode_plane |
| Metrics of a font file | read_face_metrics |
Print (feature print) | the print module |
§Pages, units and pixels
- Page indices are zero-based everywhere at the crate root. (Page ranges
in the
printmodule are one-based, because users type them.) - Page geometry is in PDF points, 1/72 inch, with the origin at the bottom
left. “The page” means its crop box with
/Rotateapplied, which is what a viewer shows;PageGeometrycarries the other boxes. - A resolution in DPI maps points to pixels: a US Letter page (612 x 792
points) is 1275 x 1650 pixels at 150 DPI.
RenderSession::page_pixel_sizedoes this arithmetic. - Rasters are 8-bit RGB or grayscale, rows top to bottom, composited over white, with the page’s annotations drawn.
§Rendering more than once
RenderSession::export_page is the whole job in one call. To render a
page several times (thumbnail and full size, tiles, a zoomed region),
compile it once and render the handle:
use exprim::{RasterProduct, RenderSession};
let session = RenderSession::open(bytes, None)?;
let page = session.compile(0)?;
let thumbnail = session.render(&page, &RasterProduct::gray8(120, 170))?;
let full = session.render(&page, &RasterProduct::rgb8(1240, 1754))?;A RasterProduct names the output size, the pixel format and an
optional DeviceCrop. The same product gives the same pixels every
time, on every thread.
§Errors and damaged files
Every fallible call returns ReadError. Opening fails only when the
file as a whole cannot be read; a damaged cross-reference table is rebuilt
by scanning. After that, failures are per page: a page whose content
cannot be interpreted or rendered returns an error for that page, and the
others still work. Bookmark and metadata readers skip what they cannot
resolve and return what remains. A panic inside the renderer is caught and
reported as ReadError::Render.
§Threads and memory
A RenderSession can be shared between threads. Calls run on the thread
that makes them, so rendering pages in parallel is a matter of calling
from several threads; a rayon iterator over page indices works. Each
thread keeps its own scratch buffers and reuses them from page to page.
Memory is bounded in three places: a session keeps at most eight compiled
pages (see RenderSession::open_with_cache_capacity), an export refuses
images over DEFAULT_MAX_EXPORT_PIXELS unless told otherwise, and the
parser and renderer apply fixed limits to what one document or page may
allocate. Long work can be stopped with a CancellationToken.
§Encrypted documents
Pass the password to RenderSession::open. examine_document reports
whether a file is encrypted and whether it needs a password, without
failing.
§Features
print: office printing (paper, margins, scaling, N-up, booklets, duplex, page ranges; CUPS and Windows spooling) in theprintmodule.profiling: per-stage timers for benchmark tooling.
§Stability
The crate root is the supported API. The engine’s layers (parser, content interpreter, fonts, rasterizer) are public modules so that tools built on them do not need a fork, but they are hidden from this documentation and carry no semver promise before 1.0: a minor release may change them.
Modules§
- print
print - Office printing over the exprim reader.
Structs§
- Analysis
Target - The raster a pipeline inspects to decide how to process a page. Part of a
PageOutputPlan. - Base
Target - The main raster of a page in a
PageOutputPlan. - Cancellation
Token - Cooperative cancellation token. The renderer token stays private to this crate while page jobs can cheaply clone, cancel, and checkpoint it.
- Compiled
Document Page - An immutable compiled page whose renderer representation remains private.
- Decode
Reference - A whole-page raster size whose image footprints set the lowest resolution a product’s images are decoded at.
- Device
Crop - A rectangle cut out of a full-page raster, in that raster’s pixels.
- Direct
Scan Image - The embedded JPEG of a page that is nothing but one full-page image, as stored in the PDF.
- Document
Intake - Read-only facts collected before a document enters the processing path.
- Document
Metadata - Credible document identity carried by the source PDF’s Info dictionary.
- Export
Options - How to export one page.
- FaceB
Box - A font’s global bounding box in design units (
head’sxMin..yMax). - Face
Metrics - The subset of a face’s metadata a PDF font descriptor needs.
- Gray
Surface - An owned 8-bit grayscale raster: one byte per pixel, rows top to bottom. Cloning shares the pixel buffer.
- Native
Text Word - A word and its exact bounding box in source-render pixel space.
- OcrTarget
- The raster of a page handed to text recognition. Part of a
PageOutputPlan. - Owned
Bookmark Node - One resolved source-outline node. Page indexes are zero-based source space.
- Page
Geometry - Visible page geometry in PDF user space.
- Page
Output Plan - Every raster a processing pipeline wants from one page, rendered together
by
RenderSession::render_output_plan. - Page
Raster Products - The rasters
RenderSession::render_output_planproduced for one page. - Page
Text Evidence - Native text and image evidence used to decide whether OCR is necessary.
- Preserved
Jbig2 Smask - Source-preserving foreground text plane for a conservatively qualified MRC
page. Encoded bytes stay authoritative;
working_coverageis a separate area-averaged opacity plane on the target grid, used only by processing and analysis. - Raster
Product - One final-size raster requested by a document processing pipeline.
- Region
Target - One extra region of a page in a
PageOutputPlan, usually a crop at its own resolution. - Render
Session - Per-document immutable renderer state.
- Rendered
Region - One rendered region of a
PageOutputPlan, with the target it was rendered for. - RgbSurface
- An owned 8-bit RGB raster: three bytes per pixel, rows top to bottom, no alpha. Cloning shares the pixel buffer.
- Session
Options - Memory bounds of one
RenderSession. Every open document has its own caches, so a host that keeps many documents open divides its allowance among them here; the defaults suit one document at a time. A smaller bound costs recompiling, decoding or rasterizing again, never different output.
Enums§
- Compile
Status - exprim’s own form of the renderer’s per-page compile health.
- Export
Color - Colour of the exported raster.
- Gray
Suitability - Whether rendering a page straight to grayscale matches rendering it in colour and converting afterwards.
- Image
Format - Encoded container for an exported page.
- Jbig2
Stencil Polarity - Which decoded JBIG2 sample value the output stencil must paint. An image
/SMaskuses 1 as opaque, while/ImageMaskuses 0 as paint, so the usual source/Decode [0 1]becomes an output stencil/Decode [1 0]. - Page
Content Kind - OCR-relevant page classification derived from one semantic compilation.
- Raster
Format - Pixel format requested from a compiled document page.
- Raster
Plane - Host raster owned by this API. Renderer surface types do not leave this crate.
- Read
Error - Errors at the document API. Renderer error types do not escape.
Constants§
- DEFAULT_
EXPORT_ DPI - Resolution used when a caller does not state one. Matches the
pdfr renderdefault so the two entry points agree. - DEFAULT_
MAX_ EXPORT_ PIXELS - Default ceiling on
width * heightfor one exported page, about 100 megapixels — a 300 DPI A0 sheet still fits, while a malformed or hostile/MediaBoxcannot talk the caller into a multi-gigabyte allocation.
Functions§
- encode_
plane - Encode an already-rendered plane.
- examine_
document - Examine document bytes without exposing renderer report types.
- extract_
metadata - Extract
/Titleand/Authorwithout rendering a page. - extract_
outline - Extract the source outline without rasterizing any page.
- has_
text_ layer - Whether
page(zero-based) has any extractable text. - page_
text - The text of
page(zero-based) in reading order. - page_
text_ evidence - Compile a page once and return its OCR routing evidence.
- pixel_
size_ for_ dpi - Pixel size a page occupies at
dpi, using the page’s display extent so that a page rotated by an odd multiple of 90 degrees reports the swapped axes a viewer would show. - positioned_
words - The words of
pagewith their bounding boxes, mapped onto a rendering of the page that issource_widthxsource_heightpixels. - read_
face_ metrics - Read metadata for face
indexof a font file.