printpdf 0.13.0

Rust library for reading and writing PDF files
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
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
//! Form XObjects read from a PDF.
//!
//! A form XObject (ISO 32000-1, 8.10) is a content stream with a `/BBox`, a `/Matrix` and
//! `/Resources` of its own. Pages that macOS (Quartz), Word or a print driver write put the whole
//! page into one form: the page's content stream is `q ... /Fm1 Do Q` and the text is in the
//! form. [`parse_form`] reads such a form into an [`XObject::Form`]: the operators of its content
//! stream become [`Op`]s, and its `/Resources` are read by the functions that read the resources
//! of a page, into a scope of its own. A name in the form never clashes with a name on the page.
//!
//! A form is modelled only when writing it again from the model loses nothing. Otherwise it stays
//! an [`XObject::External`], byte for byte, and an info message says why. That is the case when
//!
//! - its dictionary or its `/Resources` has an entry that is not in ISO 32000-1,
//! - its content stream cannot be decoded or split into operators, uses an operator that has no
//!   [`Op`], or sets a pattern that its own resources do not have,
//! - it selects a font that has no font program, for example a Type 3 font,
//! - or it has no `/BBox`.
//!
//! What the model has no field for but ISO 32000-1 names (`/ColorSpace`,
//! `/Properties`, `/ProcSet`, `/Group` attributes, `/OC`, `/Metadata`, ...) is kept in
//! [`FormXObject::extra`] and written back.
//!
//! Each form object is read once, however many names or pages refer to it. Reading stops at
//! [`MAX_FORM_DEPTH`] nested forms, at a form that is its own ancestor, and when a document has
//! more than [`MAX_FORMS`] forms or more than [`MAX_FORM_CONTENT_BYTES`] bytes of form content:
//! the form that is not read stays as it is.

use std::{
    collections::{BTreeMap, BTreeSet},
    sync::Arc,
};

use lopdf::{
    Dictionary as LopdfDictionary, Document as LopdfDocument, Object, ObjectId, Stream as LopdfStream,
};

use super::pattern::{pattern_space_names, read_scope_patterns, PatternCtx};
use super::{
    convert_operations, decode_content, decode_limited, dictitem_from_lopdf_resolved, font_resources,
    get_dict_or_resolve_ref, parse_rect, parse_xobjects_internal, parsefont, read_extgstates,
    read_shadings, warn_if_budget_spent, Decoded, FontTextDecodeKind, InlineBudget,
    ParsedOrBuiltinFont, PdfWarnMsg, PendingXObject, MAX_STREAM_BYTES,
};
use crate::{
    form_walk::MAX_FORM_DEPTH,
    matrix::CurTransMat,
    ops::PdfFontHandle,
    xobject::{FormType, FormXObject, GroupXObject, GroupXObjectType},
    DictItem, ExtendedGraphicsState, ExtendedGraphicsStateId, ExtendedGraphicsStateMap, FontId, Op,
    Pattern, PatternId, PatternMap, PdfFontMap, PdfLayerMap, PdfResources, Shading, ShadingId,
    ShadingMap, XObjectId, XObjectMap,
};

/// Most forms that are read from one document; the others stay as they are.
const MAX_FORMS: usize = 100_000;

/// Most bytes of decoded content that the forms of one document are read from.
const MAX_FORM_CONTENT_BYTES: usize = 256 * 1024 * 1024;

/// The entries of a form's dictionary that are read, or kept in [`FormXObject::extra`].
const FORM_KEYS: &[&[u8]] = &[
    b"Type",
    b"Subtype",
    b"FormType",
    b"BBox",
    b"Matrix",
    b"Resources",
    b"Group",
    b"Ref",
    b"Metadata",
    b"PieceInfo",
    b"LastModified",
    b"StructParent",
    b"StructParents",
    b"OPI",
    b"OC",
    b"Name",
    b"Length",
    b"Filter",
    b"DecodeParms",
    b"Measure",
    b"PtData",
    b"AF",
];

/// The entries of a form's dictionary that are kept as they are, in [`FormXObject::extra`].
const EXTRA_KEYS: &[&str] = &[
    "Ref",
    "Metadata",
    "PieceInfo",
    "LastModified",
    "OPI",
    "OC",
    "Measure",
    "PtData",
    "AF",
];

/// The resource categories of ISO 32000-1, 7.8.3.
const RESOURCE_KEYS: &[&[u8]] = &[
    b"Font",
    b"XObject",
    b"ExtGState",
    b"Shading",
    b"ColorSpace",
    b"Pattern",
    b"Properties",
    b"ProcSet",
];

