Skip to main content

Crate stet_pdf_reader

Crate stet_pdf_reader 

Source
Expand description

PDF parser, page navigator, and content stream interpreter.

stet-pdf-reader is a self-contained PDF reader: it opens a PDF, walks its object graph, and interprets each page’s content stream into a stet_graphics::display_list::DisplayList that any downstream consumer (rasterizer, PDF writer, custom output device) can render.

The crate intentionally has no dependency on stet-core — it uses only stet-fonts (font parsing) and stet-graphics (display list and ICC types), so it can be used as a standalone PDF parser/renderer without pulling in the PostScript interpreter.

§Quick start

use stet_pdf_reader::PdfDocument;

let data = std::fs::read("document.pdf")?;
let doc = PdfDocument::from_bytes(&data)?;

for page in 0..doc.page_count() {
    let display_list = doc.render_page(page, 150.0)?;
    // …consume the display list (rasterize, convert, inspect, etc.)
}

With the default render feature enabled, PdfDocument::render_page_to_rgba skips the display-list-handling boilerplate and produces RGBA pixels directly via stet-render.

§Encrypted PDFs

from_bytes / from_bytes_with_icc try the empty password. If the file uses a non-empty user password they return PdfError::PasswordRequired; the caller can then prompt the user and retry with PdfDocument::from_bytes_with_password:

use stet_pdf_reader::{PdfDocument, PdfError};
use stet_graphics::icc::IccCache;

let data = std::fs::read("encrypted.pdf")?;
let doc = match PdfDocument::from_bytes(&data) {
    Ok(doc) => doc,
    Err(PdfError::PasswordRequired) => {
        let pw = prompt_user_for_password();
        PdfDocument::from_bytes_with_password(&data, IccCache::new(), pw.as_bytes())?
    }
    Err(e) => return Err(e.into()),
};

RC4 (40/128-bit), AES-128, and AES-256 (R=5/6) are all supported.

§Structural API

In addition to rendering, PdfDocument exposes typed, read-only access to a document’s structural content — for indexers, accessibility tools, link extractors, format converters, and other consumers that want to inspect a PDF rather than display it.

Every accessor parses lazily on first call and caches its result; a document the caller only renders pays nothing for the structural API surface.

use stet_pdf_reader::PdfDocument;

let data = std::fs::read("document.pdf")?;
let doc = PdfDocument::from_bytes(&data)?;

// Document metadata (Info dict + XMP).
let m = doc.metadata();
println!("Title:    {:?}", m.title);
println!("Author:   {:?}", m.author);
println!("Producer: {:?}", m.producer);

// Outline / bookmarks.
for item in doc.outline() {
    println!("- {} ({} children)", item.title, item.children.len());
}

// Annotations on page 1.
for annot in doc.page_annotations(0)? {
    println!("{:?} at {:?}", annot.kind, annot.rect);
}

// AcroForm field tree.
if let Some(form) = doc.form() {
    for field in &form.fields {
        println!("{}: {:?}", field.name, field.value);
    }
}

// Embedded file attachments.
for (name, file) in doc.embedded_files() {
    let bytes = doc.embedded_file_bytes(name)?;
    println!("{name} ({} bytes, {:?})", bytes.len(), file.mime_type);
}

// Optional Content (layers).
for layer in doc.layers() {
    println!("layer {} {:?} default_visible={}",
        layer.ocg_id, layer.name, layer.default_visible);
}

// Recoverable parse problems (cycles, dropped entries, etc.).
for w in doc.parse_warnings().iter() {
    eprintln!("[{:?}] {:?}: {}", w.severity, w.phase, w.message);
}

Full accessor list, each cached after first call:

Walkers that recurse over potentially-cyclic structures (outline tree, name trees, form-field tree) bound traversal with a visited-set and a depth cap; truncations are surfaced via parse_warnings so a missing branch is never silent.

For a longer-form reference with one focused example per accessor, see the PDF Reader API guide in the repository. The Optional Content / layer surface (Layer, Configuration, LayerSet, OcgVisibility, RenderIntent) has its own reference at docs/PDF-LAYERS.md.

§Acknowledgements

JPEG 2000, JBIG2, and CCITT-Fax stream decoding use the hayro-jpeg2000, hayro-jbig2, and hayro-ccitt crates from the hayro PDF renderer by Laurenz Stampfl. Big thanks to the hayro project for factoring those decoders out as reusable crates — stet-pdf-reader would not cover the full PDF stream-filter surface without them.

Re-exports§

