printpdf 0.12.12

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
//! Shrinking a finished PDF without changing what it shows or what its text reads as: its
//! pictures encoded again ([`optimize_images`]), and the `/ActualText` its glyphs read as anyway
//! dropped ([`optimize_text`]).

use std::collections::{BTreeMap, BTreeSet};
use std::rc::Rc;

use lopdf::content::{Content, Operation};
use lopdf::{Dictionary, Document, Object, ObjectId, Stream};

use crate::{cmap::ToUnicodeCMap, PdfWarnMsg};
#[cfg(feature = "images")]
use crate::{
    deserialize::raw_bitmap_from_stream, image::image_to_stream, ImageOptimizationOptions,
};

/// The widest `TJ` adjustment (thousandths of an em) between two glyphs that readers still take
/// for one word. A wider gap reads as a space (poppler: a tenth of the font size), so
/// letter-spaced text ("P R E F A C E") keeps its `/ActualText`.
const MAX_KERN: f32 = 100.0;

/// Drops the `/ActualText` of every `/Span` in a finished PDF whose glyphs read as that text
/// anyway (see [`drop_redundant_actual_text`]); everything else is written back as it was. One
/// info message tells how many were dropped and how many kept.
pub fn optimize_text(pdf: &[u8], warnings: &mut Vec<PdfWarnMsg>) -> Result<Vec<u8>, String> {
    let mut doc = Document::load_mem(pdf).map_err(|e| format!("Failed to load PDF: {e}"))?;
    let spans = drop_redundant_actual_text(&mut doc);
    for id in &spans.rewritten {
        if let Ok(Object::Stream(stream)) = doc.get_object_mut(*id) {
            let _ = stream.compress();
        }
    }
    warnings.push(PdfWarnMsg::info(
        0,
        0,
        format!(
            "/ActualText: {} spans dropped, {} kept",
            spans.dropped, spans.kept
        ),
    ));
    let mut bytes = Vec::new();
    doc.save_to(&mut bytes)
        .map_err(|e| format!("Failed to write PDF: {e}"))?;
    Ok(bytes)
}

/// What [`drop_redundant_actual_text`] did
pub(crate) struct DroppedSpans {
    /// `/ActualText` spans dropped
    pub dropped: usize,
    /// `/ActualText` spans kept
    pub kept: usize,
    /// The content streams written again (uncompressed)
    pub rewritten: Vec<ObjectId>,
}

/// Drops the `/ActualText` of every `/Span` whose glyphs read as that text anyway.
///
/// A reader takes the text of a span with an `/ActualText` from that string, and other text from
/// the glyphs: each code through its font's `/ToUnicode`, with a space wherever the glyphs leave
/// a gap. The `/ActualText` adds nothing when
///
/// - it is all the span's properties hold (no `/MCID`, `/Lang`, ...), with nothing else marked
///   inside the span,
/// - every glyph in the span has text in its font's `/ToUnicode` (an Identity-H/V Type0 font or
///   a simple font), and together they spell the `/ActualText` exactly,
/// - and they are set as plain text: no character spacing, horizontal scaling or rise, no gap
///   wider than [`MAX_KERN`] between two glyphs unless after a space, and no `'`, `"` or form
///   XObject inside the span.
///
/// The span's `BDC` and `EMC` go, and what it shows stays. Pages whose content streams other
/// pages share, or that do not parse, are left as they are.
pub(crate) fn drop_redundant_actual_text(doc: &mut Document) -> DroppedSpans {
    let mut result = DroppedSpans {
        dropped: 0,
        kept: 0,
        rewritten: Vec::new(),
    };
    let pages: Vec<ObjectId> = doc.get_pages().into_values().collect();
    let mut uses: BTreeMap<ObjectId, usize> = BTreeMap::new();
    for page in &pages {
        for id in doc.get_page_contents(*page) {
            *uses.entry(id).or_default() += 1;
        }
    }
    let mut fonts = BTreeMap::new();

    for page in pages {
        let streams = doc.get_page_contents(page);
        if streams.is_empty() || streams.iter().any(|id| uses[id] > 1) {
            continue;
        }
        let bytes = doc.get_page_content(page);
        if !bytes.windows(11).any(|w| w == b"/ActualText") {
            continue;
        }
        let Ok(content) = Content::decode(&bytes) else {
            continue;
        };
        let page_fonts = page_fonts(doc, page, &mut fonts);
        let (drop, kept) = redundant_spans(&content.operations, &page_fonts);
        result.kept += kept;
        if drop.is_empty() {
            continue;
        }
        let operations: Vec<Operation> = content
            .operations
            .into_iter()
            .enumerate()
            .filter(|(i, _)| !drop.contains(i))
            .map(|(_, op)| op)
            .collect();
        let Ok(new) = (Content { operations }).encode() else {
            result.kept += drop.len() / 2;
            continue;
        };
        result.dropped += drop.len() / 2;
        // the page's content, all in its first stream
        doc.objects.insert(
            streams[0],
            Object::Stream(Stream::new(Dictionary::new(), new)),
        );
        if streams.len() > 1 {
            for id in &streams[1..] {
                doc.objects.remove(id);
            }
            if let Ok(page) = doc.get_dictionary_mut(page) {
                page.set("Contents", streams[0]);
            }
        }
        result.rewritten.push(streams[0]);
    }
    result
}

