Skip to main content

Crate exprim

Crate exprim 

Source
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 thisUse
Open a documentRenderSession::open
Check a file before opening: encrypted, damaged, per-page healthexamine_document
Page count, page boxes and rotationRenderSession::page_count, RenderSession::page_geometry
A page as a PNG or JPEGRenderSession::export_page, ExportOptions
A page as raw pixels, at any size or croppedRenderSession::compile, RenderSession::render, RasterProduct
Text of a pagepage_text, has_text_layer
Words with their positionspositioned_words
Whether a page needs text recognitionpage_text_evidence
Bookmarks, title and authorextract_outline, extract_metadata
Encode pixels you already renderedencode_plane
Metrics of a font fileread_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 print module 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 /Rotate applied, which is what a viewer shows; PageGeometry carries 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_size does 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 the print module.
  • 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§

printprint
Office printing over the exprim reader.

Structs§

AnalysisTarget
The raster a pipeline inspects to decide how to process a page. Part of a PageOutputPlan.
BaseTarget
The main raster of a page in a PageOutputPlan.
CancellationToken
Cooperative cancellation token. The renderer token stays private to this crate while page jobs can cheaply clone, cancel, and checkpoint it.
CompiledDocumentPage
An immutable compiled page whose renderer representation remains private.
DecodeReference
A whole-page raster size whose image footprints set the lowest resolution a product’s images are decoded at.
DeviceCrop
A rectangle cut out of a full-page raster, in that raster’s pixels.
DirectScanImage
The embedded JPEG of a page that is nothing but one full-page image, as stored in the PDF.
DocumentIntake
Read-only facts collected before a document enters the processing path.
DocumentMetadata
Credible document identity carried by the source PDF’s Info dictionary.
ExportOptions
How to export one page.
FaceBBox
A font’s global bounding box in design units (head’s xMin..yMax).
FaceMetrics
The subset of a face’s metadata a PDF font descriptor needs.
GraySurface
An owned 8-bit grayscale raster: one byte per pixel, rows top to bottom. Cloning shares the pixel buffer.
NativeTextWord
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.
OwnedBookmarkNode
One resolved source-outline node. Page indexes are zero-based source space.
PageGeometry
Visible page geometry in PDF user space.
PageOutputPlan
Every raster a processing pipeline wants from one page, rendered together by RenderSession::render_output_plan.
PageRasterProducts
The rasters RenderSession::render_output_plan produced for one page.
PageTextEvidence
Native text and image evidence used to decide whether OCR is necessary.
PreservedJbig2Smask
Source-preserving foreground text plane for a conservatively qualified MRC page. Encoded bytes stay authoritative; working_coverage is a separate area-averaged opacity plane on the target grid, used only by processing and analysis.
RasterProduct
One final-size raster requested by a document processing pipeline.
RegionTarget
One extra region of a page in a PageOutputPlan, usually a crop at its own resolution.
RenderSession
Per-document immutable renderer state.
RenderedRegion
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.
SessionOptions
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§

CompileStatus
exprim’s own form of the renderer’s per-page compile health.
ExportColor
Colour of the exported raster.
GraySuitability
Whether rendering a page straight to grayscale matches rendering it in colour and converting afterwards.
ImageFormat
Encoded container for an exported page.
Jbig2StencilPolarity
Which decoded JBIG2 sample value the output stencil must paint. An image /SMask uses 1 as opaque, while /ImageMask uses 0 as paint, so the usual source /Decode [0 1] becomes an output stencil /Decode [1 0].
PageContentKind
OCR-relevant page classification derived from one semantic compilation.
RasterFormat
Pixel format requested from a compiled document page.
RasterPlane
Host raster owned by this API. Renderer surface types do not leave this crate.
ReadError
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 render default so the two entry points agree.
DEFAULT_MAX_EXPORT_PIXELS
Default ceiling on width * height for one exported page, about 100 megapixels — a 300 DPI A0 sheet still fits, while a malformed or hostile /MediaBox cannot 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 /Title and /Author without 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 page with their bounding boxes, mapped onto a rendering of the page that is source_width x source_height pixels.
read_face_metrics
Read metadata for face index of a font file.