/// The resource categories that have no typed map, which are kept as they are.
const RAW_CATEGORIES: &[&str] = &["ColorSpace", "Properties", "ProcSet"];

/// A form that is read, whose nested XObjects may still wait to be decoded.
#[derive(Clone)]
pub(crate) struct PendingForm {
    /// The form, with the resources of its scope except its XObjects.
    pub(crate) form: FormXObject,
    /// The XObjects of the form's scope.
    pub(crate) xobjects: BTreeMap<XObjectId, PendingXObject>,
}

/// What reading the XObjects of one document keeps from one XObject to the next.
pub(crate) struct XObjectCtx<'a> {
    /// What is left of the budget for the references that are copied into preserved XObjects.
    pub(super) budget: InlineBudget,
    /// How the text of the document's fonts decodes: the scope of a form without `/Resources`.
    font_decode: &'a BTreeMap<String, FontTextDecodeKind>,
    /// The forms that are read already, by object. An `Err` is the reason a form is not modelled.
    /// A form that is used again is shared, not copied.
    cache: BTreeMap<ObjectId, Result<Arc<PendingForm>, String>>,
    /// The forms being read, outermost first.
    stack: Vec<ObjectId>,
    forms_left: usize,
    bytes_left: usize,
    reported_budget: bool,
    /// What reading the patterns of the forms keeps from one pattern to the next.
    patterns: PatternCtx,
}

impl<'a> XObjectCtx<'a> {
    pub(crate) fn new(font_decode: &'a BTreeMap<String, FontTextDecodeKind>) -> Self {
        XObjectCtx {
            budget: InlineBudget::new(),
            font_decode,
            cache: BTreeMap::new(),
            stack: Vec::new(),
            forms_left: MAX_FORMS,
            bytes_left: MAX_FORM_CONTENT_BYTES,
            reported_budget: false,
            patterns: PatternCtx::new(),
        }
    }
}

/// Reads the form XObject `stream`, the entry `value` of an `/XObject` dictionary, under the name
/// `name`. `None` when the form stays as it is (see the module documentation).
pub(super) fn parse_form(
    doc: &LopdfDocument,
    value: &Object,
    stream: &LopdfStream,
    name: &XObjectId,
    page: usize,
    ctx: &mut XObjectCtx<'_>,
    warnings: &mut Vec<PdfWarnMsg>,
) -> Option<Arc<PendingForm>> {
    let id = match value {
        Object::Reference(id) => Some(*id),
        _ => None,
    };
    if let Some(id) = id {
        if let Some(done) = ctx.cache.get(&id) {
            return done.clone().ok();
        }
        if ctx.stack.contains(&id) {
            warnings.push(PdfWarnMsg::info(
                page,
                0,
                format!(
                    "form XObject {} has itself in its resources; that one is kept as it is",
                    name.0
                ),
            ));
            return None;
        }
    }
    if ctx.stack.len() >= MAX_FORM_DEPTH {
        warnings.push(PdfWarnMsg::info(
            page,
            0,
            format!(
                "form XObject {} is nested in more than {MAX_FORM_DEPTH} forms and is kept as it is",
                name.0
            ),
        ));
        return None;
    }
    if ctx.forms_left == 0 || ctx.bytes_left == 0 {
        if !ctx.reported_budget {
            ctx.reported_budget = true;
            warnings.push(PdfWarnMsg::warning(
                page,
                0,
                format!(
                    "the document has more than {MAX_FORMS} forms or {MAX_FORM_CONTENT_BYTES} \
                     bytes of form content; the forms from {} on are kept as they are",
                    name.0
                ),
            ));
        }
        return None;
    }
    ctx.forms_left = ctx.forms_left.saturating_sub(1);

    ctx.stack.extend(id);
    let result = read_form(doc, stream, page, ctx, warnings).map(Arc::new);
    if id.is_some() {
        ctx.stack.pop();
    }
    if let Some(id) = id {
        ctx.cache.insert(id, result.clone());
    }
    match result {
        Ok(form) => {
            warn_if_budget_spent(&mut ctx.budget, name, page, warnings);
            Some(form)
        }
        Err(reason) => {
            warnings.push(PdfWarnMsg::info(
                page,
                0,
                format!("form XObject {} is kept as it is: {reason}", name.0),
            ));
            None
        }
    }
}