/// What a font's codes read as: the text its `/ToUnicode` gives each code, and how many bytes a
/// code takes (two in an Identity-H/V Type0 font, one in a simple font)
struct FontText {
    code_bytes: usize,
    to_unicode: ToUnicodeCMap,
}

impl FontText {
    /// None for other encodings and for fonts without a `/ToUnicode`: their text is not checked
    fn of(doc: &Document, font: &Dictionary) -> Option<FontText> {
        let name = |key: &[u8]| font.get(key).and_then(Object::as_name).ok();
        let code_bytes = match name(b"Subtype")? {
            b"Type0" if matches!(name(b"Encoding"), Some(b"Identity-H" | b"Identity-V")) => 2,
            b"Type1" | b"MMType1" | b"TrueType" | b"Type3" => 1,
            _ => return None,
        };
        let (_, cmap) = doc.dereference(font.get(b"ToUnicode").ok()?).ok()?;
        let cmap = cmap.as_stream().ok()?;
        let bytes = cmap
            .decompressed_content()
            .unwrap_or_else(|_| cmap.content.clone());
        let to_unicode = ToUnicodeCMap::parse(&String::from_utf8_lossy(&bytes)).ok()?;
        Some(FontText {
            code_bytes,
            to_unicode,
        })
    }
}

/// The fonts a page's content can name, by resource name: from the page's own resources first,
/// then from those it inherits. `cache` keeps each font object's text across pages.
fn page_fonts(
    doc: &Document,
    page: ObjectId,
    cache: &mut BTreeMap<ObjectId, Option<Rc<FontText>>>,
) -> BTreeMap<Vec<u8>, Option<Rc<FontText>>> {
    let mut fonts = BTreeMap::new();
    let Ok((own, inherited)) = doc.get_page_resources(page) else {
        return fonts;
    };
    let resources = own.into_iter().chain(
        inherited
            .iter()
            .filter_map(|id| doc.get_dictionary(*id).ok()),
    );
    for resources in resources {
        let Some(font_dict) = resources
            .get(b"Font")
            .ok()
            .and_then(|fonts| doc.dereference(fonts).ok())
            .and_then(|(_, fonts)| fonts.as_dict().ok())
        else {
            continue;
        };
        for (name, font) in font_dict.iter() {
            if fonts.contains_key(name) {
                continue;
            }
            let text = match font {
                Object::Reference(id) => cache
                    .entry(*id)
                    .or_insert_with(|| {
                        let font = doc.get_dictionary(*id).ok()?;
                        FontText::of(doc, font).map(Rc::new)
                    })
                    .clone(),
                Object::Dictionary(font) => FontText::of(doc, font).map(Rc::new),
                _ => None,
            };
            fonts.insert(name.clone(), text);
        }
    }
    fonts
}

/// The text state that decides how glyphs read
#[derive(Clone)]
struct TextState {
    font: Option<Rc<FontText>>,
    char_spacing: f32,
    scaling: f32,
    rise: f32,
}

impl TextState {
    const INITIAL: TextState = TextState {
        font: None,
        char_spacing: 0.0,
        scaling: 100.0,
        rise: 0.0,
    };

    /// No character spacing, horizontal scaling or rise
    fn plain(&self) -> bool {
        self.char_spacing == 0.0 && self.scaling == 100.0 && self.rise == 0.0
    }
}

/// An open marked-content section
struct Span {
    /// Index of its `BDC` or `BMC`
    begin: usize,
    /// Its `/ActualText`, if it is a `/Span` with nothing else in its properties
    actual_text: Option<String>,
    /// What its glyphs read as, while they can be read
    text: Option<String>,
    /// Whether the last glyph read is a space
    after_space: bool,
}

