| 1 |
use std::collections::BTreeMap; |
| 2 |
use std::fmt::Debug; |
| 3 |
use std::fs::File; |
| 4 |
use std::io::{Error, ErrorKind, Write}; |
| 5 |
use std::path::{Path, PathBuf}; |
| 6 |
use std::time::Instant; |
| 7 |
|
| 8 |
use clap::Parser; |
| 9 |
use lopdf::{Document, Object}; |
| 10 |
use rayon::iter::{IntoParallelIterator, ParallelIterator}; |
| 11 |
use serde::{Deserialize, Serialize}; |
| 12 |
use serde_json; |
| 13 |
use shellexpand; |
| 14 |
|
| 15 |
#[cfg(feature = "async")] |
| 16 |
use tokio::runtime::Builder; |
| 17 |
|
| 18 |
static IGNORE: &[&[u8]] = &[ |
| 19 |
b"Length", |
| 20 |
b"BBox", |
| 21 |
b"FormType", |
| 22 |
b"Matrix", |
| 23 |
b"Type", |
| 24 |
b"XObject", |
| 25 |
b"Subtype", |
| 26 |
b"Filter", |
| 27 |
b"ColorSpace", |
| 28 |
b"Width", |
| 29 |
b"Height", |
| 30 |
b"BitsPerComponent", |
| 31 |
b"Length1", |
| 32 |
b"Length2", |
| 33 |
b"Length3", |
| 34 |
b"PTEX.FileName", |
| 35 |
b"PTEX.PageNumber", |
| 36 |
b"PTEX.InfoDict", |
| 37 |
b"FontDescriptor", |
| 38 |
b"ExtGState", |
| 39 |
b"MediaBox", |
| 40 |
b"Annot", |
| 41 |
]; |
| 42 |
|
| 43 |
#[derive(Debug, Deserialize, Serialize)] |
| 44 |
struct PdfText { |
| 45 |
text: BTreeMap<u32, Vec<String>>, // Key is page number |
| 46 |
errors: Vec<String>, |
| 47 |
} |
| 48 |
|
| 49 |
#[derive(Parser, Debug)] |
| 50 |
#[clap( |
| 51 |
author, |
| 52 |
version, |
| 53 |
about, |
| 54 |
long_about = "Extract TOC and write to file.", |
| 55 |
arg_required_else_help = true |
| 56 |
)] |
| 57 |
pub struct Args { |
| 58 |
pub pdf_path: PathBuf, |
| 59 |
|
| 60 |
/// Optional output directory. If omitted the directory of the PDF file will be used. |
| 61 |
#[clap(short, long)] |
| 62 |
pub output: Option<PathBuf>, |
| 63 |
|
| 64 |
/// Optional pretty print output. |
| 65 |
#[clap(short, long)] |
| 66 |
pub pretty: bool, |
| 67 |
|
| 68 |
/// Optional password for encrypted PDFs |
| 69 |
#[clap(long, default_value_t = String::from(""))] |
| 70 |
pub password: String, |
| 71 |
} |
| 72 |
|
| 73 |
impl Args { |
| 74 |
pub fn parse_args() -> Self { |
| 75 |
Args::parse() |
| 76 |
} |
| 77 |
} |
| 78 |
|
| 79 |
fn filter_func(object_id: (u32, u16), object: &mut Object) -> Option<((u32, u16), Object)> { |
| 80 |
if IGNORE.contains(&object.type_name().unwrap_or_default()) { |
| 81 |
return None; |
| 82 |
} |
| 83 |
if let Ok(d) = object.as_dict_mut() { |
| 84 |
d.remove(b"Producer"); |
| 85 |
d.remove(b"ModDate"); |
| 86 |
d.remove(b"Creator"); |
| 87 |
d.remove(b"ProcSet"); |
| 88 |
d.remove(b"Procset"); |
| 89 |
d.remove(b"XObject"); |
| 90 |
d.remove(b"MediaBox"); |
| 91 |
d.remove(b"Annots"); |
| 92 |
if d.is_empty() { |
| 93 |
return None; |
| 94 |
} |
| 95 |
} |
| 96 |
Some((object_id, object.to_owned())) |
| 97 |
} |
| 98 |
|
| 99 |
#[cfg(not(feature = "async"))] |
| 100 |
fn load_pdf<P: AsRef<Path>>(path: P) -> Result<Document, Error> { |
| 101 |
Document::load_filtered(path, filter_func).map_err(|e| Error::new(ErrorKind::Other, e.to_string())) |
| 102 |
} |
| 103 |
|
| 104 |
#[cfg(feature = "async")] |
| 105 |
fn load_pdf<P: AsRef<Path>>(path: P) -> Result<Document, Error> { |
| 106 |
Ok(Builder::new_current_thread().build().unwrap().block_on(async move { |
| 107 |
Document::load_filtered(path, filter_func) |
| 108 |
.await |
| 109 |
.map_err(|e| Error::new(ErrorKind::Other, e.to_string())) |
| 110 |
})?) |
| 111 |
} |
| 112 |
|
| 113 |
fn get_pdf_text(doc: &Document) -> Result<PdfText, Error> { |
| 114 |
let mut pdf_text: PdfText = PdfText { |
| 115 |
text: BTreeMap::new(), |
| 116 |
errors: Vec::new(), |
| 117 |
}; |
| 118 |
let pages: Vec<Result<(u32, Vec<String>), Error>> = doc |
| 119 |
.get_pages() |
| 120 |
.into_par_iter() |
| 121 |
.map( |
| 122 |
|(page_num, page_id): (u32, (u32, u16))| -> Result<(u32, Vec<String>), Error> { |
| 123 |
let text = doc.extract_text(&[page_num]).map_err(|e| { |
| 124 |
Error::new( |
| 125 |
ErrorKind::Other, |
| 126 |
format!("Failed to extract text from page {page_num} id={page_id:?}: {e:}"), |
| 127 |
) |
| 128 |
})?; |
| 129 |
Ok(( |
| 130 |
page_num, |
| 131 |
text.split('\n') |
| 132 |
.map(|s| s.trim_end().to_string()) |
| 133 |
.collect::<Vec<String>>(), |
| 134 |
)) |
| 135 |
}, |
| 136 |
) |
| 137 |
.collect(); |
| 138 |
for page in pages { |
| 139 |
match page { |
| 140 |
Ok((page_num, lines)) => { |
| 141 |
pdf_text.text.insert(page_num, lines); |
| 142 |
} |
| 143 |
Err(e) => { |
| 144 |
pdf_text.errors.push(e.to_string()); |
| 145 |
} |
| 146 |
} |
| 147 |
} |
| 148 |
Ok(pdf_text) |
| 149 |
} |
| 150 |
|
| 151 |
fn pdf2text<P: AsRef<Path> + Debug>(path: P, output: P, pretty: bool, password: &str) -> Result<(), Error> { |
| 152 |
println!("Load {path:?}"); |
| 153 |
let mut doc = load_pdf(&path)?; |
| 154 |
if doc.is_encrypted() { |
| 155 |
doc.decrypt(password) |
| 156 |
.map_err(|_err| Error::new(ErrorKind::InvalidInput, "Failed to decrypt"))?; |
| 157 |
} |
| 158 |
let text = get_pdf_text(&doc)?; |
| 159 |
if !text.errors.is_empty() { |
| 160 |
eprintln!("{path:?} has {} errors:", text.errors.len()); |
| 161 |
for error in &text.errors[..10] { |
| 162 |
eprintln!("{error:?}"); |
| 163 |
} |
| 164 |
} |
| 165 |
let data = match pretty { |
| 166 |
true => serde_json::to_string_pretty(&text).unwrap(), |
| 167 |
false => serde_json::to_string(&text).unwrap(), |
| 168 |
}; |
| 169 |
println!("Write {output:?}"); |
| 170 |
let mut f = File::create(output)?; |
| 171 |
f.write_all(data.as_bytes())?; |
| 172 |
Ok(()) |
| 173 |
} |
| 174 |
|
| 175 |
fn main() -> Result<(), Error> { |
| 176 |
let args = Args::parse_args(); |
| 177 |
|
| 178 |
let start_time = Instant::now(); |
| 179 |
let pdf_path = PathBuf::from(shellexpand::full(args.pdf_path.to_str().unwrap()).unwrap().to_string()); |
| 180 |
let output = match args.output { |
| 181 |
Some(o) => o.join(pdf_path.file_name().unwrap()), |
| 182 |
None => args.pdf_path, |
| 183 |
}; |
| 184 |
let mut output = PathBuf::from(shellexpand::full(output.to_str().unwrap()).unwrap().to_string()); |
| 185 |
output.set_extension("text"); |
| 186 |
pdf2text(&pdf_path, &output, args.pretty, &args.password)?; |
| 187 |
println!( |
| 188 |
"Done after {:.1} seconds.", |
| 189 |
Instant::now().duration_since(start_time).as_secs_f64() |
| 190 |
); |
| 191 |
Ok(()) |
| 192 |
} |