pub use annotations::Annotation;
pub use annotations::AnnotationColor;
pub use annotations::AnnotationDate;
pub use annotations::AnnotationFlags;
pub use annotations::AnnotationKind;
pub use annotations::AnnotationKindData;
pub use annotations::Border;
pub use annotations::CaretAnnotation;
pub use annotations::FileAttachmentAnnotation;
pub use annotations::FreeTextAnnotation;
pub use annotations::InkAnnotation;
pub use annotations::LineAnnotation;
pub use annotations::LinkAnnotation;
pub use annotations::MarkupAnnotation;
pub use annotations::PolygonAnnotation;
pub use annotations::PopupAnnotation;
pub use annotations::ShapeAnnotation;
pub use annotations::StampAnnotation;
pub use annotations::TextAnnotation;
pub use destination::Action;
pub use destination::Destination;
pub use destination::ViewSpec;
pub use diagnostics::LocationHint;
pub use diagnostics::ParsePhase;
pub use diagnostics::ParseWarning;
pub use diagnostics::Severity;
pub use diagnostics::WarningSink;
pub use embedded_files::AfRelationship;
pub use embedded_files::EmbeddedFile;
pub use error::PdfError;
pub use form_fields::ButtonField;
pub use form_fields::ButtonType;
pub use form_fields::ChoiceField;
pub use form_fields::ChoiceOption;
pub use form_fields::FieldFlags;
pub use form_fields::FieldKind;
pub use form_fields::FieldValue;
pub use form_fields::FormCatalog;
pub use form_fields::FormField;
pub use form_fields::SigFlags;
pub use form_fields::SignatureField;
pub use form_fields::TextField;
pub use layers::AutoStateEvent;
pub use layers::AutoStateRule;
pub use layers::BaseState;
pub use layers::Configuration;
pub use layers::CreatorInfo;
pub use layers::ExportUsage;
pub use layers::LanguageUsage;
pub use layers::Layer;
pub use layers::LayerIntent;
pub use layers::LayerTree;
pub use layers::LayerTreeNode;
pub use layers::LayerUsage;
pub use layers::ListMode;
pub use layers::PageElementSubtype;
pub use layers::PrintUsage;
pub use layers::RenderIntent;
pub use layers::UsageState;
pub use layers::UserUsage;
pub use layers::ViewUsage;
pub use layers::ZoomUsage;
pub use metadata::DocumentMetadata;
pub use metadata::PdfDate;
pub use metadata::TrappedFlag;
pub use objects::PdfDict;
pub use objects::PdfObj;
pub use outline::OutlineItem;
pub use outline::OutlineStyle;
pub use page_boxes::PageBoxes;
pub use page_tree::PageInfo;
pub use viewer_prefs::Duplex;
pub use viewer_prefs::PageLayout;
pub use viewer_prefs::PageMode;
pub use viewer_prefs::PrintScaling;
pub use viewer_prefs::ReadingDirection;
pub use viewer_prefs::ViewerPreferences;

Modules§

annotations
Typed PDF annotations (links, sticky notes, highlights, stamps, callouts, attachments, etc.).
content
PDF content stream interpreter.
crypto
PDF encryption: Standard security handler (RC4 + AES-128/256).
destination
Typed PDF destinations and actions.
diagnostics
Parse-time diagnostics — non-fatal warnings the structural parsers emit when they encounter recoverable malformations.
embedded_files
PDF embedded files (file attachments).
error
PDF parsing error types.
filters
Stream decode filter chain for PDF streams.
form_fields
PDF interactive form fields (AcroForm).
layers
PDF Optional Content (layers).
lexer
PDF tokenizer.
metadata
Document-level metadata: the Info dict and the XMP metadata stream.
name_tree
PDF name tree traversal.
objects
PDF object model for reading.
outline
Document outlines (bookmarks).
page_boxes
Per-page geometry: the five PDF page boxes plus rotation, user unit, and presentation hints.
page_tree
PDF page tree traversal with attribute inheritance.
resolver
Indirect object resolution with lazy caching and stream decompression.
resources
PDF resource lookup helpers.
viewer_prefs
PDF viewer preferences from the catalog’s /ViewerPreferences dict (and the catalog-level /PageLayout and /PageMode entries that travel with them).
xref
PDF cross-reference table and trailer parsing.

Structs§

LayerSet
Per-render override of OCG visibility.
PdfDocument
A parsed PDF document.

Enums§

MembershipPolicy
/P policy on an OCMD.
OcgVisibility
Visibility predicate for an DisplayElement::OcgGroup.
VisibilityExpr
Boolean visibility expression from an OCMD /VE array.

Type Aliases§

FontProvider
Font data provider: maps a font file name (e.g. “NimbusSans-Regular”) to raw .t1 bytes.