Skip to main content

Document

Struct Document 

Source
pub struct Document { /* private fields */ }
Expand description

A parsed PDF file.

Opening is cheap: only the header, the cross-reference sections and the trailer are read. Pages, streams and content are parsed on demand by Document::get_object, which caches what it reads.

Implementations§

Source§

impl Document

Source

pub fn extract_text(&self, page: &Page) -> Result<String>

Extract the text of a page’s content streams.

Examples found in repository?
examples/write.rs (line 23)
8fn main() -> Result<(), pdf2::Error> {
9    let mut document = Document::new();
10    document.add_page(
11        Rect::new(0.0, 0.0, 612.0, 792.0),
12        "BT /F1 24 Tf 72 700 Td (Hello from pdf2) Tj ET",
13    );
14    let bytes = document.save()?;
15    std::fs::write("hello.pdf", &bytes)?;
16
17    let reopened = Document::open(bytes)?;
18    let page = reopened.page(0)?;
19    println!(
20        "hello.pdf: PDF {}, {} page(s), {}",
21        reopened.version(),
22        reopened.page_count()?,
23        reopened.extract_text(&page)?
24    );
25    Ok(())
26}
Source

pub fn extract_text_from( &self, content: &[u8], resources: Option<&Dictionary>, ) -> Result<String>

Extract text from a decoded content stream and its resource dictionary.

Source§

impl Document

Source

pub fn open(data: impl Into<Vec<u8>>) -> Result<Self>

Open a PDF from its bytes.

Accepts %PDF-1.x and %PDF-2.x files whose cross-reference is a classic table, an xref stream, or a hybrid of both, with any number of /Prev sections.

An encrypted file is opened with the empty password, which covers the common “no password needed, but encrypted” case; use Document::open_with_password otherwise.

Examples found in repository?
examples/write.rs (line 17)
8fn main() -> Result<(), pdf2::Error> {
9    let mut document = Document::new();
10    document.add_page(
11        Rect::new(0.0, 0.0, 612.0, 792.0),
12        "BT /F1 24 Tf 72 700 Td (Hello from pdf2) Tj ET",
13    );
14    let bytes = document.save()?;
15    std::fs::write("hello.pdf", &bytes)?;
16
17    let reopened = Document::open(bytes)?;
18    let page = reopened.page(0)?;
19    println!(
20        "hello.pdf: PDF {}, {} page(s), {}",
21        reopened.version(),
22        reopened.page_count()?,
23        reopened.extract_text(&page)?
24    );
25    Ok(())
26}
Source

pub fn open_with_password( data: impl Into<Vec<u8>>, password: &[u8], ) -> Result<Self>

Open a PDF with a password for its /V 5 (AES-256) security handler.

Source

pub fn open_path(path: impl AsRef<Path>) -> Result<Self>

Open a PDF from a file path.

Source

pub fn open_path_with_password( path: impl AsRef<Path>, password: &[u8], ) -> Result<Self>

Open a PDF from a file path with a password.

Source

pub fn is_encrypted(&self) -> bool

Whether the document was opened with a security handler.

Source

pub fn version(&self) -> &str

The version from the header, e.g. "2.0".

Examples found in repository?
examples/write.rs (line 21)
8fn main() -> Result<(), pdf2::Error> {
9    let mut document = Document::new();
10    document.add_page(
11        Rect::new(0.0, 0.0, 612.0, 792.0),
12        "BT /F1 24 Tf 72 700 Td (Hello from pdf2) Tj ET",
13    );
14    let bytes = document.save()?;
15    std::fs::write("hello.pdf", &bytes)?;
16
17    let reopened = Document::open(bytes)?;
18    let page = reopened.page(0)?;
19    println!(
20        "hello.pdf: PDF {}, {} page(s), {}",
21        reopened.version(),
22        reopened.page_count()?,
23        reopened.extract_text(&page)?
24    );
25    Ok(())
26}
Source

pub fn trailer(&self) -> &Dictionary

The newest trailer dictionary.

Source

pub fn catalog(&self) -> Result<Object>

The document catalog, reached through the trailer’s /Root.

The catalogue is the entry point of the whole object graph (§7.7.2).

Source

pub fn get_object(&self, id: ObjectId) -> Result<Object>

Fetch the object with this id, following the cross-reference.

Only the object number selects the entry, so a stale generation still resolves — that is what real readers do and what incremental updates rely on. Use Document::get_object_by_number to fetch with the generation the cross-reference records.

