Skip to main content

Crate flpdf

Crate flpdf 

Source
Expand description

flpdf is a pure-Rust toolkit for reading, inspecting, transforming, and writing PDF documents.

qpdf correspondence: crate root aggregating multiple qpdf library components and flpdf-only APIs.

The crate is organised as a few small layers that you can mix as needed:

  • Pdf is the parsed-but-lazy document handle. Pdf::open reads the trailer and cross-reference table, then resolves objects on demand via canonical ObjectHandle resolution. Pdf::uninitialized represents qpdf’s default-constructed document before any input source has been processed.
  • ObjectHandle and ObjectRef are the data model.
  • pages and outline_object_helper are traversal helpers built on top of Pdf. They mirror the read-only inspection surface that qpdf --show-pages and --json-key=outlines provide.
  • PdfWriter configures the one fresh full-rewrite output with qpdf-shaped settings.
  • job::QPDFJob::check owns the qpdf-compatible document-check lifecycle and warning/exit-status boundary.

§End-to-end example

use std::fs::File;
use std::io::BufReader;
use flpdf::{pages, Pdf, PdfWriter};

let file = BufReader::new(File::open("input.pdf")?);
let mut pdf = Pdf::open(file)?;

for object_ref in pages::page_refs(&mut pdf)? {
    println!("page: {object_ref}");
}

let mut writer = PdfWriter::new(&mut pdf);
writer.set_output_file("output.pdf")?;
writer.write()?;

Errors flow through the unified Error enum and the crate-level Result alias, except for the small ParseObjectRefError returned by ObjectRef::parse.

§Known limitations

  • Outline and page-label preservation. Support scope varies by operation:

    • PdfWriter output (with no page selection) preserves both destination sources — the legacy catalog /Dests dictionary and the modern /Names /Dests name tree (ISO 32000-2 §7.9.6, §12.3.2.3); deeply nested outlines (walks are iterative); all five /A action subtypes (GoTo, GoToR, URI, Launch, Named) plus their /Next chains (ISO 32000-2 §12.6.2); the /SE structure-element link (ISO 32000-2 §14.7); and the /PageLabels number-tree ranges (ISO 32000-2 §7.9.7).
    • rebuild_page_tree alone only rewrites the /Pages tree; it does NOT remap outline /Dest refs, does NOT drop /Dests entries whose targets went away, and does NOT reconstruct /PageLabels. Serializing only rebuild_page_tree’s output leaves stale destinations and label ranges pointing at pages no longer in the tree. Pair it with job::remap_outline_and_dests and (when labels matter) PageLabelDocumentHelper::labels_for_selection + PageLabelDocumentHelper::write_reconstructed_labels — the extract_pages and merge_documents pipelines assemble that combination for you.
    • merge_documents preserves outlines, both dest sources, and the trailer /Info dictionary for the PRIMARY input only (matching qpdf --pages), and reconstructs /PageLabels across every input’s selected pages.
    • extract_pages returns a new document whose serialized output is minimal and intentionally omits catalog-level navigation — /Outlines, catalog /Dests, and /Names /Dests are all dropped — as well as the source’s trailer /Info, because it builds on an empty document and copies pages rather than document-level data (matching qpdf --empty --pages). Only /PageLabels is reconstructed for the selection. Callers who need outlines, dests, or /Info preserved should use merge_documents with a single input.
  • Raw outline keys are preserved. Ordinary rewriting keeps /SE, /Dest, /A, and unknown outline dictionary keys as PDF objects rather than applying flpdf-specific validation or pruning policy.

  • flpdf --json’s pagelabels section uses qpdf JSON v2’s outer {index, label} entries and raw page-label dictionaries (/S, /P, /St). The outlines section uses qpdf JSON v2’s key layout.

Re-exports§

