Skip to main content

pltrs_render/pdf/
object.rs

1//! PDF objects and matplotlib's `pdfRepr` serialization, including its
2//! line filling of arrays, dictionaries and operator sequences.
3
4use crate::vector::{VectorError, trimmed};
5
6/// A PDF object, or an operator or verbatim content in a content stream
7/// (what matplotlib's `pdfRepr` writes: numbers, names, strings, arrays,
8/// dictionaries, references, `null`, `Op`s and `Verbatim` content).
9///
10/// ```
11/// use pltrs_render::PdfObject;
12/// let page = PdfObject::Dict(vec![
13///     ("Type".to_owned(), PdfObject::name("Page")),
14///     ("Parent".to_owned(), PdfObject::Ref(2)),
15///     ("Rotate".to_owned(), PdfObject::Null),
16/// ]);
17/// assert_eq!(page.repr()?, b"<< /Type /Page /Parent 2 0 R /Rotate null >>");
18/// # Ok::<(), pltrs_render::VectorError>(())
19/// ```
20#[derive(Clone, Debug, PartialEq)]
21pub enum Obj {
22    /// `null`.
23    Null,
24    /// `true` / `false`.
25    Bool(bool),
26    /// An integer.
27    Int(i64),
28    /// A real number (written with up to ten decimals).
29    Real(f64),
30    /// A name (`/Name`).
31    Name(String),
32    /// A literal string.
33    Str(Vec<u8>),
34    /// An array.
35    Array(Vec<Obj>),
36    /// A dictionary with keys in insertion order.
37    Dict(Vec<(String, Obj)>),
38    /// An indirect reference (`12 0 R`).
39    Ref(u32),
40    /// Objects separated by spaces without brackets (how a `Bbox` is
41    /// written: `x y width height`).
42    Seq(Vec<Obj>),
43    /// Bytes written as they are: operators and path data.
44    Raw(Vec<u8>),
45}
46
47impl Obj {
48    /// A name object.
49    pub fn name(name: impl Into<String>) -> Self {
50        Self::Name(name.into())
51    }
52
53    /// An operator.
54    pub fn op(op: &str) -> Self {
55        Self::Raw(op.as_bytes().to_vec())
56    }
57
58    /// A dictionary from `(key, value)` pairs.
59    pub(super) fn dict<const N: usize>(entries: [(&str, Obj); N]) -> Self {
60        Self::Dict(
61            entries
62                .into_iter()
63                .map(|(k, v)| (k.to_owned(), v))
64                .collect(),
65        )
66    }
67
68    /// An array of reals.
69    pub(super) fn reals(values: impl IntoIterator<Item = f64>) -> Self {
70        Self::Array(values.into_iter().map(Self::Real).collect())
71    }
72
73    /// The object in PDF syntax (matplotlib's `pdfRepr`): reals with up to
74    /// ten decimals, containers filled into lines under 75 columns.
75    ///
76    /// # Errors
77    ///
78    /// When a number is not finite, which PDF cannot write.
79    pub fn repr(&self) -> Result<Vec<u8>, VectorError> {
80        Ok(match self {
81            Self::Null => b"null".to_vec(),
82            Self::Bool(b) => {
83                if *b {
84                    b"true".to_vec()
85                } else {
86                    b"false".to_vec()
87                }
88            }
89            Self::Int(i) => i.to_string().into_bytes(),
90            Self::Real(r) => {
91                if !r.is_finite() {
92                    return Err(VectorError::NonFinite("number in a PDF"));
93                }
94                trimmed(*r, 10).into_bytes()
95            }
96            Self::Name(name) => name_repr(name),
97            Self::Str(bytes) => string_repr(bytes),
98            Self::Array(items) => {
99                let mut parts = vec![b"[".to_vec()];
100                for item in items {
101                    parts.push(item.repr()?);
102                }
103                parts.push(b"]".to_vec());
104                fill(&parts)
105            }
106            Self::Dict(entries) => {
107                let mut parts = vec![b"<<".to_vec()];
108                for (key, value) in entries {
109                    let mut part = name_repr(key);
110                    part.push(b' ');
111                    part.extend(value.repr()?);
112                    parts.push(part);
113                }
114                parts.push(b">>".to_vec());
115                fill(&parts)
116            }
117            Self::Ref(id) => format!("{id} 0 R").into_bytes(),
118            Self::Seq(items) => fill(&items.iter().map(Obj::repr).collect::<Result<Vec<_>, _>>()?),
119            Self::Raw(bytes) => bytes.clone(),
120        })
121    }
122}
123
124/// A name: bytes outside `!`–`~` as `#xx` (matplotlib's `Name`).
125fn name_repr(name: &str) -> Vec<u8> {
126    let mut out = vec![b'/'];
127    for c in name.chars() {
128        match u32::from(c) {
129            0x21..=0x7e => out.push(c as u8),
130            code => out.extend(format!("#{:02x}", code & 0xff).into_bytes()),
131        }
132    }
133    out
134}
135
136/// A literal string with backslashes, parentheses and line breaks
137/// escaped.
138fn string_repr(bytes: &[u8]) -> Vec<u8> {
139    let mut out = Vec::with_capacity(bytes.len() + 2);
140    out.push(b'(');
141    for &b in bytes {
142        match b {
143            b'\\' => out.extend_from_slice(b"\\\\"),
144            b'(' => out.extend_from_slice(b"\\("),
145            b')' => out.extend_from_slice(b"\\)"),
146            b'\n' => out.extend_from_slice(b"\\n"),
147            b'\r' => out.extend_from_slice(b"\\r"),
148            _ => out.push(b),
149        }
150    }
151    out.push(b')');
152    out
153}
154
155/// A string as `pdfRepr` writes Python text: ASCII as is, anything else
156/// as UTF-16BE with a byte-order mark.
157///
158/// ```
159/// use pltrs_render::{PdfObject, pdf_text_string};
160/// assert_eq!(pdf_text_string("ab"), PdfObject::Str(b"ab".to_vec()));
161/// assert_eq!(pdf_text_string("é"), PdfObject::Str(vec![0xfe, 0xff, 0, 0xe9]));
162/// ```
163pub fn text_string(text: &str) -> Obj {
164    if text.is_ascii() {
165        Obj::Str(text.as_bytes().to_vec())
166    } else {
167        let mut bytes = vec![0xfe, 0xff];
168        for unit in text.encode_utf16() {
169            bytes.extend_from_slice(&unit.to_be_bytes());
170        }
171        Obj::Str(bytes)
172    }
173}
174
175/// One line of `objects` as matplotlib's `PdfFile.output` writes it: their
176/// syntax joined by `_fill`, then a newline.
177///
178/// ```
179/// use pltrs_render::{PdfObject, pdf_line};
180/// assert_eq!(pdf_line(&[PdfObject::Int(1), PdfObject::name("j")]).unwrap(), b"1 /j\n");
181/// ```
182///
183/// # Errors
184///
185/// When an object holds a non-finite number.
186pub fn line(objects: &[Obj]) -> Result<Vec<u8>, VectorError> {
187    let parts = objects
188        .iter()
189        .map(Obj::repr)
190        .collect::<Result<Vec<_>, _>>()?;
191    let mut line = fill(&parts);
192    line.push(b'\n');
193    Ok(line)
194}
195
196/// `_fill`: joins `parts` with spaces, breaking lines before a part that
197/// would reach 75 columns.
198pub(super) fn fill(parts: &[Vec<u8>]) -> Vec<u8> {
199    const LINE: usize = 75;
200    let mut lines: Vec<Vec<u8>> = Vec::new();
201    let (mut position, mut start) = (0, 0);
202    for (i, part) in parts.iter().enumerate() {
203        if position + part.len() < LINE {
204            position += part.len() + 1;
205        } else {
206            lines.push(parts[start..i].join(&b' '));
207            start = i;
208            position = part.len();
209        }
210    }
211    lines.push(parts[start..].join(&b' '));
212    lines.join(&b'\n')
213}
214
215#[cfg(test)]
216mod tests {
217    use super::*;
218
219    fn text(obj: &Obj) -> String {
220        String::from_utf8(obj.repr().unwrap()).unwrap()
221    }
222
223    #[test]
224    fn scalars() {
225        assert_eq!(text(&Obj::Real(31.0 / 255.0)), "0.1215686275");
226        assert_eq!(text(&Obj::Real(-0.0)), "-0");
227        assert_eq!(text(&Obj::Real(460.8)), "460.8");
228        assert_eq!(text(&Obj::Int(42)), "42");
229        assert_eq!(text(&Obj::name("A b#")), "/A#20b#");
230        assert_eq!(text(&Obj::Str(b"a(b)\\\n".to_vec())), "(a\\(b\\)\\\\\\n)");
231        assert_eq!(text(&Obj::Ref(3)), "3 0 R");
232        assert!(Obj::Real(f64::NAN).repr().is_err());
233        assert_eq!(text_string("é"), Obj::Str(vec![0xfe, 0xff, 0, 0xe9]));
234    }
235
236    #[test]
237    fn containers_fill_lines() {
238        let dict = Obj::dict([
239            ("Type", Obj::name("Page")),
240            ("MediaBox", Obj::reals([0.0, 0.0, 460.8, 345.6])),
241        ]);
242        assert_eq!(
243            text(&dict),
244            "<< /Type /Page /MediaBox [ 0 0 460.8 345.6 ] >>"
245        );
246        let long = vec![b"x".repeat(80)];
247        assert_eq!(fill(&long), [b"\n".to_vec(), b"x".repeat(80)].concat());
248        let words: Vec<Vec<u8>> = (0..30).map(|i| format!("w{i:02}").into_bytes()).collect();
249        let filled = String::from_utf8(fill(&words)).unwrap();
250        assert!(filled.lines().all(|line| line.len() < 75));
251        assert_eq!(filled.lines().count(), 2);
252    }
253}