Debian Codegraph @

debian/missing-sources/lopdf/examples/extract_toc.rs

raw
1 use std::fmt::Debug;
2 use std::fs::File;
3 use std::io::{Error, ErrorKind, Write};
4 use std::path::{Path, PathBuf};
5 use std::time::Instant;
6
7 use clap::Parser;
8 use lopdf::{Document, Object};
9 use serde_json;
10 use shellexpand;
11
12 #[cfg(feature = "async")]
13 use tokio::runtime::Builder;
14
15 static IGNORE: &[&[u8]] = &[
16 b"Length",
17 b"BBox",
18 b"FormType",
19 b"Matrix",
20 b"Resources",
21 b"Type",
22 b"XObject",
23 b"Subtype",
24 b"Filter",
25 b"ColorSpace",
26 b"Width",
27 b"Height",
28 b"BitsPerComponent",
29 b"Length1",
30 b"Length2",
31 b"Length3",
32 b"PTEX.FileName",
33 b"PTEX.PageNumber",
34 b"PTEX.InfoDict",
35 b"FontDescriptor",
36 b"ExtGState",
37 b"Font",
38 b"MediaBox",
39 b"Annot",
40 ];
41
42 #[derive(Parser, Debug)]
43 #[clap(
44 author,
45 version,
46 about,
47 long_about = "Extract TOC and write to file.",
48 arg_required_else_help = true
49 )]
50 pub struct Args {
51 pub pdf_path: PathBuf,
52
53 /// Optional output directory. If omitted the directory of the PDF file will be used.
54 #[clap(short, long)]
55 pub output: Option<PathBuf>,
56
57 /// Optional pretty print output.
58 #[clap(short, long)]
59 pub pretty: bool,
60 }
61
62 impl Args {
63 pub fn parse_args() -> Self {
64 Args::parse()
65 }
66 }
67
68 fn filter_func(object_id: (u32, u16), object: &mut Object) -> Option<((u32, u16), Object)> {
69 if IGNORE.contains(&object.type_name().unwrap_or_default()) {
70 return None;
71 }
72 if let Ok(d) = object.as_dict_mut() {
73 d.remove(b"Font");
74 d.remove(b"Resources");
75 d.remove(b"Producer");
76 d.remove(b"ModDate");
77 d.remove(b"Creator");
78 d.remove(b"ProcSet");
79 d.remove(b"Procset");
80 d.remove(b"XObject");
81 d.remove(b"MediaBox");
82 d.remove(b"Annots");
83 if d.is_empty() {
84 return None;
85 }
86 }
87 Some((object_id, object.to_owned()))
88 }
89
90 #[cfg(not(feature = "async"))]
91 fn load_pdf<P: AsRef<Path>>(path: P) -> Result<Document, Error> {
92 Document::load_filtered(path, filter_func).map_err(|e| Error::new(ErrorKind::Other, e.to_string()))
93 }
94
95 #[cfg(feature = "async")]
96 fn load_pdf<P: AsRef<Path>>(path: P) -> Result<Document, Error> {
97 Ok(Builder::new_current_thread().build().unwrap().block_on(async move {
98 Document::load_filtered(path, filter_func)
99 .await
100 .map_err(|e| Error::new(ErrorKind::Other, e.to_string()))
101 })?)
102 }
103
104 fn pdf2toc<P: AsRef<Path> + Debug>(path: P, output: P, pretty: bool) -> Result<(), Error> {
105 println!("Load {path:?}");
106 let doc = load_pdf(&path)?;
107 if doc.is_encrypted() {
108 return Err(Error::new(ErrorKind::InvalidInput, "Password missing!"));
109 }
110 let toc = doc.get_toc().map_err(|e| Error::new(ErrorKind::Other, e.to_string()))?;
111 if !toc.errors.is_empty() {
112 eprintln!("{path:?} has {} errors:", toc.errors.len());
113 for error in &toc.errors[..10] {
114 eprintln!("{error:?}");
115 }
116 }
117 let data = match pretty {
118 true => serde_json::to_string_pretty(&toc).unwrap(),
119 false => serde_json::to_string(&toc).unwrap(),
120 };
121 println!("Write {output:?}");
122 let mut f = File::create(output)?;
123 f.write_all(data.as_bytes())?;
124 Ok(())
125 }
126
127 fn main() -> Result<(), Error> {
128 let args = Args::parse_args();
129
130 let start_time = Instant::now();
131 let pdf_path = PathBuf::from(shellexpand::full(args.pdf_path.to_str().unwrap()).unwrap().to_string());
132 let output = match args.output {
133 Some(o) => o.join(pdf_path.file_name().unwrap()),
134 None => args.pdf_path,
135 };
136 let mut output = PathBuf::from(shellexpand::full(output.to_str().unwrap()).unwrap().to_string());
137 output.set_extension("toc");
138 pdf2toc(&pdf_path, &output, args.pretty)?;
139 println!(
140 "Done after {:.1} seconds.",
141 Instant::now().duration_since(start_time).as_secs_f64()
142 );
143 Ok(())
144 }