Skip to main content

pdf_min/
font.rs

1use crate::basic::BasicPdfWriter;
2use format_bytes::write_bytes as wb;
3
4///
5pub trait Font {
6    /// Get the PDF object number.
7    fn obj(&self) -> usize;
8    /// Encode string.
9    fn encode(&self, s: &str, to: &mut Vec<u8>);
10    /// Initialise the font by writing defition to w.
11    fn init(&mut self, w: &mut BasicPdfWriter, name: &str);
12}
13
14///
15#[derive(Default)]
16pub struct StandardFont {
17    obj: usize,
18}
19
20impl Font for StandardFont {
21    fn obj(&self) -> usize {
22        self.obj
23    }
24
25    fn init(&mut self, w: &mut BasicPdfWriter, name: &str) {
26        if self.obj == 0 {
27            self.obj = w.begin();
28            let _ = wb!(
29                &mut w.b,
30                b"<</Type/Font/Subtype/Type1/Name/F{}/BaseFont/{}/Encoding/WinAnsiEncoding>>",
31                self.obj,
32                name.as_bytes()
33            );
34            w.end();
35        }
36    }
37
38    fn encode(&self, s: &str, to: &mut Vec<u8>) {
39        let mut e = encoding_rs::WINDOWS_1252.new_encoder();
40        let x = e
41            .max_buffer_length_from_utf8_without_replacement(s.len())
42            .unwrap();
43        to.reserve(x); // Weird that this is necessary.
44        let (r, _n) = e.encode_from_utf8_to_vec_without_replacement(s, to, false);
45        assert!(r == encoding_rs::EncoderResult::InputEmpty);
46    }
47}
48
49/// Names of standard Times font.
50pub static TIMES: [&str; 4] = [
51    "Times-Roman",
52    "Times-Bold",
53    "Times-Italic",
54    "Times-BoldItalic",
55];
56
57/// Names of standard Helvetica font.
58pub static HELVETICA: [&str; 4] = [
59    "Helvetica",
60    "Helvetica-Bold",
61    "Helvetica-Oblique",
62    "Helvetica-BoldOblique",
63];
64
65/// Names of standard Courier font.
66pub static COURIER: [&str; 4] = [
67    "Courier",
68    "Courier-Bold",
69    "Courier-Oblique",
70    "Courier-BoldOblique",
71];