lopdf 0.47.0

A Rust library for PDF document manipulation.
Documentation
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
use super::Object;

#[cfg(feature = "chrono")]
mod chrono_impl {
    use crate::Object;
    use crate::datetime::{date_literal, date_with_offset};
    use chrono::prelude::*;

    impl From<DateTime<FixedOffset>> for Object {
        fn from(date: DateTime<FixedOffset>) -> Self {
            date_with_offset(date.format("D:%Y%m%d%H%M%S%:z'").to_string())
        }
    }

    impl From<DateTime<Utc>> for Object {
        fn from(date: DateTime<Utc>) -> Self {
            date_literal(date.format("D:%Y%m%d%H%M%SZ").to_string())
        }
    }

    /// A PDF date states a fixed offset from UT and never a named zone
    /// (ISO 32000-1, 7.9.4), so this is the conversion that keeps what the
    /// file said. Re-expressing it in the machine's own zone is what the
    /// `chrono-clock` feature adds.
    impl TryFrom<super::DateTime> for DateTime<FixedOffset> {
        type Error = chrono::format::ParseError;

        fn try_from(value: super::DateTime) -> Result<DateTime<FixedOffset>, Self::Error> {
            let from_date = |date: NaiveDate| {
                FixedOffset::east_opt(0)
                    .unwrap()
                    .from_utc_datetime(&date.and_time(NaiveTime::from_hms_opt(0, 0, 0).unwrap()))
            };

            // A date without the UT offset is GMT, like a date without a time of day.
            let from_utc = |date: NaiveDateTime| FixedOffset::east_opt(0).unwrap().from_utc_datetime(&date);

            DateTime::parse_from_str(&value.0, "%Y%m%d%H%M%S%#z")
                .or_else(|_| DateTime::parse_from_str(&value.0, "%Y%m%d%H%M%#z"))
                .or_else(|_| NaiveDateTime::parse_from_str(&value.0, "%Y%m%d%H%M%S").map(from_utc))
                .or_else(|_| NaiveDateTime::parse_from_str(&value.0, "%Y%m%d%H%M").map(from_utc))
                .or_else(|_| NaiveDate::parse_from_str(&value.0, "%Y%m%d").map(from_date))
        }
    }
}

/// The system-local conversions, kept apart from `chrono` because `Local`
/// exists only with chrono's `clock` feature — which brings `iana-time-zone`
/// and its per-platform chain. A PDF date never names a zone, so a consumer
/// that does not want the reading machine's offset applied to someone else's
/// document can have dates for `chrono` and `num-traits` alone.
#[cfg(feature = "chrono-clock")]
mod chrono_clock_impl {
    use crate::Object;
    use crate::datetime::date_with_offset;
    use chrono::prelude::*;

    impl From<DateTime<Local>> for Object {
        fn from(date: DateTime<Local>) -> Self {
            date_with_offset(date.format("D:%Y%m%d%H%M%S%:z'").to_string())
        }
    }

    impl TryFrom<super::DateTime> for DateTime<Local> {
        type Error = chrono::format::ParseError;

        fn try_from(value: super::DateTime) -> Result<DateTime<Local>, Self::Error> {
            DateTime::<FixedOffset>::try_from(value).map(|date| date.with_timezone(&Local))
        }
    }
}

#[cfg(feature = "jiff")]
mod jiff_impl {
    use crate::Object;
    use crate::datetime::{date_literal, date_with_offset};
    use jiff::{Timestamp, Zoned};

    impl From<Zoned> for Object {
        fn from(date: Zoned) -> Self {
            date_with_offset(date.strftime("D:%Y%m%d%H%M%S%:z'").to_string())
        }
    }

    impl From<Timestamp> for Object {
        fn from(date: Timestamp) -> Self {
            date_literal(date.strftime("D:%Y%m%d%H%M%SZ").to_string())
        }
    }

    impl TryFrom<super::DateTime> for Zoned {
        type Error = jiff::Error;