Results are cached, so fetching the same object twice parses it once.

Source

pub fn get_object_by_number(&self, number: u32) -> Result<Object>

Fetch an object by number, using the generation the cross-reference has.

Source

pub fn contains_object(&self, number: u32) -> bool

Whether the cross-reference knows number as a live object.

Source

pub fn stream(&self, id: ObjectId) -> Result<Stream>

Fetch a stream object by id.

Source

pub fn decode_stream(&self, stream: &Stream) -> Result<Vec<u8>>

Decode a stream’s payload through its filter chain.

Indirect /Filter and /DecodeParms entries are resolved through the object table first, which is what the plain Stream::decode cannot do on its own.

Source

pub fn stream_data(&self, id: ObjectId) -> Result<Vec<u8>>

Fetch a stream by id and decode its payload in one step.

Source§

impl Document

Source

pub fn catalog_dict(&self) -> Result<Dictionary>

The catalog dictionary.

Source

pub fn pages(&self) -> Result<Vec<Page>>

Walk the page tree and return every page in document order.

Source

pub fn page_count(&self) -> Result<usize>

Number of pages, counted by walking the tree rather than trusting /Count.

Examples found in repository?
examples/write.rs (line 22)
8fn main() -> Result<(), pdf2::Error> {
9    let mut document = Document::new();
10    document.add_page(
11        Rect::new(0.0, 0.0, 612.0, 792.0),
12        "BT /F1 24 Tf 72 700 Td (Hello from pdf2) Tj ET",
13    );
14    let bytes = document.save()?;
15    std::fs::write("hello.pdf", &bytes)?;
16
17    let reopened = Document::open(bytes)?;
18    let page = reopened.page(0)?;
19    println!(
20        "hello.pdf: PDF {}, {} page(s), {}",
21        reopened.version(),
22        reopened.page_count()?,
23        reopened.extract_text(&page)?
24    );
25    Ok(())
26}
Source

pub fn page(&self, index: usize) -> Result<Page>

The page at index, counting from zero.

Examples found in repository?
examples/write.rs (line 18)
8fn main() -> Result<(), pdf2::Error> {
9    let mut document = Document::new();
10    document.add_page(
11        Rect::new(0.0, 0.0, 612.0, 792.0),
12        "BT /F1 24 Tf 72 700 Td (Hello from pdf2) Tj ET",
13    );
14    let bytes = document.save()?;
15    std::fs::write("hello.pdf", &bytes)?;
16
17    let reopened = Document::open(bytes)?;
18    let page = reopened.page(0)?;
19    println!(
20        "hello.pdf: PDF {}, {} page(s), {}",
21        reopened.version(),
22        reopened.page_count()?,
23        reopened.extract_text(&page)?
24    );
25    Ok(())
26}
Source

pub fn page_content(&self, page: &Page) -> Result<Vec<u8>>

The decoded content of a page, with its streams joined by a newline.

This is the input the content-stream interpreter takes.

Source

pub fn has_metadata(&self) -> Result<bool>

Whether the catalog carries an XMP /Metadata stream.

Source

pub fn metadata(&self) -> Result<Option<Vec<u8>>>

The decoded XMP metadata packet, if the document has one.

Source§

impl Document

Source

pub fn new() -> DocumentBuilder

Start a new, empty PDF 2.0 document.

Returns a DocumentBuilder rather than a reader: collect objects and pages with it, then DocumentBuilder::save the file and Document::open it back. The name follows the plan’s Document::new() … save() shape; the builder is the only thing that can be “new”, because a reader always comes from bytes.

Examples found in repository?
examples/write.rs (line 9)
8fn main() -> Result<(), pdf2::Error> {
9    let mut document = Document::new();
10    document.add_page(
11        Rect::new(0.0, 0.0, 612.0, 792.0),
12        "BT /F1 24 Tf 72 700 Td (Hello from pdf2) Tj ET",
13    );
14    let bytes = document.save()?;
15    std::fs::write("hello.pdf", &bytes)?;
16
17    let reopened = Document::open(bytes)?;
18    let page = reopened.page(0)?;
19    println!(
20        "hello.pdf: PDF {}, {} page(s), {}",
21        reopened.version(),
22        reopened.page_count()?,
23        reopened.extract_text(&page)?
24    );
25    Ok(())
26}

Trait Implementations§

Source§

impl Debug for Document

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl LengthResolver for Document

Source§

fn resolve_length(&self, id: ObjectId) -> Result<usize>

The byte length of the object id points at.

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.