Skip to main content

pdf_textlayer/
cli.rs

1//! The `pdf-textlayer` command line.
2//!
3//! The binary, the Python package, and the Node.js package all run this, so
4//! the command behaves the same however it was installed.
5
6use std::ffi::OsString;
7use std::path::PathBuf;
8
9use clap::Parser;
10use clap::builder::{PossibleValuesParser, TypedValueParser};
11
12use crate::{Adapter, Error, FontMetrics, Options, make_searchable_pdf};
13
14#[derive(Parser, Debug)]
15#[command(
16    name = "pdf-textlayer",
17    bin_name = "pdf-textlayer",
18    version,
19    about = "Add an invisible, searchable text layer to a PDF using OCR JSON. \
20             Pages without OCR text are left untouched."
21)]
22struct Cli {
23    /// Source PDF (scanned, native, or mixed).
24    input_pdf: PathBuf,
25    /// OCR JSON for the source PDF (see --from for supported formats).
26    parsed_json: PathBuf,
27    /// Path to write the resulting PDF.
28    output_pdf: PathBuf,
29    /// JSON adapter to use.
30    #[arg(
31        long = "from",
32        default_value = "liteparse",
33        value_parser = PossibleValuesParser::new(Adapter::ALL.map(Adapter::name))
34            .map(|name| Adapter::from_name(&name).expect("listed adapter")),
35    )]
36    adapter: Adapter,
37    /// Drop OCR items below this confidence (0-1).
38    #[arg(long, default_value_t = 0.0)]
39    min_confidence: f64,
40    /// Whose character widths size the invisible text: Helvetica, Times, or Courier.
41    #[arg(
42        long,
43        default_value = "helv",
44        value_parser = PossibleValuesParser::new(["helv", "tiro", "cour"])
45            .map(|name| FontMetrics::from_name(&name).expect("listed font")),
46    )]
47    font: FontMetrics,
48}
49
50/// Run the command with `args` (the first is the program name) and return the
51/// process exit code. Errors are printed to stderr. `--help`, `--version`,
52/// and invalid arguments exit the process, as clap does.
53pub fn main<I, T>(args: I) -> i32
54where
55    I: IntoIterator<Item = T>,
56    T: Into<OsString> + Clone,
57{
58    match run(args) {
59        Ok(()) => 0,
60        Err(error) => {
61            eprintln!("error: {error}");
62            1
63        }
64    }
65}
66
67/// Run the command with `args` (the first is the program name).
68pub fn run<I, T>(args: I) -> Result<(), Error>
69where
70    I: IntoIterator<Item = T>,
71    T: Into<OsString> + Clone,
72{
73    let cli = Cli::parse_from(args);
74    let options = Options {
75        min_confidence: cli.min_confidence,
76        font: cli.font,
77        ..Options::default()
78    };
79    let stats = make_searchable_pdf(&cli.input_pdf, &cli.parsed_json, &cli.output_pdf, cli.adapter, &options)?;
80
81    let ocr_pages: Vec<String> = stats.ocr_pages.iter().map(u32::to_string).collect();
82    println!("Wrote: {}", cli.output_pdf.display());
83    println!("Pages: {}", stats.pages);
84    println!(
85        "Text layer added on {} page(s): {}",
86        ocr_pages.len(),
87        if ocr_pages.is_empty() {
88            "(none)".to_string()
89        } else {
90            ocr_pages.join(", ")
91        }
92    );
93    println!("Items drawn: {}", stats.items_drawn);
94
95    Ok(())
96}
97
98#[cfg(test)]
99mod tests {
100    use super::*;
101
102    #[test]
103    fn defaults_and_flags_parse() {
104        let cli = Cli::try_parse_from(["pdf-textlayer", "in.pdf", "in.json", "out.pdf"]).unwrap();
105        assert_eq!(
106            (cli.adapter, cli.font, cli.min_confidence),
107            (Adapter::Liteparse, FontMetrics::Helvetica, 0.0)
108        );
109
110        let cli = Cli::try_parse_from([
111            "pdf-textlayer",
112            "in.pdf",
113            "in.json",
114            "out.pdf",
115            "--from",
116            "liteparse",
117            "--font",
118            "tiro",
119            "--min-confidence",
120            "0.5",
121        ])
122        .unwrap();
123        assert_eq!((cli.font, cli.min_confidence), (FontMetrics::Times, 0.5));
124    }
125
126    #[test]
127    fn unknown_adapter_and_font_are_rejected() {
128        assert!(Cli::try_parse_from(["pdf-textlayer", "a", "b", "c", "--from", "textract"]).is_err());
129        assert!(Cli::try_parse_from(["pdf-textlayer", "a", "b", "c", "--font", "comic"]).is_err());
130    }
131}