/// The indices of the `BDC` and `EMC` of each `/Span` whose `/ActualText` its glyphs read as
/// anyway, and how many other `/ActualText` spans there are
fn redundant_spans(
    ops: &[Operation],
    fonts: &BTreeMap<Vec<u8>, Option<Rc<FontText>>>,
) -> (BTreeSet<usize>, usize) {
    let mut state = TextState::INITIAL;
    let mut saved = Vec::new();
    let mut open: Vec<Span> = Vec::new();
    let mut drop = BTreeSet::new();
    let mut kept = 0;
    for (i, op) in ops.iter().enumerate() {
        // an operand that is not a number leaves the text not plain (NaN is no number)
        let number = || {
            op.operands
                .first()
                .and_then(|n| n.as_float().ok())
                .unwrap_or(f32::NAN)
        };
        match op.operator.as_str() {
            "q" => saved.push(state.clone()),
            "Q" => {
                if let Some(s) = saved.pop() {
                    state = s;
                }
            }
            "Tf" => {
                state.font = op
                    .operands
                    .first()
                    .and_then(|name| name.as_name().ok())
                    .and_then(|name| fonts.get(name))
                    .cloned()
                    .flatten()
            }
            "Tc" => state.char_spacing = number(),
            "Tz" => state.scaling = number(),
            "Ts" => state.rise = number(),
            "BDC" | "BMC" => {
                // with marked content inside, a span is left as it is
                for span in &mut open {
                    span.text = None;
                }
                open.push(Span {
                    begin: i,
                    actual_text: actual_text(&op.operands),
                    text: Some(String::new()),
                    after_space: false,
                });
            }
            "EMC" => {
                if let Some(Span {
                    begin,
                    actual_text: Some(actual_text),
                    text,
                    ..
                }) = open.pop()
                {
                    if text.as_ref() == Some(&actual_text) {
                        drop.insert(begin);
                        drop.insert(i);
                    } else {
                        kept += 1;
                    }
                }
            }
            "Tj" | "TJ" => {
                if let Some(span) = open.last_mut() {
                    let readable = match &mut span.text {
                        Some(text) => read(text, &mut span.after_space, op, &state).is_some(),
                        None => true,
                    };
                    if !readable {
                        span.text = None;
                    }
                }
            }
            "'" | "\"" | "Do" => {
                if let Some(span) = open.last_mut() {
                    span.text = None;
                }
            }
            _ => {}
        }
    }
    (drop, kept)
}

/// The `/ActualText` of a `/Span` whose properties hold nothing else
fn actual_text(operands: &[Object]) -> Option<String> {
    let [Object::Name(tag), Object::Dictionary(properties)] = operands else {
        return None;
    };
    if tag != b"Span" || properties.len() != 1 {
        return None;
    }
    match properties.get(b"ActualText") {
        Ok(Object::String(bytes, _)) => text_string(bytes),
        _ => None,
    }
}

/// A PDF text string: UTF-16BE after its byte-order mark, UTF-8 after its (PDF 2.0), else
/// PDFDocEncoding, of which only the printable characters it shares with Latin-1 are read
fn text_string(bytes: &[u8]) -> Option<String> {
    if let Some(utf16) = bytes.strip_prefix(&[0xFE, 0xFF]) {
        if utf16.len() % 2 != 0 {
            return None;
        }
        let units: Vec<u16> = utf16
            .chunks(2)
            .map(|pair| u16::from_be_bytes([pair[0], pair[1]]))
            .collect();
        return String::from_utf16(&units).ok();
    }
    if let Some(utf8) = bytes.strip_prefix(&[0xEF, 0xBB, 0xBF]) {
        return String::from_utf8(utf8.to_vec()).ok();
    }
    bytes
        .iter()
        .map(|&b| matches!(b, 0x20..=0x7E | 0xA1..=0xAC | 0xAE..=0xFF).then_some(b as char))
        .collect()
}

/// Appends what the glyphs of a `Tj` or `TJ` read as to `text`. None if they cannot be read the
/// same way by every reader: a glyph without text, text not set plain, or a gap between two
/// glyphs that reads as a space.
fn read(
    text: &mut String,
    after_space: &mut bool,
    op: &Operation,
    state: &TextState,
) -> Option<()> {
    let font = state.font.as_ref().filter(|_| state.plain())?;
    let items: &[Object] = match (op.operator.as_str(), op.operands.first()?) {
        ("TJ", Object::Array(items)) => items,
        ("Tj", string @ Object::String(..)) => std::slice::from_ref(string),
        _ => return None,
    };
    for item in items {
        match item {
            Object::String(codes, _) => {
                if codes.len() % font.code_bytes != 0 {
                    return None;
                }
                for code in codes.chunks(font.code_bytes) {
                    let code = code.iter().fold(0u32, |c, &b| c << 8 | u32::from(b));
                    let glyph = font.to_unicode.lookup_string(code)?;
                    *after_space = glyph.chars().all(char::is_whitespace);
                    text.push_str(&glyph);
                }
            }
            Object::Integer(_) | Object::Real(_) => {
                // a TJ number moves the next glyph left: a negative one widens the gap
                let widening = -item.as_float().ok()?;
                if widening.abs() > MAX_KERN && !(widening > 0.0 && *after_space) {
                    return None;
                }
            }
            _ => return None,
        }
    }
    Some(())
}

