Debian Codegraph @

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

raw
1 // Display a summary of the annotations in a PDF file to the terminal
2 //
3 // Run with `cargo run --example print_annotations <pdf-file>`
4
5 use core::str;
6 use env_logger::Env;
7 use lopdf::{Document, Object};
8 use std::env;
9 use std::process;
10
11 fn logging() {
12 env_logger::Builder::from_env(Env::default().default_filter_or("info")).init()
13 }
14
15 fn args() -> Vec<String> {
16 let args: Vec<String> = env::args().collect();
17
18 if args.len() != 2 {
19 eprintln!("Usage: {} <pdf-file>", &args[0]);
20 process::exit(1);
21 }
22
23 args
24 }
25
26 fn handle_pdf_page(doc: Document) -> u32 {
27 let mut page_counter = 1;
28
29 for page in doc.page_iter() {
30 for a in doc.get_page_annotations(page).unwrap() {
31 let subtype = a.get_deref(b"Subtype", &doc).and_then(Object::as_name).unwrap_or(b"");
32 println!(
33 "Page {}, {} annotation at {:?}",
34 page_counter,
35 str::from_utf8(subtype).unwrap(),
36 a.get_deref(b"Rect", &doc).and_then(Object::as_array).unwrap()
37 );
38 if let Ok(Object::String(c, _)) = a.get_deref(b"Contents", &doc) {
39 println!(" Contents: {:.60}", String::from_utf8_lossy(c).lines().next().unwrap());
40 }
41 if subtype == b"Link" {
42 if let Ok(ahref) = a.get_deref(b"A", &doc).and_then(Object::as_dict) {
43 print!(
44 " {} -> ",
45 ahref
46 .get_deref(b"S", &doc)
47 .and_then(Object::as_name)
48 .map(str::from_utf8)
49 .unwrap()
50 .unwrap()
51 );
52 if let Ok(d) = ahref.get_deref(b"D", &doc).and_then(Object::as_array) {
53 println!("{:?}", d);
54 } else if let Ok(Object::String(u, _)) = ahref.get_deref(b"URI", &doc) {
55 println!("{}", String::from_utf8_lossy(u));
56 } else if let Ok(n) = ahref
57 .get_deref(b"N", &doc)
58 .and_then(Object::as_name)
59 .map(str::from_utf8)
60 .unwrap()
61 {
62 println!("{}", n);
63 }
64 }
65 }
66 }
67 page_counter += 1;
68 }
69
70 page_counter
71 }
72
73 #[cfg(not(feature = "async"))]
74 fn main() {
75 logging();
76
77 let args: Vec<String> = args();
78
79 match Document::load(&args[1]) {
80 Ok(doc) => _ = handle_pdf_page(doc),
81 Err(e) => eprintln!("Error opening {:?}: {:?}", &args[1], e),
82 }
83 }
84
85 #[cfg(feature = "async")]
86 #[tokio::main]
87 async fn main() {
88 logging();
89
90 let args: Vec<String> = args();
91
92 match Document::load(&args[1]).await {
93 Ok(doc) => _ = handle_pdf_page(doc),
94 Err(e) => eprintln!("Error opening {:?}: {:?}", &args[1], e),
95 }
96 }