/// The form of `stream`, or why it cannot be modelled.
fn read_form(
    doc: &LopdfDocument,
    stream: &LopdfStream,
    page: usize,
    ctx: &mut XObjectCtx<'_>,
    warnings: &mut Vec<PdfWarnMsg>,
) -> Result<PendingForm, String> {
    let dict = &stream.dict;
    if let Some(key) = dict
        .iter()
        .map(|(key, _)| key)
        .find(|key| !FORM_KEYS.contains(&key.as_slice()))
    {
        return Err(format!(
            "its dictionary has the entry /{}, which is not modelled",
            String::from_utf8_lossy(key)
        ));
    }

    let bbox = dict
        .get(b"BBox")
        .ok()
        .and_then(|bbox| parse_rect(deref(doc, bbox)).ok())
        .ok_or_else(|| "it has no usable /BBox".to_string())?;
    let matrix = match dict.get(b"Matrix") {
        Err(_) => None,
        Ok(matrix) => Some(
            parse_matrix(deref(doc, matrix))
                .ok_or_else(|| "its /Matrix is not six numbers".to_string())?,
        ),
    };

    let limit = ctx.bytes_left.min(MAX_STREAM_BYTES);
    let content = match decode_limited(stream, limit) {
        Decoded::Data(data) => data,
        Decoded::Undecodable => return Err("its content stream cannot be decoded".to_string()),
        Decoded::TooLarge => return Err("its content stream is too large".to_string()),
    };
    ctx.bytes_left = ctx.bytes_left.saturating_sub(content.len());
    let operations = decode_content(&content)?;

    // The resources the content names its fonts in: the form's own, or the document's.
    let mut scope = match dict.get(b"Resources") {
        Err(_) => None,
        Ok(resources) => {
            let Some(resources) = get_dict_or_resolve_ref(
                "form /Resources",
                doc,
                resources,
                warnings,
                Some(page),
            ) else {
                return Err("its /Resources is not a dictionary".to_string());
            };
            Some(read_scope(doc, resources, page, ctx, warnings)?)
        }
    };
    let font_decode = match &scope {
        Some(scope) => scope.font_decode(),
        None => ctx.font_decode.clone(),
    };
    let no_pattern_spaces = BTreeSet::new();
    let pattern_spaces = scope
        .as_ref()
        .map_or(&no_pattern_spaces, |scope| &scope.pattern_spaces);
    let ops = convert_operations(
        page,
        &operations,
        &BTreeMap::new(),
        &font_decode,
        pattern_spaces,
        warnings,
    )?;
    let fonts = match scope.as_mut() {
        Some(scope) => font_resources(std::mem::take(&mut scope.fonts).into_iter()),
        None => BTreeMap::new(),
    };
    check_content(
        &ops,
        scope.as_ref().map(|scope| (&fonts, &scope.patterns)),
    )?;

    let mut extra = BTreeMap::new();
    let mut group = None;
    if let Ok(object) = dict.get(b"Group") {
        let item = inline(doc, object, &mut ctx.budget);
        if is_plain_transparency_group(&item) {
            group = Some(GroupXObject {
                group_type: GroupXObjectType::TransparencyGroup,
            });
        } else {
            extra.insert("Group".to_string(), item);
        }
    }
    for key in EXTRA_KEYS {
        if let Ok(object) = dict.get(key.as_bytes()) {
            extra.insert((*key).to_string(), inline(doc, object, &mut ctx.budget));
        }
    }
    let integer = |key: &[u8]| {
        dict.get(key)
            .ok()
            .and_then(|object| deref(doc, object).as_i64().ok())
    };
    let form_name = match dict.get(b"Name").ok().map(|object| deref(doc, object)) {
        Some(Object::String(bytes, _)) | Some(Object::Name(bytes)) => {
            Some(String::from_utf8_lossy(bytes).into_owned())
        }
        _ => None,
    };

    let (resources, xobjects) = match scope {
        None => (None, BTreeMap::new()),
        Some(scope) => {
            if !scope.raw.is_empty() {
                extra.insert("Resources".to_string(), DictItem::Dict { map: scope.raw });
            }
            let resources = PdfResources {
                fonts: PdfFontMap { map: fonts },
                xobjects: XObjectMap::default(),
                extgstates: ExtendedGraphicsStateMap {
                    map: scope.extgstates,
                },
                shadings: ShadingMap { map: scope.shadings },
                patterns: PatternMap { map: scope.patterns },
                layers: PdfLayerMap::default(),
            };
            (Some(resources), scope.xobjects)
        }
    };

    Ok(PendingForm {
        form: FormXObject {
            form_type: FormType::Type1,
            size: None,
            bbox,
            matrix,
            ops,
            resources,
            group,
            ref_dict: None,
            metadata: None,
            piece_info: None,
            last_modified: None,
            struct_parent: integer(b"StructParent"),
            struct_parents: integer(b"StructParents"),
            opi: None,
            oc: None,
            name: form_name,
            extra,
        },
        xobjects,
    })
}

