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:
Pdfis the parsed-but-lazy document handle.Pdf::openreads the trailer and cross-reference table, then resolves objects on demand via canonical ObjectHandle resolution.Pdf::uninitializedrepresents qpdf’s default-constructed document before any input source has been processed.ObjectHandleandObjectRefare the data model.pagesandoutline_object_helperare traversal helpers built on top ofPdf. They mirror the read-only inspection surface thatqpdf --show-pagesand--json-key=outlinesprovide.PdfWriterconfigures the one fresh full-rewrite output with qpdf-shaped settings.job::QPDFJob::checkowns 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:
PdfWriteroutput (with no page selection) preserves both destination sources — the legacy catalog/Destsdictionary and the modern/Names /Destsname tree (ISO 32000-2 §7.9.6, §12.3.2.3); deeply nested outlines (walks are iterative); all five/Aaction subtypes (GoTo,GoToR,URI,Launch,Named) plus their/Nextchains (ISO 32000-2 §12.6.2); the/SEstructure-element link (ISO 32000-2 §14.7); and the/PageLabelsnumber-tree ranges (ISO 32000-2 §7.9.7).rebuild_page_treealone only rewrites the/Pagestree; it does NOT remap outline/Destrefs, does NOT drop/Destsentries whose targets went away, and does NOT reconstruct/PageLabels. Serializing onlyrebuild_page_tree’s output leaves stale destinations and label ranges pointing at pages no longer in the tree. Pair it withjob::remap_outline_and_destsand (when labels matter)PageLabelDocumentHelper::labels_for_selection+PageLabelDocumentHelper::write_reconstructed_labels— theextract_pagesandmerge_documentspipelines assemble that combination for you.merge_documentspreserves outlines, both dest sources, and the trailer/Infodictionary for the PRIMARY input only (matching qpdf--pages), and reconstructs/PageLabelsacross every input’s selected pages.extract_pagesreturns a new document whose serialized output is minimal and intentionally omits catalog-level navigation —/Outlines, catalog/Dests, and/Names /Destsare 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/PageLabelsis reconstructed for the selection. Callers who need outlines, dests, or/Infopreserved should usemerge_documentswith 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’spagelabelssection uses qpdf JSON v2’s outer{index, label}entries and raw page-label dictionaries (/S,/P,/St). Theoutlinessection 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 /EmbeddedFilesname-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
Pdfvalues from empty, file, and memory inputs. - error
- Error types and result aliases for PDF processing.
- filespec_
helper - Typed wrappers for
/Filespecdictionaries and/EmbeddedFilestreams, 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
/Preference 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
OutlineTreewith 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 PageLabelDocumentHelperreads and reconstructs (ISO 32000-1 §12.4.2) the catalog/PageLabelsnumber tree. Read methods retain liveObjectHandlevalues for raw/S,/P, and/Stsemantics;LabelRangeis 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
/Pagestree. - pages
- Page-tree traversal helpers.
- parser
- PDF object and content-stream parsing.
- 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
/Pgreference drop after page extraction. - thread_
bead_ p - Article-thread bead
/Preference 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
ObjectHandlegraphs before their encoded payloads enter the handle-native filter pipeline. - xref_
entry - PDF cross-reference entry representation.
Structs§
- Array
Item Cursor - A reversible cursor over
ArrayItems. The cursor keeps the canonical array handle and returns an owned handle clone for its current child. - Array
Items - A qpdf-shaped view over the items of an array handle.
- Dict
Item - 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. - Dict
Item Cursor - A reversible cursor over
DictItems. - Dict
Items - A qpdf-shaped view over the entries of a dictionary handle.
- Name
Tree - Read and modify a PDF name tree (a
/Names-style sorted key/value index). - Name
Tree Cursor - Cursor over a
NameTreewhose values retain liveObjectHandleidentity. - Number
Tree - Read and modify a PDF number tree (a
/PageLabels-style sorted integer-key index). - Number
Tree Cursor - Cursor over a
NumberTree. - Object
Handle - A shared, cloneable handle to a PDF object.
- Object
Handle Matrix - The all-zero-default matrix nested inside qpdf’s
QPDFObjectHandle. - Qpdf
ObjGen - Raw qpdf object/generation identity carried by an object handle.
Enums§
- Object
Json Error - Errors raised by the canonical ObjectHandle JSON writer.
- Qpdf
Stream Json Data
Constants§
- DEFAULT_
MAX_ TREE_ DEPTH - Default
/Kidsdescent 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’sencode_flagsargument. - STREAM_
ENCODE_ NORMALIZE - Request content-stream token normalization when encoding stream data for
ObjectHandle::pipe_stream_data’sencode_flagsargument.
Traits§
- Stream
Data Provider - 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 fromversion, 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.