        fn try_from(value: super::DateTime) -> Result<Self, Self::Error> {
            use jiff::civil::{Date, DateTime};

            // Date formats from PDF 32000-1:2008 §7.9.4. Per the spec, a plus/minus O field
            // means local time is later/earlier than UT, a `Z` means equal to UT, and a missing
            // offset means GMT. Formats are tried in order, each more lenient than the last,
            // and a `Zoned` is always returned to preserve the timezone.
            Zoned::strptime("%Y%m%d%H%M%S%#z", &value.0)
                .or_else(|_| DateTime::strptime("%Y%m%d%H%M%SZ", &value.0).and_then(|dt| dt.in_tz("UTC")))
                .or_else(|_| Zoned::strptime("%Y%m%d%H%M%#z", &value.0))
                .or_else(|_| DateTime::strptime("%Y%m%d%H%MZ", &value.0).and_then(|dt| dt.in_tz("UTC")))
                .or_else(|_| DateTime::strptime("%Y%m%d%H%M%S", &value.0).and_then(|dt| dt.in_tz("GMT")))
                .or_else(|_| DateTime::strptime("%Y%m%d%H%M", &value.0).and_then(|dt| dt.in_tz("GMT")))
                .or_else(|_| Date::strptime("%Y%m%d", &value.0).and_then(|dt| dt.at(0, 0, 0, 0).in_tz("GMT")))
        }
    }
}

#[cfg(feature = "time")]
mod time_impl {
    use super::date_literal;
    use crate::Object;
    use time::{OffsetDateTime, PrimitiveDateTime};

    /// The naive datetime is taken to be UTC and rendered with the `Z` suffix
    /// (PDF 32000-1 §7.9.4) — the `time`-crate counterpart of the
    /// `chrono::DateTime<Utc>` and `jiff::Timestamp` impls above.
    ///
    /// (This replaces a `From<time::Time>` impl that never compiled — see
    /// issue #518: it referenced a nonexistent `FormatItem::StringLiteral`
    /// with a strftime pattern, and a bare time-of-day cannot form a valid
    /// PDF date anyway, which must start at the year.)
    impl From<PrimitiveDateTime> for Object {
        fn from(date: PrimitiveDateTime) -> Self {
            // D:%Y%m%d%H%M%SZ
            let format =
                time::format_description::parse_borrowed::<3>("D:[year][month][day][hour][minute][second]Z").unwrap();
            date_literal(date.format(&format).unwrap())
        }
    }

    impl From<OffsetDateTime> for Object {
        fn from(date: OffsetDateTime) -> Self {
            // The `time` crate spells PDF's offset separator directly (the
            // literal `'` in the format), so unlike chrono/jiff there is no
            // `:` to fix up and the bytes are already correct.
            let format = time::format_description::parse_borrowed::<3>(
                "D:[year][month][day][hour][minute][second][offset_hour sign:mandatory]'[offset_minute]'",
            )
            .unwrap();
            date_literal(date.format(&format).unwrap())
        }
    }

    /// WARNING: `tm_wday` (weekday), `tm_yday` (day index in year), `tm_isdst`
    /// (daylight saving time) and `tm_nsec` (nanoseconds of the date from 1970)
    /// are set to 0 since they aren't available in the PDF time format. They could,
    /// however, be calculated manually
    impl TryFrom<super::DateTime> for OffsetDateTime {
        type Error = time::Error;

        fn try_from(value: super::DateTime) -> Result<OffsetDateTime, Self::Error> {
            use time::format_description::parse_borrowed;
            use time::{Date, PrimitiveDateTime};

            // A `Z` means the time is UT (PDF 32000-1 §7.9.4).
            let text = match value.0.strip_suffix('Z') {
                Some(text) => format!("{text}+0000"),
                None => value.0,
            };
            let parse = |format: &str| -> Result<OffsetDateTime, Self::Error> {
                Ok(OffsetDateTime::parse(&text, &parse_borrowed::<3>(format)?)?)
            };

            // A date without the UT offset is GMT, like a date without a time of day.
            let parse_utc = |format: &str| -> Result<OffsetDateTime, Self::Error> {
                Ok(PrimitiveDateTime::parse(&text, &parse_borrowed::<3>(format)?)?.assume_utc())
            };

            // Like the chrono and jiff conversions, also accept a date without seconds, without
            // the UT offset or without a time of day.
            parse("[year][month][day][hour][minute][second][offset_hour sign:mandatory][offset_minute]")
                .or_else(|_| parse("[year][month][day][hour][minute][offset_hour sign:mandatory][offset_minute]"))
                .or_else(|_| parse_utc("[year][month][day][hour][minute][second]"))
                .or_else(|_| parse_utc("[year][month][day][hour][minute]"))
                .or_else(|_| {
                    let date = Date::parse(&text, &parse_borrowed::<3>("[year][month][day]")?)?;
                    Ok(date.midnight().assume_utc())
                })
        }
    }
}