/// Encodes the pictures of a finished PDF again, as [`PdfDocument::save`](crate::PdfDocument::save)
/// would with `options`, and puts each one that comes out smaller in place of the old one, under
/// the same object number, so the pages that show it stay as they are. Fonts, pages and content
/// streams are written back unchanged.
///
/// Only pictures whose pixels printpdf reads and writes the same way are encoded again: 8-bit
/// DeviceGray or DeviceRGB, Flate-compressed or not, with no soft mask, mask, /Decode array or
/// predictor. JPEGs, masks and everything else are kept as they are.
///
/// For scans of black-and-white prints (engravings, woodcuts), `dither_greyscale` makes their
/// grey pixels black or white, and the pictures are then written with one bit per pixel.
#[cfg(feature = "images")]
pub fn optimize_images(
    pdf: &[u8],
    options: &ImageOptimizationOptions,
    warnings: &mut Vec<PdfWarnMsg>,
) -> Result<Vec<u8>, String> {
    let mut doc = Document::load_mem(pdf).map_err(|e| format!("Failed to load PDF: {e}"))?;

    // masks are pictures too, but they belong to the picture they mask
    let masks: BTreeSet<ObjectId> = doc
        .objects
        .values()
        .filter_map(as_image)
        .flat_map(|image| {
            [b"SMask".as_slice(), b"Mask"]
                .into_iter()
                .filter_map(|key| image.dict.get(key).and_then(Object::as_reference).ok())
        })
        .collect();
    let pictures: Vec<ObjectId> = doc
        .objects
        .iter()
        .filter(|(id, object)| !masks.contains(id) && as_image(object).is_some_and(reencodable))
        .map(|(id, _)| *id)
        .collect();

    for id in pictures {
        let Some(old) = doc.objects.get(&id).and_then(as_image) else {
            continue;
        };
        let Some(picture) = raw_bitmap_from_stream(&doc, old) else {
            continue;
        };
        let old_dict = old.dict.clone();
        let old_len = old.content.len();
        let mut new = image_to_stream(picture, &mut doc, Some(options));
        if new.content.len() >= old_len {
            continue;
        }
        // whatever else the picture carries (/Intent, /Metadata, /OC, ...) stays with it
        for (key, value) in old_dict.iter() {
            if !new.dict.has(key) && !matches!(key.as_slice(), b"Filter" | b"DecodeParms") {
                new.dict.set(key.clone(), value.clone());
            }
        }
        warnings.push(PdfWarnMsg::info(
            0,
            0,
            format!(
                "picture {} {} R: {old_len} bytes, now {}",
                id.0,
                id.1,
                new.content.len()
            ),
        ));
        doc.objects.insert(id, Object::Stream(new));
    }

    let mut bytes = Vec::new();
    doc.save_to(&mut bytes)
        .map_err(|e| format!("Failed to write PDF: {e}"))?;
    Ok(bytes)
}

#[cfg(feature = "images")]
fn as_image(object: &Object) -> Option<&Stream> {
    match object {
        Object::Stream(s)
            if s.dict.get(b"Subtype").and_then(Object::as_name).ok() == Some(b"Image") =>
        {
            Some(s)
        }
        _ => None,
    }
}

/// Whether the picture's pixels are read and written the same way: 8-bit DeviceGray or
/// DeviceRGB, Flate or no filter, and nothing else that changes how they are drawn
#[cfg(feature = "images")]
fn reencodable(image: &Stream) -> bool {
    let dict = &image.dict;
    let flate_or_none = match dict.get(b"Filter") {
        Err(_) => true,
        Ok(Object::Name(filter)) => filter == b"FlateDecode",
        Ok(Object::Array(filters)) => filters
            .iter()
            .all(|f| f.as_name().ok() == Some(b"FlateDecode")),
        Ok(_) => false,
    };
    flate_or_none
        && matches!(
            dict.get(b"ColorSpace").and_then(Object::as_name).ok(),
            Some(b"DeviceGray" | b"DeviceRGB")
        )
        && dict.get(b"BitsPerComponent").and_then(Object::as_i64).ok() == Some(8)
        && [
            b"SMask".as_slice(),
            b"Mask",
            b"Decode",
            b"DecodeParms",
            b"ImageMask",
        ]
        .iter()
        .all(|key| !dict.has(key))
}