/// The resources of a form, read from its `/Resources` dictionary.
struct FormScope {
    fonts: BTreeMap<FontId, ParsedOrBuiltinFont>,
    xobjects: BTreeMap<XObjectId, PendingXObject>,
    extgstates: BTreeMap<ExtendedGraphicsStateId, ExtendedGraphicsState>,
    shadings: BTreeMap<ShadingId, Shading>,
    patterns: BTreeMap<PatternId, Pattern>,
    /// The names of the `[/Pattern ...]` color spaces of the scope.
    pattern_spaces: BTreeSet<String>,
    /// What the typed maps cannot hold: the categories without one, and the graphics states and
    /// shadings that would lose something.
    raw: BTreeMap<String, DictItem>,
}

impl FormScope {
    /// How the text of each font resource name decodes.
    fn font_decode(&self) -> BTreeMap<String, FontTextDecodeKind> {
        self.fonts
            .iter()
            .map(|(id, font)| (id.0.clone(), font.decode_kind()))
            .collect()
    }
}

/// Reads the resources of one `/Resources` dictionary into a scope: the same functions that read
/// the resources of the pages, applied to this dictionary alone.
fn read_scope(
    doc: &LopdfDocument,
    resources: &LopdfDictionary,
    page: usize,
    ctx: &mut XObjectCtx<'_>,
    warnings: &mut Vec<PdfWarnMsg>,
) -> Result<FormScope, String> {
    if let Some(key) = resources
        .iter()
        .map(|(key, _)| key)
        .find(|key| !RESOURCE_KEYS.contains(&key.as_slice()))
    {
        return Err(format!(
            "its /Resources has the entry /{}, which is not modelled",
            String::from_utf8_lossy(key)
        ));
    }

    let fonts =
        parsefont::parse_fonts_enhanced(doc, resources, warnings, Some(page), &BTreeMap::new());
    let mut xobjects = BTreeMap::new();
    parse_xobjects_internal(doc, resources, warnings, Some(page), &mut xobjects, ctx);
    let extgstates = read_extgstates(doc, resources, page, warnings).unwrap_or_default();
    let mut shadings = BTreeMap::new();
    read_shadings(doc, resources, page, &mut shadings, warnings);

    let mut raw = BTreeMap::new();
    for category in RAW_CATEGORIES {
        if let Ok(object) = resources.get(category.as_bytes()) {
            raw.insert((*category).to_string(), inline(doc, object, &mut ctx.budget));
        }
    }
    keep_lossy_extgstates(doc, resources, &extgstates, &mut ctx.budget, &mut raw);
    keep_unmodelled_shadings(doc, resources, &shadings, &mut ctx.budget, &mut raw);
    let patterns = read_scope_patterns(doc, resources, page, &mut ctx.patterns, warnings)?;
    let pattern_spaces = pattern_space_names(doc, resources);

    Ok(FormScope {
        fonts,
        xobjects,
        extgstates,
        shadings,
        patterns,
        pattern_spaces,
        raw,
    })
}

/// The fonts that have a font program and the patterns of a form's own scope.
type ScopeNames<'a> = (
    &'a BTreeMap<FontId, crate::font::PdfFont>,
    &'a BTreeMap<PatternId, Pattern>,
);

/// Checks that the form is written again as it was read: no operator without an [`Op`], no
/// pattern that the scope does not have, no font that has no font program. `scope` is `None` for
/// a form that uses the fonts and patterns of the document, and else the fonts and the patterns
/// of the form.
fn check_content(ops: &[Op], scope: Option<ScopeNames<'_>>) -> Result<(), String> {
    if ops.iter().any(|op| matches!(op, Op::Unknown { .. })) {
        return Err("its content has an operator that no Op models".to_string());
    }
    for op in ops {
        match op {
            Op::SetFillPattern { id, .. } | Op::SetOutlinePattern { id, .. } => {
                // The patterns of the document are read after the forms.
                match scope {
                    Some((_, patterns)) if patterns.contains_key(id) => {}
                    _ => return Err(format!("its content sets the pattern {}, which it has not", id.0)),
                }
            }
            Op::SetFont {
                font: PdfFontHandle::External(id),
                ..
            } => {
                if let Some((fonts, _)) = scope {
                    if !fonts.contains_key(id) {
                        return Err(format!("it selects the font {}, which has no font program", id.0));
                    }
                }
            }
            _ => {}
        }
    }
    Ok(())
}

