pdfboss_write/importer.rs
1//! Transplanting a source document's object graph into a [`Writer`] (ISO
2//! 32000 ยง7.3.10, indirect references): [`Importer`] renumbers every
3//! reference it meets once and drains the resulting queue iteratively, so a
4//! long chain of references costs no stack, and a caller may substitute a
5//! translated body for any object before the drain reaches it.
6
7use std::marker::PhantomData;
8
9use pdfboss_core::{
10 block_on, AsyncObjectSource, Dict, Document, FastMap, Immediate, Name, ObjRef, Object, Page,
11 Rect, Stream,
12};
13
14use crate::error::{Error, Result};
15use crate::update::{core_error, deflate};
16use crate::writer::Writer;
17
18/// Copies one source document's reachable object graph into a [`Writer`].
19/// Every reference met through [`Importer::reference`] or [`Importer::copy`]
20/// is reserved a target number once and queued, so repeated imports from the
21/// same source dedup by source object number: one `Importer` per source
22/// document, and one `Writer` accepts several `Importer`s in sequence.
23///
24/// The source is any [`AsyncObjectSource`], a borrowed [`Document`] unless
25/// `S` says otherwise. [`Importer::new`] opens a [`Document`] for the
26/// synchronous methods; [`Importer::with_source`] opens any other source,
27/// such as an asynchronous document reading over a network, for the `_with`
28/// methods, which are the one implementation both share.
29pub struct Importer<'w, 's, S = Immediate<&'s Document>> {
30 writer: &'w mut Writer,
31 source: S,
32 map: FastMap<ObjRef, ObjRef>,
33 pending: Vec<ObjRef>,
34 substitutions: FastMap<ObjRef, Object>,
35 compress: bool,
36 borrow: PhantomData<&'s ()>,
37}
38
39impl<'w, 's> Importer<'w, 's> {
40 /// Opens `source` for import into `writer`. Refuses a locked source:
41 /// `Document::get` only decrypts transparently once a working
42 /// password configured a decryptor, so copying from a locked source
43 /// would emit raw ciphertext into a plain target with no `/Encrypt`
44 /// of its own. A password-opened encrypted document copies fine: its
45 /// content already reads as plaintext through `Document::get`, exactly
46 /// what [`crate::encrypt_document`] relies on to re-encrypt it under
47 /// new passwords.
48 pub fn new(writer: &'w mut Writer, source: &'s Document) -> Result<Importer<'w, 's>> {
49 // The public load path already refuses a wrong or missing password
50 // before any `Document` exists; this check is a second safeguard,
51 // for a `Document` constructed some other way.
52 if source.is_locked() {
53 return Err(Error::EncryptedBase);
54 }
55 Ok(Importer::with_source(writer, Immediate(source)))
56 }
57
58 /// Drains the pending queue; called by `page`/`document` before
59 /// returning, public for callers that mixed `reference` in. Runs
60 /// [`Importer::finish_with`] over the borrowed document.
61 pub fn finish(&mut self) -> Result<()> {
62 block_on(self.finish_with())
63 }
64
65 /// The whole reachable graph from the source catalog; returns the
66 /// new root ref. Substitutions apply.
67 pub fn document(&mut self) -> Result<ObjRef> {
68 let root = self
69 .source
70 .0
71 .xref()
72 .trailer
73 .get_ref("Root")
74 .ok_or(Error::MissingRoot)?;
75 let new_root = self.reference(root);
76 self.finish()?;
77 Ok(new_root)
78 }
79
80 /// Page `index` of the source under `parent`, as
81 /// [`Importer::page_with`] describes.
82 pub fn page(&mut self, index: usize, parent: ObjRef) -> Result<ObjRef> {
83 let page = self.source.0.page(index).map_err(core_error)?;
84 block_on(self.page_with(&page, parent))
85 }
86}
87
88impl<'w, 's, S: AsyncObjectSource> Importer<'w, 's, S> {
89 /// Opens `source` for import into `writer`. A source has no way to
90 /// report that it is locked, so the caller hands over one that already
91 /// decrypts, as an opened asynchronous document does.
92 pub fn with_source(writer: &'w mut Writer, source: S) -> Importer<'w, 's, S> {
93 let compress = writer.compress();
94 Importer {
95 writer,
96 source,
97 map: FastMap::default(),
98 pending: Vec::new(),
99 substitutions: FastMap::default(),
100 compress,
101 borrow: PhantomData,
102 }
103 }
104
105 /// The target number for source reference `r`, reserved and queued on
106 /// first sight.
107 pub fn reference(&mut self, r: ObjRef) -> ObjRef {
108 if let Some(copied) = self.map.get(&r) {
109 return *copied;
110 }
111 let copied = self.writer.reserve();
112 self.map.insert(r, copied);
113 self.pending.push(r);
114 copied
115 }
116
117 /// A copy of `obj` (source-space) with every reference renumbered into
118 /// the target: the existing private translation, made public.
119 pub fn copy(&mut self, obj: &Object) -> Result<Object> {
120 Ok(match obj {
121 Object::Ref(r) => Object::Ref(self.reference(*r)),
122 Object::Dict(d) => Object::Dict(self.copy_dict(d)?),
123 Object::Array(items) => Object::Array(
124 items
125 .iter()
126 .map(|item| self.copy(item))
127 .collect::<Result<Vec<Object>>>()?,
128 ),
129 Object::Stream(_) => return Err(Error::NestedStream),
130 other => other.clone(),
131 })
132 }
133
134 /// A copy of `dict`'s direct structure with every reference mapped.
135 pub(crate) fn copy_dict(&mut self, dict: &Dict) -> Result<Dict> {
136 let mut out = Dict::new();
137 for (key, value) in dict.iter() {
138 out.insert(key.clone(), self.copy(value)?);
139 }
140 Ok(out)
141 }
142
143 /// A stream body: its dictionary copied without `/Length` (the writer
144 /// sets it), its data compressed when asked and not already filtered.
145 fn copy_stream(&mut self, stream: &Stream) -> Result<Object> {
146 let mut dict = stream.dict.clone();
147 dict.remove("Length");
148 let mut dict = self.copy_dict(&dict)?;
149 let data = if self.compress && dict.get("Filter").is_none() {
150 dict.insert(name("Filter"), Object::Name(name("FlateDecode")));
151 deflate(&stream.data)?
152 } else {
153 stream.data.clone()
154 };
155 Ok(Object::Stream(Stream { dict, data }))
156 }
157
158 /// Replaces the source object's body during the transplant. The
159 /// body is TARGET-space and drain fills it verbatim, no
160 /// renumbering: the caller translates any source refs into it via
161 /// `reference`/`copy` first, and may use refs of objects already
162 /// in the writer directly.
163 ///
164 /// Must be called before `finish` drains `r`: once `r` is popped off
165 /// the pending queue and filled, a later `substitute` for it has no
166 /// effect. `page` cannot trigger this hazard: it only substitutes a
167 /// reference it has itself just queued for the first time.
168 pub fn substitute(&mut self, r: ObjRef, body: Object) {
169 self.substitutions.insert(r, body);
170 }
171
172 /// Drains the pending queue, fetching each queued object from the
173 /// source: the implementation behind [`Importer::finish`].
174 pub async fn finish_with(&mut self) -> Result<()> {
175 while let Some(r) = self.pending.pop() {
176 let target = self.map[&r];
177 let body = match self.substitutions.remove(&r) {
178 Some(body) => body,
179 None => match self.source.get(r).await.map_err(core_error)? {
180 Object::Stream(s) => self.copy_stream(&s)?,
181 other => self.copy(&other)?,
182 },
183 };
184 self.writer.fill(target, body)?;
185 }
186 Ok(())
187 }
188
189 /// `page` as a self-contained object under `parent`
190 /// (target-space): old `/Parent` replaced with `parent`, effective
191 /// `/Resources` and `/MediaBox` materialized, `/Rotate` when non-zero,
192 /// `/CropBox` when it differs from the media box, `/Type /Page` always
193 /// present. Returns the page's new ref. The source `/Parent` is dropped
194 /// before translation, so none of the source's page tree (siblings,
195 /// ancestors) rides along as unreachable objects in the target.
196 ///
197 /// `page` must come from this importer's source, since its references
198 /// are resolved there. A page with an object of its own is checked
199 /// against the source's object of that number and refused when the
200 /// source has no such object or a different one there. The check
201 /// cannot tell apart two documents whose page dictionaries are
202 /// identical, and a page inlined into `/Kids` cannot be checked at all.
203 ///
204 /// ISO 32000 gives a page exactly one parent, so every call gets its
205 /// own page object: importing the same source page again (for a
206 /// second parent, or a repeat in an assembled document) never reuses
207 /// an earlier call's object, even though the resources and content
208 /// beneath keep deduping through this `Importer`'s map. The one
209 /// exception is the very first time a given indirect source page is
210 /// seen: that call keeps the page's source-graph identity (so an
211 /// `/Annots` `/P` back-reference elsewhere in the graph resolves to
212 /// this same object rather than a duplicate). Pages inlined into
213 /// `/Kids` (no object of their own) always get a fresh object.
214 pub async fn page_with(&mut self, page: &Page, parent: ObjRef) -> Result<ObjRef> {
215 if let Some(r) = page.object_ref() {
216 let own = self.source.get(r).await.ok();
217 if own.as_ref().and_then(Object::as_dict) != Some(page.dict()) {
218 return Err(Error::Other(format!(
219 "page {} does not come from the source being copied: object {} {} R \
220 there is a different object",
221 page.index + 1,
222 r.num,
223 r.gen
224 )));
225 }
226 }
227 let mut dict = page.dict().clone();
228 dict.remove("Parent");
229 dict.insert(name("Type"), Object::Name(name("Page")));
230 dict.insert(name("Resources"), Object::Dict(page.resources.clone()));
231 dict.insert(name("MediaBox"), rect_array(page.media_box));
232 if page.rotate != 0 {
233 dict.insert(name("Rotate"), Object::Int(i64::from(page.rotate)));
234 }
235 if page.crop_box != page.media_box {
236 dict.insert(name("CropBox"), rect_array(page.crop_box));
237 }
238 let mut translated = self.copy_dict(&dict)?;
239 translated.insert(name("Parent"), Object::Ref(parent));
240 let target = match page.object_ref() {
241 Some(r) if !self.map.contains_key(&r) => {
242 let target = self.reference(r);
243 self.substitute(r, Object::Dict(translated));
244 target
245 }
246 _ => {
247 let target = self.writer.reserve();
248 self.writer.fill(target, Object::Dict(translated))?;
249 target
250 }
251 };
252 self.finish_with().await?;
253 Ok(target)
254 }
255}
256
257/// A rectangle as a PDF `[x0 y0 x1 y1]` array of reals.
258pub(crate) fn rect_array(rect: Rect) -> Object {
259 Object::Array(
260 [rect.x0, rect.y0, rect.x1, rect.y1]
261 .iter()
262 .map(|v| Object::Real(widen(*v)))
263 .collect(),
264 )
265}
266
267/// `value` widened to `f64` through its own shortest round-trip decimal,
268/// rather than a raw bit widening: a plain `f64::from(f32)` keeps every
269/// bit of the `f32`'s binary value, which usually needs far more decimal
270/// digits to print than the `f32` itself means (`0.1_f32` widens to
271/// `0.10000000149011612`, not `0.1`). Formatting the `f32` first and
272/// reparsing produces the `f64` an `Object::Real` should hold: the one
273/// whose decimal digits match what the source number meant.
274fn widen(value: f32) -> f64 {
275 value
276 .to_string()
277 .parse()
278 .unwrap_or_else(|_| f64::from(value))
279}
280
281fn name(text: &str) -> Name {
282 Name(text.to_string())
283}
284
285#[cfg(test)]
286mod tests {
287 use pdfboss_core::Rect;
288
289 use super::*;
290 use crate::ser::serialize_object;
291
292 fn real_at(array: &Object, index: usize) -> String {
293 let Object::Array(items) = array else {
294 panic!("expected an array, got {array:?}");
295 };
296 let mut out = Vec::new();
297 serialize_object(&items[index], &mut out).expect("a real serializes");
298 String::from_utf8(out).expect("real syntax is ASCII")
299 }
300
301 #[test]
302 fn rect_array_keeps_the_f32_shortest_decimal() {
303 let rect = Rect::new(0.1, 0.0, 300.0, 400.0);
304 let array = rect_array(rect);
305 assert_eq!(real_at(&array, 0), "0.1");
306 }
307}