pub use logger::QPDFLogger;
pub use acroform_document_helper::AcroFormDocumentHelper;
pub use acroform_document_helper::AcroFormFieldInfo;
pub use annotation_object_helper::AnnotationObjectHelper;
pub use content_normalizer::normalize_content_stream;
pub use content_normalizer::ContentNormalization;
pub use content_stream::ObjectHandleParserCallbacks as ObjectParserCallbacks;
pub use content_stream::parse_content_operations;
pub use content_stream::ObjectHandleParserCallbacks;
pub use content_stream::ParseControl;
pub use default_appearance::parse_default_appearance;
pub use default_appearance::DefaultAppearance;
pub use default_appearance::TextColor;
pub use diagnostics::Diagnostics;
pub use embedded_files::delete_embedded_file;
pub use embedded_files::insert_embedded_file;
pub use embedded_files::list_embedded_files;
pub use embedded_files::list_embedded_files_with_max_depth;
pub use embedded_files::remove_attachment;
pub use embedded_files::EmbeddedFileDocumentHelper;
pub use embedded_files::DEFAULT_MAX_EMBEDDED_FILES_DEPTH;
pub use encryption::permissions::Permissions;
pub use encryption::permissions::PermissionsConfig;
pub use encryption::permissions::PrintPermission;
pub use encryption::permissions::R2PermissionsConfig;
pub use encryption::CopyEncryptionSource;
pub use encryption::EncryptMethod;
pub use encryption::EncryptParams;
pub use encryption::ObjectKeyAlg;
pub use encryption::PasswordMode;
pub use encryption::PasswordWriteNotice;
pub use error::EncryptedError;
pub use error::Error;
pub use error::QpdfErrorCode;
pub use error::QpdfExc;
pub use error::Result;
pub use error::UsageError;
pub use filespec_helper::encode_utf16be;
pub use filespec_helper::format_pdf_date;
pub use filespec_helper::md5_checksum;
pub use filespec_helper::EmbeddedFileStream;
pub use filespec_helper::FileParamDates;
pub use filespec_helper::FileSpec;
pub use filespec_helper::FileSpecBuilder;
pub use form_field_object_helper::FormFieldObjectHelper;
pub use job::add_attachment_from_path;Deprecated
pub use job::ascii_filename_fallback;Deprecated
pub use job::copy_duplicate_page_annotations;
pub use job::extract_attachment;Deprecated
pub use job::extract_attachment_to_path;Deprecated
pub use job::handle_under_overlay;
pub use job::merge_documents;
pub use job::overlay_verbose_report;
pub use job::write_attachment;Deprecated
pub use job::MergeInput;
pub use job::OverlayKind;
pub use job::OverlaySpec;
pub use job::OverlayVerbosePage;
pub use job::OverlayVerboseSource;
pub use job::PageRange;
pub use job::DEFAULT_MAX_ACROFORM_DEPTH;
pub use job::optimize_images;
pub use job::ImageOptimizationOptions;
pub use job::RemoveUnreferencedResources;
pub use matrix::Matrix;
pub use matrix::Rectangle;
pub use object_ref::ObjectRef;
pub use object_ref::ParseObjectRefError;
pub use objr_obj_annot_p::drop_objr_obj_annot_dangling_p;
pub use outline_document_helper::OutlineDocumentHelper;
pub use outline_object_helper::OutlineId;
pub use outline_object_helper::OutlineItem;
pub use outline_object_helper::OutlineTree;
pub use outline_object_helper::OutlineTreeIter;
pub use page_document_helper::PageDocumentHelper;
pub use page_document_helper::PageInput;
pub use page_extract::extract_page;
pub use page_extract::extract_pages;
pub use page_label_document_helper::LabelRange;
pub use page_label_document_helper::LabelStyle;
pub use page_label_document_helper::PageLabelDocumentHelper;
pub use page_object_helper::PageBox;
pub use page_object_helper::PageObjectHelper;
pub use page_splice::splice_pages;
pub use page_splice::splice_pages_with_max_depth;
pub use pages::tree_rebuild::rebuild_page_tree;
pub use pages::tree_rebuild::rebuild_page_tree_with_max_depth;
pub use pages::tree_rebuild::RebuildResult;
pub use pdf::Pdf;
pub use pdf_version::parse_pdf_version;
pub use pdf_version::parse_pdf_version_spec;
pub use pdf_version::PdfVersion;
pub use pipeline::Pipeline;
pub use pipeline::PipelineError;
pub use pipeline::PipelineHandle;
pub use pipeline::PipelineRef;
pub use pipeline::PipelineResult;
pub use qdf_fix::fix_qdf;
pub use reader::PdfOpenOptions;
pub use reader::ReadSeek;
pub use signatures::acroform_sig_flags;
pub use signatures::clear_sig_flags;
pub use signatures::signatures;
pub use signatures::signatures_with_max_depth;
pub use signatures::strip_signature_values;
pub use signatures::SignatureInfo;
pub use signatures::DEFAULT_MAX_SIGNATURE_FIELD_DEPTH;
pub use signatures::SIG_FLAGS_APPEND_ONLY;
pub use signatures::SIG_FLAGS_SIGNATURES_EXIST;
pub use stream_filter::register_stream_filter;
pub use stream_filter::OwnedDecodePipeline;
pub use stream_filter::StreamFilter;
pub use struct_tree_pg::drop_struct_elem_dangling_pg;
pub use struct_tree_pg::drop_struct_elem_dangling_pg_with_max_depth;
pub use struct_tree_pg::DEFAULT_MAX_STRUCT_TREE_DEPTH;
pub use thread_bead_p::drop_thread_bead_dangling_p;
pub use token_filter::TokenFilter;
pub use token_filter::TokenFilterOutput;
pub use tokenizer::Token as ContentToken;
pub use tokenizer::TokenType as ContentTokenType;
pub use writer::write_stream_to_buf;
pub use writer::CompressStreams;
pub use writer::DecodeLevel;
pub use writer::NewlineBeforeEndstream;
pub use writer::ObjectStreamMode;
pub use writer::PdfWriter;
pub use writer::StreamDataMode;
pub use writer::WriterConfiguration;
pub use xref::XrefForm;
pub use xref_entry::XrefEntry;

