Skip to main content

pdfrum_edit/
info.rs

1//! The document information dictionary (ISO 32000-1 §14.3.3) and the date
2//! strings it holds (§7.9.4).
3//!
4//! `/Info` hangs off the trailer rather than the catalog, which is the one
5//! thing that makes it different from every other dictionary an edit
6//! touches: a document without one needs a new object *and* a trailer that
7//! names it, and the trailer is built by the writer from the base document's.
8//! [`EditDoc`] carries that one override and the writer reads it back through
9//! `EditDoc::trailer`.
10
11use std::time::{SystemTime, UNIX_EPOCH};
12
13use pdfrum_object::{Dict, Name, ObjRef, Object, PdfString, Resolve, encode_text, names};
14
15use crate::doc::EditDoc;
16
17/// Set or remove one text entry of the document's `/Info` dictionary.
18///
19/// `Some(text)` writes `key` as a text string — `PDFDocEncoding` when every
20/// character has a byte there, otherwise UTF-16BE behind a byte-order mark —
21/// and `None` or an empty string removes the key. A document without an
22/// `/Info` gains one, as a new indirect object the saved trailer names; an
23/// `/Info` that is not a dictionary is replaced by one.
24///
25/// ```
26/// use std::sync::Arc;
27/// use pdfrum_edit::{EditDoc, SaveOptions, save, set_info_entry};
28/// use pdfrum_object::names;
29/// use pdfrum_parser::{LoadOptions, load};
30///
31/// let bytes: Arc<[u8]> = Arc::from(&include_bytes!("../tests/files/hello.pdf")[..]);
32/// let doc = load(bytes, &LoadOptions::default())?;
33/// let mut edit = EditDoc::new(&doc);
34/// set_info_entry(&mut edit, names::TITLE, Some("Hello"));
35///
36/// let mut out = Vec::new();
37/// save(&edit, &SaveOptions::default(), &mut out)?;
38/// let reloaded = load(Arc::from(&out[..]), &LoadOptions::default())?;
39/// let info = reloaded.trailer().dict(names::INFO, &reloaded).expect("an /Info");
40/// assert_eq!(info.text(names::TITLE, &reloaded).as_deref(), Some("Hello"));
41/// # Ok::<(), Box<dyn std::error::Error>>(())
42/// ```
43pub fn set_info_entry(dest: &mut EditDoc<'_>, key: &Name, text: Option<&str>) {
44    let existing = dest.trailer().reference(names::INFO);
45    let mut info = existing
46        .and_then(|r| dest.fetch(r).ok())
47        .as_deref()
48        .and_then(Object::as_dict)
49        .cloned()
50        .unwrap_or_default();
51    match text.filter(|t| !t.is_empty()) {
52        Some(text) => info.insert(
53            key.clone(),
54            Object::Str(PdfString::literal(encode_text(text))),
55        ),
56        None => {
57            info.remove(key);
58        }
59    }
60    store_info(dest, existing, info);
61}
62
63/// Write `info` back where the trailer will find it.
64fn store_info(dest: &mut EditDoc<'_>, existing: Option<ObjRef>, info: Dict) {
65    let object = Object::Dict(info);
66    // A reference the trailer already carries — even one that pointed at
67    // something broken — is reused, so an incremental save appends one object
68    // and the trailer copies through unchanged.
69    if let Some(reference) = existing {
70        dest.replace(reference, object);
71    } else {
72        let reference = dest.add(object);
73        dest.set_info(reference);
74    }
75}
76
77/// `time` as a PDF date string (ISO 32000-1 §7.9.4): `D:YYYYMMDDHHmmSSZ00'00'`,
78/// always in UTC, which is the one zone every reader agrees on.
79///
80/// A time before 1970 reads as the epoch.
81///
82/// ```
83/// use std::time::{Duration, UNIX_EPOCH};
84/// use pdfrum_edit::pdf_date;
85///
86/// assert_eq!(pdf_date(UNIX_EPOCH), "D:19700101000000Z00'00'");
87/// assert_eq!(
88///     pdf_date(UNIX_EPOCH + Duration::from_secs(1_700_000_000)),
89///     "D:20231114221320Z00'00'"
90/// );
91/// ```
92#[must_use]
93pub fn pdf_date(time: SystemTime) -> String {
94    let seconds = time
95        .duration_since(UNIX_EPOCH)
96        .map_or(0, |elapsed| elapsed.as_secs());
97    let days = i64::try_from(seconds / 86_400).unwrap_or(i64::MAX);
98    let second_of_day = seconds % 86_400;
99    let (year, month, day) = civil_from_days(days);
100    format!(
101        "D:{year:04}{month:02}{day:02}{:02}{:02}{:02}Z00'00'",
102        second_of_day / 3600,
103        second_of_day % 3600 / 60,
104        second_of_day % 60
105    )
106}
107
108/// The proleptic Gregorian date `days` after 1970-01-01, as (year, month,
109/// day) — the era arithmetic of Howard Hinnant's `civil_from_days`.
110fn civil_from_days(days: i64) -> (i64, i64, i64) {
111    let shifted = days.saturating_add(719_468);
112    let era = shifted.div_euclid(146_097);
113    let day_of_era = shifted.rem_euclid(146_097);
114    let year_of_era =
115        (day_of_era - day_of_era / 1460 + day_of_era / 36_524 - day_of_era / 146_096) / 365;
116    let day_of_year = day_of_era - (365 * year_of_era + year_of_era / 4 - year_of_era / 100);
117    let shifted_month = (5 * day_of_year + 2) / 153;
118    let day = day_of_year - (153 * shifted_month + 2) / 5 + 1;
119    let month = if shifted_month < 10 {
120        shifted_month + 3
121    } else {
122        shifted_month - 9
123    };
124    let year = year_of_era + era * 400 + i64::from(month <= 2);
125    (year, month, day)
126}
127
128#[cfg(test)]
129mod tests {
130    use std::sync::Arc;
131    use std::time::{Duration, UNIX_EPOCH};
132
133    use pdfrum_object::{Name, ObjRef, Object, Resolve, names};
134    use pdfrum_parser::{Document, LoadOptions, load};
135
136    use super::{civil_from_days, pdf_date, set_info_entry};
137    use crate::doc::EditDoc;
138
139    const PAGE_TREE: &[u8] = b"%PDF-1.7\n\
1401 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n\
1412 0 obj\n<< /Type /Pages /Count 1 /Kids [3 0 R] >>\nendobj\n\
1423 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] >>\nendobj\n";
143
144    fn doc(with_info: bool) -> Document {
145        let mut file = PAGE_TREE.to_vec();
146        file.extend_from_slice(b"4 0 obj\n<< /Title (Old) /Author (Ann) >>\nendobj\n");
147        file.extend_from_slice(if with_info {
148            b"trailer\n<< /Root 1 0 R /Info 4 0 R /Size 5 >>\n"
149        } else {
150            b"trailer\n<< /Root 1 0 R /Size 5 >>\n"
151        });
152        load(Arc::from(file), &LoadOptions::default()).expect("opens")
153    }
154
155    fn info_of(edit: &EditDoc<'_>) -> pdfrum_object::Dict {
156        edit.trailer()
157            .dict(names::INFO, edit)
158            .expect("an /Info the trailer names")
159    }
160
161    #[test]
162    fn an_existing_info_is_edited_in_place() {
163        let base = doc(true);
164        let mut edit = EditDoc::new(&base);
165        set_info_entry(&mut edit, names::TITLE, Some("New"));
166        set_info_entry(&mut edit, names::AUTHOR, None);
167        set_info_entry(&mut edit, names::SUBJECT, Some("\u{7f51}\u{9875}"));
168        assert_eq!(
169            edit.trailer().reference(names::INFO),
170            Some(ObjRef::new(4, 0))
171        );
172        let info = info_of(&edit);
173        assert_eq!(info.text(names::TITLE, &edit).as_deref(), Some("New"));
174        assert!(!info.contains_key(names::AUTHOR));
175        assert_eq!(
176            info.string(names::SUBJECT).map(|s| s.bytes.to_vec()),
177            Some(b"\xFE\xFF\x7F\x51\x98\x75".to_vec()),
178            "outside PDFDocEncoding goes out as UTF-16BE with a mark"
179        );
180    }
181
182    #[test]
183    fn a_document_without_an_info_gains_one_the_trailer_names() {
184        let base = doc(false);
185        let mut edit = EditDoc::new(&base);
186        assert!(!edit.trailer().contains_key(names::INFO));
187        set_info_entry(&mut edit, names::TITLE, Some("T"));
188        set_info_entry(&mut edit, names::CREATOR, Some("C"));
189        let reference = edit.trailer().reference(names::INFO).expect("named");
190        assert!(reference.num > 4, "a fresh object, not a reused number");
191        let info = info_of(&edit);
192        assert_eq!(info.text(names::TITLE, &edit).as_deref(), Some("T"));
193        assert_eq!(info.text(names::CREATOR, &edit).as_deref(), Some("C"));
194        // The second entry landed in the same object as the first.
195        assert_eq!(edit.edited().count(), 1);
196    }
197
198    #[test]
199    fn an_empty_value_removes_and_a_missing_key_removes_nothing() {
200        let base = doc(true);
201        let mut edit = EditDoc::new(&base);
202        set_info_entry(&mut edit, names::TITLE, Some(""));
203        set_info_entry(&mut edit, names::KEYWORDS, None);
204        let info = info_of(&edit);
205        assert!(!info.contains_key(names::TITLE));
206        assert!(!info.contains_key(names::KEYWORDS));
207        assert_eq!(info.text(names::AUTHOR, &edit).as_deref(), Some("Ann"));
208    }
209
210    #[test]
211    fn an_info_that_is_not_a_dictionary_is_replaced() {
212        let mut file = PAGE_TREE.to_vec();
213        file.extend_from_slice(
214            b"4 0 obj\n42\nendobj\ntrailer\n<< /Root 1 0 R /Info 4 0 R /Size 5 >>\n",
215        );
216        let base = load(Arc::from(file), &LoadOptions::default()).expect("opens");
217        let mut edit = EditDoc::new(&base);
218        set_info_entry(&mut edit, &Name::from("Title"), Some("T"));
219        let object = edit.fetch(ObjRef::new(4, 0)).expect("replaced");
220        assert!(matches!(&*object, Object::Dict(d) if d.contains_key(names::TITLE)));
221    }
222
223    #[test]
224    fn dates_are_utc_and_civil() {
225        assert_eq!(pdf_date(UNIX_EPOCH), "D:19700101000000Z00'00'");
226        assert_eq!(
227            pdf_date(UNIX_EPOCH + Duration::from_hours(264_384)),
228            "D:20000229000000Z00'00'",
229            "a century leap day"
230        );
231        assert_eq!(
232            pdf_date(UNIX_EPOCH + Duration::from_hours(474_780)),
233            "D:20240229120000Z00'00'"
234        );
235        assert_eq!(
236            pdf_date(UNIX_EPOCH + Duration::from_secs(4_102_444_799)),
237            "D:20991231235959Z00'00'"
238        );
239        assert_eq!(civil_from_days(0), (1970, 1, 1));
240        assert_eq!(civil_from_days(-1), (1969, 12, 31));
241        assert_eq!(civil_from_days(-719_468), (0, 3, 1));
242    }
243}