pdfcer_model/writer/rebuild/mod.rs
1//! A from-scratch structural rewrite: drop unreferenced objects, merge
2//! identical ones, renumber densely, and optionally pack objects into object
3//! streams with a cross-reference stream (ISO 32000-2 §7.5.7, §7.5.8).
4//!
5//! Unlike [`super::save_full`], nothing here is copied verbatim and the
6//! numbering changes, so this is only for an operator-requested size
7//! reduction (decision 191). Decoded content is unchanged: stream data is
8//! copied as stored, with its filters.
9//!
10//! What is dropped regardless of the options: object streams and
11//! cross-reference streams of the input (they are rebuilt or not needed),
12//! and a linearization parameter dictionary, which is rewritten when the
13//! output is linearized and dropped otherwise (Annex F.3.3).
14
15mod emit;
16mod graph;
17mod linearize;
18
19use std::collections::BTreeSet;
20
21use super::{SaveOptions, WriteError};
22use crate::PdfVersion;
23use crate::document::Document;
24use crate::object::ObjId;
25
26/// What [`rebuild`] does beyond renumbering.
27#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
28pub struct RebuildOptions {
29 /// Drop every object not reachable from the trailer's `/Root` or `/Info`.
30 pub remove_unreferenced: bool,
31 /// Merge objects that are identical after their own references are
32 /// merged: streams (except page content streams), fonts, font
33 /// descriptors, encodings, graphics states, non-empty arrays and plain
34 /// values. Pages, annotations, fields, layers and structure elements
35 /// keep their identity even when identical.
36 pub merge_duplicates: bool,
37 /// Pack every non-stream object into Flate-compressed object streams
38 /// and write a cross-reference stream. Raises the header to PDF 1.5
39 /// when it is lower (§7.5.7 is a PDF 1.5 feature).
40 pub object_streams: bool,
41 /// Flate level (0–9) for object streams and the cross-reference stream.
42 pub level: u8,
43 /// Write a linearized file ("Fast Web View", Annex F) instead: page 1
44 /// first, then a hint stream locating every page. Object streams are
45 /// not packed when this is on, the header is raised to PDF 1.2 when
46 /// lower, and inheritable page attributes move onto every page. Off in
47 /// [`Self::all`]: it adds bytes rather than saving them.
48 pub linearize: bool,
49}
50
51impl RebuildOptions {
52 /// Everything on, Flate level 9.
53 #[must_use]
54 pub const fn all() -> Self {
55 Self {
56 remove_unreferenced: true,
57 merge_duplicates: true,
58 object_streams: true,
59 level: 9,
60 linearize: false,
61 }
62 }
63
64 /// Everything off: a caller holding this keeps the file's structure and
65 /// does not call [`rebuild`] at all (see [`Self::is_none`]).
66 #[must_use]
67 pub const fn none() -> Self {
68 Self {
69 remove_unreferenced: false,
70 merge_duplicates: false,
71 object_streams: false,
72 level: 9,
73 linearize: false,
74 }
75 }
76
77 /// Whether no option is on, so a rebuild would only renumber.
78 #[must_use]
79 pub const fn is_none(&self) -> bool {
80 !self.remove_unreferenced
81 && !self.merge_duplicates
82 && !self.object_streams
83 && !self.linearize
84 }
85}
86
87impl Default for RebuildOptions {
88 fn default() -> Self {
89 Self::all()
90 }
91}
92
93/// What a [`rebuild`] did, in the INPUT document's object numbers.
94#[derive(Debug, Clone, PartialEq, Eq, Default)]
95pub struct RebuildReport {
96 /// Indirect objects in the input, structural streams included.
97 pub objects_in: usize,
98 /// Indirect objects written, new object and cross-reference streams
99 /// included.
100 pub objects_out: usize,
101 /// Objects dropped as unreachable.
102 pub unreferenced: Vec<ObjId>,
103 /// `(dropped, kept)` pairs: each dropped object was identical to `kept`
104 /// and every reference to it now names `kept`.
105 pub merged: Vec<(ObjId, ObjId)>,
106 /// Input object and cross-reference streams and linearization
107 /// dictionaries, which are never carried over.
108 pub structural_dropped: Vec<ObjId>,
109 /// References to objects the input does not define, written as `null`
110 /// (§7.3.10 gives them that meaning already).
111 pub dangling: usize,
112 /// Object streams written.
113 pub object_streams: usize,
114 /// The new header version, when packing or linearizing raised it.
115 pub version_raised: Option<PdfVersion>,
116 /// Whether the output is linearized.
117 pub linearized: bool,
118}
119
120/// Rewrite `doc` from scratch under `rebuild_options`. `options` supplies
121/// the cross-reference entry EOL and the final EOL; `producer` is not
122/// applied (the `/Info` dictionary is carried as it is).
123///
124/// # Errors
125///
126/// [`WriteError::EncryptedSaveUnsupported`] for an encrypted document, and
127/// [`WriteError::Xref`] if a cross-reference section cannot be emitted,
128/// [`WriteError::NothingToLinearize`] when linearizing a document with no
129/// catalog or no page.
130pub fn rebuild(
131 doc: &Document,
132 rebuild_options: &RebuildOptions,
133 options: &SaveOptions,
134) -> Result<(Vec<u8>, RebuildReport), WriteError> {
135 rebuild_with(doc, rebuild_options, options, None)
136}
137
138/// [`rebuild`], writing `%PDF-<version>` as the header instead of the
139/// input's version. Object streams still raise it to 1.5; a linearized
140/// rebuild keeps the input's version.
141///
142/// # Errors
143///
144/// As [`rebuild`].
145pub fn rebuild_declaring(
146 doc: &Document,
147 rebuild_options: &RebuildOptions,
148 options: &SaveOptions,
149 version: PdfVersion,
150) -> Result<(Vec<u8>, RebuildReport), WriteError> {
151 rebuild_with(doc, rebuild_options, options, Some(version))
152}
153
154fn rebuild_with(
155 doc: &Document,
156 rebuild_options: &RebuildOptions,
157 options: &SaveOptions,
158 header: Option<PdfVersion>,
159) -> Result<(Vec<u8>, RebuildReport), WriteError> {
160 if doc.encryption().is_some() {
161 return Err(WriteError::EncryptedSaveUnsupported);
162 }
163 let mut report = RebuildReport {
164 objects_in: doc.object_count(),
165 ..RebuildReport::default()
166 };
167 let mut live = graph::live_objects(doc, &mut report);
168 if rebuild_options.remove_unreferenced {
169 let reached = graph::reachable(doc.trailer(), &live);
170 report.unreferenced = live
171 .keys()
172 .filter(|id| !reached.contains(id))
173 .copied()
174 .collect();
175 live.retain(|id, _| reached.contains(id));
176 }
177 let canon = if rebuild_options.merge_duplicates {
178 graph::merge_duplicates(doc, &live, &mut report)
179 } else {
180 std::collections::BTreeMap::new()
181 };
182 let kept: BTreeSet<ObjId> = live
183 .keys()
184 .filter(|id| !canon.contains_key(id))
185 .copied()
186 .collect();
187 let bytes = if rebuild_options.linearize {
188 report.linearized = true;
189 linearize::write(doc, &live, &canon, &kept, &mut report)?
190 } else {
191 let renum = graph::Renumbering::new(&kept, &canon);
192 emit::write(
193 doc,
194 &live,
195 &renum,
196 (rebuild_options, header),
197 options,
198 &mut report,
199 )?
200 };
201 Ok((bytes, report))
202}
203
204#[cfg(test)]
205#[allow(
206 clippy::unwrap_used,
207 clippy::expect_used,
208 clippy::panic,
209 clippy::indexing_slicing
210)] // test code: a failed lookup should fail the test loudly
211mod tests;