/// The object `object` refers to, one level deep.
fn deref<'a>(doc: &'a LopdfDocument, object: &'a Object) -> &'a Object {
    match object {
        Object::Reference(id) => doc.get_object(*id).unwrap_or(object),
        other => other,
    }
}

/// `[a b c d e f]` as a matrix.
fn parse_matrix(object: &Object) -> Option<CurTransMat> {
    let Object::Array(entries) = object else {
        return None;
    };
    let mut matrix = [0.0f32; 6];
    if entries.len() != matrix.len() {
        return None;
    }
    for (slot, entry) in matrix.iter_mut().zip(entries) {
        *slot = match entry {
            Object::Integer(i) => *i as f32,
            Object::Real(r) => *r,
            _ => return None,
        };
    }
    Some(CurTransMat::Raw(matrix))
}

/// A copy of `object` with the references in it resolved, within the budget of the document.
fn inline(doc: &LopdfDocument, object: &Object, budget: &mut InlineBudget) -> DictItem {
    dictitem_from_lopdf_resolved(doc, object, 0, &mut Vec::new(), budget)
}

/// Whether `group` says no more than that the form is a transparency group.
fn is_plain_transparency_group(group: &DictItem) -> bool {
    let DictItem::Dict { map } = group else {
        return false;
    };
    map.keys().all(|key| key == "Type" || key == "S")
        && matches!(map.get("S"), Some(DictItem::Name(name)) if name.as_slice() == b"Transparency")
}

/// The dictionary of the resource category `key`.
fn category_dict<'a>(
    doc: &'a LopdfDocument,
    resources: &'a LopdfDictionary,
    key: &[u8],
) -> Option<&'a LopdfDictionary> {
    let object = resources.get(key).ok()?;
    get_dict_or_resolve_ref("form resources", doc, object, &mut Vec::new(), None)
}

/// Keeps the graphics states that the typed map cannot write again without loss (an entry the
/// model has no field for, such as `/SMask`) as they are.
fn keep_lossy_extgstates(
    doc: &LopdfDocument,
    resources: &LopdfDictionary,
    typed: &BTreeMap<ExtendedGraphicsStateId, ExtendedGraphicsState>,
    budget: &mut InlineBudget,
    raw: &mut BTreeMap<String, DictItem>,
) {
    let Some(category) = category_dict(doc, resources, b"ExtGState") else {
        return;
    };
    let mut kept = BTreeMap::new();
    for (name, state) in typed {
        let Ok(entry) = category.get(name.0.as_bytes()) else {
            continue;
        };
        let Some(source) =
            get_dict_or_resolve_ref("form graphics state", doc, entry, &mut Vec::new(), None)
        else {
            continue;
        };
        let written = crate::graphics::extgstate_to_dict(state);
        if source
            .iter()
            .any(|(key, _)| key.as_slice() != b"Type" && !written.has(key))
        {
            kept.insert(name.0.clone(), inline(doc, entry, budget));
        }
    }
    if !kept.is_empty() {
        raw.insert("ExtGState".to_string(), DictItem::Dict { map: kept });
    }
}

/// Keeps the shadings that the typed map cannot hold, or cannot write again without loss, as they
/// are.
fn keep_unmodelled_shadings(
    doc: &LopdfDocument,
    resources: &LopdfDictionary,
    typed: &BTreeMap<ShadingId, Shading>,
    budget: &mut InlineBudget,
    raw: &mut BTreeMap<String, DictItem>,
) {
    let Some(category) = category_dict(doc, resources, b"Shading") else {
        return;
    };
    let mut kept = BTreeMap::new();
    for (key, entry) in category.iter() {
        let name = String::from_utf8_lossy(key).into_owned();
        let lossy = match typed.get(&ShadingId(name.clone())) {
            None => true,
            Some(shading) => {
                let written = shading.to_dict();
                get_dict_or_resolve_ref("form shading", doc, entry, &mut Vec::new(), None)
                    .is_none_or(|source| source.iter().any(|(key, _)| !written.has(key)))
            }
        };
        if lossy {
            kept.insert(name, inline(doc, entry, budget));
        }
    }
    if !kept.is_empty() {
        raw.insert("Shading".to_string(), DictItem::Dict { map: kept });
    }
}