/// A PDF date carrying a fixed UTC offset: `D:YYYYMMDDHHMMSS+HH'mm'`
/// (ISO 32000-1, 7.9.4). The offset uses an apostrophe where the common
/// `%z`/`%:z` conventions use a colon, so the raw formatted bytes need
/// fixing up.
#[cfg(any(feature = "chrono", feature = "jiff"))]
fn date_with_offset(text: String) -> Object {
    let mut bytes = text.into_bytes();
    convert_utc_offset(&mut bytes);
    Object::string_literal(bytes)
}

/// Wrap date text that is already in PDF form. Use this for a date at UTC
/// (`D:YYYYMMDDHHMMSSZ`) and for the `time` crate's offset form, which spells
/// the `'` separator itself; only [`date_with_offset`] needs the fixup.
#[cfg(any(feature = "chrono", feature = "jiff", feature = "time"))]
fn date_literal(text: String) -> Object {
    Object::string_literal(text)
}

// Find the last `:` and turn it into an `'` to account for PDF weirdness
#[allow(dead_code)]
fn convert_utc_offset(bytes: &mut [u8]) {
    let mut index = bytes.len();
    while let Some(last) = bytes[..index].last_mut() {
        if *last == b':' {
            *last = b'\'';
            break;
        }
        index -= 1;
    }
}

#[derive(Clone, Debug)]
pub struct DateTime(String);

impl Object {
    // Parses the `D`, `:` and `\` out of a `Object::String` to parse the date time
    fn datetime_string(&self) -> Option<String> {
        if let Object::String(bytes, _) = self {
            String::from_utf8(bytes.iter().filter(|b| !b"D:'".contains(b)).cloned().collect()).ok()
        } else {
            None
        }
    }

    pub fn as_datetime(&self) -> Option<DateTime> {
        self.datetime_string().map(DateTime)
    }
}

