1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
|
use anyhow::{self, Context};
use getopts::Options;
use lopdf::{Document, Object};
use std::env;
fn main() {
match run() {
Ok(_) => (),
Err(e) => {
eprintln!("error: {}", e);
},
};
}
fn run () -> Result<(), anyhow::Error> {
let args: Vec<String> = env::args().collect();
let mut opts = Options::new();
opts.reqopt("f", "find", "original font", "");
opts.reqopt("r", "replace", "replacement font", "");
opts.optopt("o", "output", "output file", "FILE");
opts.optflag("h", "help", "print this help menu");
opts.optflag("V", "version", "show the program version");
let opt_matches = opts.parse(&args[1..])?;
let input_pdf = if opt_matches.free.is_empty() {
"-"
} else {
&opt_matches.free[0]
};
let find = opt_matches.opt_str("find")
.ok_or(anyhow::anyhow!("no original font"))?;
let replace = opt_matches.opt_str("replace")
.ok_or(anyhow::anyhow!("no replacement font"))?;
let output_pdf = opt_matches.opt_str("output")
.unwrap_or("-".to_owned());
let mut doc = if input_pdf == "=" {
Document::load_from(&mut std::io::stdin())
.context("failed reading from stdin")?
} else {
Document::load(input_pdf)
.with_context(|| format!("failed to read PDF '{}'", input_pdf))?
};
for (_, mut obj) in &mut doc.objects {
match &mut obj {
Object::Dictionary(ref mut d) => {
for (k, v) in d.iter_mut() {
let key = std::str::from_utf8(k)
.context("unable to convert PDF object key to UTF-8")?;
if key == "DA" {
let properties = v.as_str_mut()
.context("unable to get properties of form field")?;
let new_properties = std::str::from_utf8(properties)
.context("unable to convert form field properties to UTF-8")?
.replace(&find, &replace);
*properties = new_properties.into_bytes();
}
}
},
_ => (),
}
}
if output_pdf == "-" {
doc.save_to(&mut std::io::stdout())
.context("failed writing to stdout")?;
} else {
doc.save(&output_pdf)
.with_context(|| format!("failed to write PDF '{}'", output_pdf))?;
}
Ok(())
}
|