Modules§

acroform_document_helper
High-level AcroForm document helper.
annotation_object_helper
Typed accessor helpers for annotation objects.
content_normalizer
Normalize PDF content streams and report malformed-token recovery.
content_stream
Content-stream object callbacks (ISO 32000-1 §7.8.2).
default_appearance
Parser for the PDF /DA (default appearance) string.
diagnostics
Ordered warnings and diagnostics for PDF processing.
document_json
Write the document-level PDF JSON object map and stream side files.
embedded_files
Read/write access to the /Names /EmbeddedFiles name-tree.
encryption
This is the crate-level encryption route. The child modules group the Standard security handler, key derivation, crypt-filter interpretation, password normalization, permission projection, and cryptographic primitives under one source tree. Writer emission and pipeline stages remain in the writer and pipeline modules.
engine
Construct and initialize Pdf values from empty, file, and memory inputs.
error
Error types and result aliases for PDF processing.
filespec_helper
Typed wrappers for /Filespec dictionaries and /EmbeddedFile streams, plus a builder for constructing them.
form_field_object_helper
Provide live lookup and mutation for AcroForm field dictionaries.
job
Coordinate document-level inspection, transformation, and output policies.
json
Parse, validate, and serialize PDF inspection JSON values.
json_inspect
Convert PDF objects and streams to canonical inspection JSON values.
linearization
Linearization support — data model and planning structures.
logger
Shared logger sinks for info, warning, error, and binary-save output.
matrix
PDF coordinate matrices and rectangle transforms.
object_copy
Cross-document deep object copier (identity-preserving reservation + cycle handling).
object_ref
PDF object-reference identity and parsing.
objr_obj_annot_p
Annotation /P reference drop for annotations kept alive only through a structure-tree object reference (/Type /OBJR) /Obj, after page extraction.
outline_document_helper
High-level outline (/Outlines) document helper.
outline_object_helper
Materialize outline items as a live OutlineTree with bounded traversal.
page_document_helper
Provide live traversal and mutation for a document’s page tree.
page_extract
Page extraction into a fresh document.
page_label_document_helper
PageLabelDocumentHelper reads and reconstructs (ISO 32000-1 §12.4.2) the catalog /PageLabels number tree. Read methods retain live ObjectHandle values for raw /S, /P, and /St semantics; LabelRange is the typed view used by reconstruction and inspection APIs.
page_object_helper
Provide live typed access to one PDF page.
page_splice
Surgical in-place mutation of the /Pages tree.
pages
Page-tree traversal helpers.
parser
PDF object and content-stream parsing.
pdf
Central PDF document state and object-handle ownership.
pdf_string
Decode PDFDocEncoding, construct Unicode PDF strings, and serialize binary strings for flpdf consumers.
pdf_version
Parse and format PDF version identifiers.
pipeline
Streaming pipeline traits and lifecycle errors.
qdf_fix
Repair QDF cross-reference offsets after manual edits.
qutil
Provide shared PDF utilities for integer conversion, file identity, and text encoding. Invalid or unrepresentable input is converted to ? where the corresponding API is lossy; resource lookup, font selection, and password policy remain owned by their respective modules.
reader
PDF input loading, resolution, recovery, and authentication.
resources
Remove unreferenced resources from page and Form content.
signatures
Inspect signature fields and manage signature-related AcroForm flags.
stream_filter
Decode and re-encode PDF stream filters.
struct_tree_pg
Structure-tree /Pg reference drop after page extraction.
thread_bead_p
Article-thread bead /P reference drop after page extraction.
token_filter
Token-filter callbacks and content rewriting.
tokenizer
PDF lexical tokenization.
writer
PDF writer orchestration and shared writer modules.
xref
Load, validate, and recover PDF cross-reference data. Xref streams are parsed as live ObjectHandle graphs before their encoded payloads enter the handle-native filter pipeline.
xref_entry
PDF cross-reference entry representation.