impl DateTime {
    /// The date's characters with `D`, `:` and `'` removed.
    ///
    /// Every typed conversion of this value needs a date backend — `chrono`,
    /// `jiff` or `time` — but [`Object::as_datetime`] itself needs none. A
    /// build that enables no backend could therefore obtain a `DateTime` and
    /// have no way to read it. This is that way.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

#[test]
fn a_datetime_is_readable_without_a_backend() {
    let text = Object::string_literal("D:20260710143000+02'00'");
    // The `D`, `:` and apostrophes are filtered out on the way in; the
    // relation sign survives, because it is what the offset means.
    assert_eq!(text.as_datetime().unwrap().as_str(), "20260710143000+0200");
    assert!(Object::Integer(20260710).as_datetime().is_none());
}

#[cfg(feature = "chrono")]
#[test]
fn parse_datetime_fixed_offset_keeps_the_offset_the_file_stated() {
    use chrono::prelude::*;

    let text = Object::string_literal("D:20260710143000+02'00'");
    let date: DateTime<FixedOffset> = text.as_datetime().unwrap().try_into().unwrap();
    // Not shifted into UTC, and not into the reading machine's zone either.
    assert_eq!(date.offset().local_minus_utc(), 2 * 3600);
    assert_eq!(date.hour(), 14);
    // And it round-trips back to the same text.
    let back: Object = date.into();
    assert_eq!(back, Object::string_literal("D:20260710143000+02'00'"));
}

#[cfg(feature = "chrono")]
#[test]
fn parse_datetime_fixed_offset_round_trip() {
    use chrono::prelude::*;

    // A fixed instant: `Utc::now` needs chrono's `clock` feature, which this row lacks.
    let time = FixedOffset::east_opt(-5 * 3600 - 30 * 60)
        .unwrap()
        .with_ymd_and_hms(2026, 7, 10, 14, 30, 0)
        .unwrap();
    let text: Object = time.into();
    let time2: Option<DateTime<FixedOffset>> = text.as_datetime().and_then(|dt| dt.try_into().ok());
    assert_eq!(time2, Some(time));
}

#[cfg(feature = "chrono-clock")]
#[test]
fn parse_datetime_local() {
    use chrono::prelude::*;

    let time = Local::now().with_nanosecond(0).unwrap();
    let text: Object = time.into();
    let time2: Option<DateTime<Local>> = text.as_datetime().and_then(|dt| dt.try_into().ok());
    assert_eq!(time2, Some(time));
}

#[cfg(feature = "chrono")]
#[test]
fn parse_datetime_utc() {
    use chrono::prelude::*;

    let time = Utc.with_ymd_and_hms(2026, 7, 10, 14, 30, 0).unwrap();
    let text: Object = time.into();
    let time2: Option<DateTime<FixedOffset>> = text.as_datetime().and_then(|dt| dt.try_into().ok());
    assert_eq!(time2, Some(time.fixed_offset()));
}

#[cfg(feature = "jiff")]
#[test]
fn parse_zoned() {
    use jiff::Zoned;

    let time = Zoned::now().with().subsec_nanosecond(0).build().unwrap();
    let text: Object = time.clone().into();
    let time2: Option<Zoned> = text.as_datetime().and_then(|dt| dt.try_into().ok());
    assert_eq!(time2, Some(time));
}

#[cfg(feature = "jiff")]
#[test]
fn parse_timestamp() {
    use jiff::Zoned;

    let time = Zoned::now().with().subsec_nanosecond(0).build().unwrap();
    let text: Object = time.timestamp().into();
    let time2: Option<Zoned> = text.as_datetime().and_then(|dt| dt.try_into().ok());
    assert_eq!(time2, Some(time));
}

#[cfg(feature = "chrono")]
#[test]
fn parse_datetime_seconds_missing_chrono() {
    use chrono::prelude::*;

    // this is the example from the PDF reference, version 1.7, chapter 3.8.3
    let text = Object::string_literal("D:199812231952-08'00'");
    let dt: Option<DateTime<FixedOffset>> = text.as_datetime().and_then(|dt| dt.try_into().ok());
    assert!(dt.is_some());
}

#[cfg(feature = "chrono")]
#[test]
fn parse_datetime_time_missing_chrono() {
    use chrono::prelude::*;

    let text = Object::string_literal("D:20040229");
    let dt: Option<DateTime<FixedOffset>> = text.as_datetime().and_then(|dt| dt.try_into().ok());
    assert!(dt.is_some());
}

#[cfg(feature = "jiff")]
#[test]
fn parse_datetime_seconds_missing_jiff() {
    use jiff::Zoned;

    // this is the example from the PDF reference, version 1.7, chapter 3.8.3
    let text = Object::string_literal("D:199812231952-08'00'");
    let dt: Option<Zoned> = text.as_datetime().and_then(|dt| dt.try_into().ok());
    assert!(dt.is_some());
}

#[cfg(feature = "jiff")]
#[test]
fn parse_datetime_time_missing_jiff() {
    use jiff::Zoned;

    let text = Object::string_literal("D:20040229");
    let dt: Option<Zoned> = text.as_datetime().and_then(|dt| dt.try_into().ok());
    assert!(dt.is_some());
}

#[cfg(feature = "time")]
#[test]
fn format_primitive_datetime_as_utc() {
    use time::{Date, Month, PrimitiveDateTime, Time};

    // The example date from the PDF reference (1.7, §3.8.3), as a naive
    // datetime: it must serialize with the year first and the `Z` suffix.
    let date = Date::from_calendar_date(1998, Month::December, 23).unwrap();
    let time = Time::from_hms(19, 52, 0).unwrap();
    let text: Object = PrimitiveDateTime::new(date, time).into();
    match &text {
        Object::String(bytes, _) => assert_eq!(bytes.as_slice(), b"D:19981223195200Z"),
        other => panic!("expected a string literal, got {other:?}"),
    }
}

#[cfg(feature = "time")]
#[test]
fn parse_datetime() {
    use time::OffsetDateTime;

    let time = OffsetDateTime::now_utc();

    let text: Object = time.into();
    let time2: OffsetDateTime = text.as_datetime().unwrap().try_into().unwrap();

    assert_eq!(time2.date(), time.date());

    // Ignore nanoseconds
    // - not important in the date parsing
    assert_eq!(time2.time().hour(), time.time().hour());
    assert_eq!(time2.time().minute(), time.time().minute());
    assert_eq!(time2.time().second(), time.time().second());
}

#[cfg(feature = "time")]
#[test]
fn parse_datetime_utc_time() {
    use time::{Date, Month, OffsetDateTime, PrimitiveDateTime, Time};

    // The `Z` form written by `From<PrimitiveDateTime>` must parse back.
    let date = Date::from_calendar_date(1998, Month::December, 23).unwrap();
    let time = PrimitiveDateTime::new(date, Time::from_hms(19, 52, 0).unwrap());
    let text: Object = time.into();
    let time2: Option<OffsetDateTime> = text.as_datetime().and_then(|dt| dt.try_into().ok());
    assert_eq!(time2, Some(time.assume_utc()));
}

#[cfg(feature = "time")]
#[test]
fn parse_datetime_seconds_missing_time() {
    use time::{OffsetDateTime, UtcOffset};

    // this is the example from the PDF reference, version 1.7, chapter 3.8.3
    let text = Object::string_literal("D:199812231952-08'00'");
    let dt: OffsetDateTime = text.as_datetime().unwrap().try_into().unwrap();
    assert_eq!((dt.hour(), dt.minute(), dt.second()), (19, 52, 0));
    assert_eq!(dt.offset(), UtcOffset::from_hms(-8, 0, 0).unwrap());
}

#[cfg(feature = "time")]
#[test]
fn parse_datetime_time_missing_time() {
    use time::{Date, Month, OffsetDateTime};

    let text = Object::string_literal("D:20040229");
    let dt: OffsetDateTime = text.as_datetime().unwrap().try_into().unwrap();
    let date = Date::from_calendar_date(2004, Month::February, 29).unwrap();
    assert_eq!(dt, date.midnight().assume_utc());
}

/// A date without the UT offset is read as GMT, as a date without a time of day
/// already is. Producers often leave the offset out.
#[cfg(feature = "chrono")]
#[test]
fn parse_datetime_offset_missing_chrono() {
    use chrono::prelude::*;

    let expected = Utc.with_ymd_and_hms(2024, 1, 15, 12, 30, 45).unwrap().fixed_offset();
    let text = Object::string_literal("D:20240115123045");
    let dt: Option<DateTime<FixedOffset>> = text.as_datetime().and_then(|dt| dt.try_into().ok());
    assert_eq!(dt, Some(expected));

    let expected = Utc.with_ymd_and_hms(2024, 1, 15, 12, 30, 0).unwrap().fixed_offset();
    let text = Object::string_literal("D:202401151230");
    let dt: Option<DateTime<FixedOffset>> = text.as_datetime().and_then(|dt| dt.try_into().ok());
    assert_eq!(dt, Some(expected));
}

#[cfg(feature = "jiff")]
#[test]
fn parse_datetime_offset_missing_jiff() {
    use jiff::{Timestamp, Zoned};

    let text = Object::string_literal("D:20240115123045");
    let dt: Option<Zoned> = text.as_datetime().and_then(|dt| dt.try_into().ok());
    let expected: Timestamp = "2024-01-15T12:30:45Z".parse().unwrap();
    assert_eq!(dt.map(|dt| dt.timestamp()), Some(expected));

    let text = Object::string_literal("D:202401151230");
    let dt: Option<Zoned> = text.as_datetime().and_then(|dt| dt.try_into().ok());
    let expected: Timestamp = "2024-01-15T12:30:00Z".parse().unwrap();
    assert_eq!(dt.map(|dt| dt.timestamp()), Some(expected));
}

#[cfg(feature = "time")]
#[test]
fn parse_datetime_offset_missing_time() {
    use time::{Date, Month, OffsetDateTime, Time};

    let date = Date::from_calendar_date(2024, Month::January, 15).unwrap();

    let text = Object::string_literal("D:20240115123045");
    let dt: Option<OffsetDateTime> = text.as_datetime().and_then(|dt| dt.try_into().ok());
    let expected = date.with_time(Time::from_hms(12, 30, 45).unwrap()).assume_utc();
    assert_eq!(dt, Some(expected));

    let text = Object::string_literal("D:202401151230");
    let dt: Option<OffsetDateTime> = text.as_datetime().and_then(|dt| dt.try_into().ok());
    let expected = date.with_time(Time::from_hms(12, 30, 0).unwrap()).assume_utc();
    assert_eq!(dt, Some(expected));
}