Skip to main content

text/
text.rs

1//! Extracts a document's text: `cargo run --example text -- file.pdf [page]`.
2//!
3//! Pages are separated by a form feed, matching what `pdftotext` emits, so the output can be
4//! diffed against other extractors directly.
5
6fn main() {
7    let mut args = std::env::args().skip(1);
8    let Some(path) = args.next() else {
9        eprintln!("usage: text <file.pdf> [page-index]");
10        std::process::exit(2);
11    };
12    let only: Option<usize> = args.next().and_then(|s| s.parse().ok());
13
14    let doc = match rustium_pdf::Document::open(&path) {
15        Ok(d) => d,
16        Err(e) => {
17            eprintln!("{path}: {e}");
18            std::process::exit(1);
19        }
20    };
21
22    let pages: Vec<usize> = match only {
23        Some(i) => vec![i],
24        None => (0..doc.page_count()).collect(),
25    };
26    for (n, i) in pages.iter().enumerate() {
27        if n > 0 {
28            print!("\u{000C}");
29        }
30        match doc.page(*i) {
31            Ok(page) => println!("{}", page.text()),
32            Err(e) => eprintln!("page {i}: {e}"),
33        }
34    }
35}