Structs§

ArrayItemCursor
A reversible cursor over ArrayItems. The cursor keeps the canonical array handle and returns an owned handle clone for its current child.
ArrayItems
A qpdf-shaped view over the items of an array handle.
DictItem
One dictionary entry returned by DictItemCursor::current. At the end cursor its value is an explicit uninitialized handle, matching qpdf’s default iterator value rather than a null object.
DictItemCursor
A reversible cursor over DictItems.
DictItems
A qpdf-shaped view over the entries of a dictionary handle.
NameTree
Read and modify a PDF name tree (a /Names-style sorted key/value index).
NameTreeCursor
Cursor over a NameTree whose values retain live ObjectHandle identity.
NumberTree
Read and modify a PDF number tree (a /PageLabels-style sorted integer-key index).
NumberTreeCursor
Cursor over a NumberTree.
ObjectHandle
A shared, cloneable handle to a PDF object.
ObjectHandleMatrix
The all-zero-default matrix nested inside qpdf’s QPDFObjectHandle.
QpdfObjGen
Raw qpdf object/generation identity carried by an object handle.

Enums§

ObjectJsonError
Errors raised by the canonical ObjectHandle JSON writer.
QpdfStreamJsonData

Constants§

DEFAULT_MAX_TREE_DEPTH
Default /Kids descent depth limit for name and number tree traversal.
LEAF_MAX
Default qpdf split threshold for name and number tree leaves.
STREAM_ENCODE_COMPRESS
Request Flate compression when encoding stream data for ObjectHandle::pipe_stream_data’s encode_flags argument.
STREAM_ENCODE_NORMALIZE
Request content-stream token normalization when encoding stream data for ObjectHandle::pipe_stream_data’s encode_flags argument.

Traits§

StreamDataProvider
Deferred stream-data source corresponding to qpdf’s QPDFObjectHandle::StreamDataProvider (include/qpdf/QPDFObjectHandle.hh:68-127).

Functions§

qpdf_version
Return the pinned qpdf library version exposed by qpdf’s QPDF::QPDFVersion (libqpdf/QPDF.cc:178-181). This is deliberately separate from version, which reports flpdf’s Cargo package version. qpdf-shaped CLI and helper-process output must use this value.
version
Crate version, mirroring Cargo.toml’s [package].version.