PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust
fix(create): write a new document's page tree once (#5865)
Dylan M. Taylor97260514e631
diff --git a/crates/create/src/lib.rs b/crates/create/src/lib.rsindex 4c117019d..6346e8512 100644--- a/crates/create/src/lib.rs+++ b/crates/create/src/lib.rs@@ -23,29 +23,48 @@ pub const LETTER: (f64, f64) = (612.0, 792.0);/// The largest page side PDF allows (ISO 32000-2 Annex C: 14 400 units).const MAX_SIDE: f64 = 14_400.0;-fn add_page(doc: &mut Document, w: f64, h: f64, resources: Dict, content: Option<Vec<u8>>) -> Result<ObjRef, CreateError> {- // `Document::new_empty` always has a page tree.- let pages = doc- .root()- .and_then(|r| doc.get(r).as_dict().and_then(|d| d.reference(b"Pages")))- .ok_or_else(|| CreateError::Invalid("the new document has no page tree".into()))?;- let mut page = Dict::new();- page.set(b"Type".to_vec(), Object::name("Page"));- page.set(b"Parent".to_vec(), Object::Ref(pages));- page.set(b"MediaBox".to_vec(), Object::Array(vec![0.into(), 0.into(), Object::Real(w), Object::Real(h)]));- page.set(b"Resources".to_vec(), Object::Dict(resources));- if let Some(c) = content {- let s = doc.add(Object::Stream(Stream::flate(Dict::new(), &c)));- page.set(b"Contents".to_vec(), Object::Ref(s));+/// The page tree of a document being made, with the pages added to it so far: its `/Kids` are+/// written once, by [`Pages::finish`]. Adding each page to the tree in the document would copy every+/// page before it, which a text of a million form feeds makes quadratic.+struct Pages {+ tree: ObjRef,+ kids: Vec<Object>,+}++impl Pages {+ /// The page tree of `doc`, with the pages it has.+ fn of(doc: &Document) -> Result<Self, CreateError> {+ // `Document::new_empty` always has a page tree.+ let tree = doc+ .root()+ .and_then(|r| doc.get(r).as_dict().and_then(|d| d.reference(b"Pages")))+ .ok_or_else(|| CreateError::Invalid("the new document has no page tree".into()))?;+ let kids = doc.get(tree).as_dict().and_then(|d| d.get(b"Kids")).and_then(|k| k.as_array().cloned()).unwrap_or_default();+ Ok(Self { tree, kids })+ }++ fn add(&mut self, doc: &mut Document, w: f64, h: f64, resources: Dict, content: Option<Vec<u8>>) {+ let mut page = Dict::new();+ page.set(b"Type".to_vec(), Object::name("Page"));+ page.set(b"Parent".to_vec(), Object::Ref(self.tree));+ page.set(b"MediaBox".to_vec(), Object::Array(vec![0.into(), 0.into(), Object::Real(w), Object::Real(h)]));+ page.set(b"Resources".to_vec(), Object::Dict(resources));+ if let Some(c) = content {+ let s = doc.add(Object::Stream(Stream::flate(Dict::new(), &c)));+ page.set(b"Contents".to_vec(), Object::Ref(s));+ }+ self.kids.push(Object::Ref(doc.add(page)));+ }++ /// Writes the pages added into the tree.+ fn finish(self, doc: &mut Document) -> Result<(), CreateError> {+ let count = i64::try_from(self.kids.len()).map_err(|_| CreateError::Invalid("too many pages".into()))?;+ doc.update_dict(self.tree, |d| {+ d.set(b"Count".to_vec(), Object::Int(count));+ d.set(b"Kids".to_vec(), Object::Array(self.kids));+ })+ .map_err(|e| CreateError::Invalid(e.to_string()))}- let r = doc.add(page);- let _ = doc.update_dict(pages, |d| {- let mut kids = d.get(b"Kids").and_then(|k| k.as_array().cloned()).unwrap_or_default();- kids.push(Object::Ref(r));- d.set(b"Count".to_vec(), Object::Int(kids.len() as i64));- d.set(b"Kids".to_vec(), Object::Array(kids));- });- Ok(r)}fn set_title(doc: &mut Document, title: &str) {@@ -65,9 +84,11 @@ pub fn blank(width: f64, height: f64, pages: usize) -> Result<Document, CreateErreturn Err(CreateError::Invalid("invalid page size or count".into()));}let mut doc = Document::new_empty();+ let mut tree = Pages::of(&doc)?;for _ in 0..pages {- add_page(&mut doc, width, height, Dict::new(), None)?;+ tree.add(&mut doc, width, height, Dict::new(), None);}+ tree.finish(&mut doc)?;Ok(doc)}@@ -675,6 +696,7 @@ pub fn from_images_with_resolution(images: &[(String, Vec<u8>)], resolution: Imareturn Err(CreateError::Invalid("no images".into()));}let mut doc = Document::new_empty();+ let mut tree = Pages::of(&doc)?;let mut profiles = Vec::new();for img in images.iter().map(|(name, bytes)| embed(name, bytes, usize::MAX)).collect::<Result<Vec<_>, _>>()?.into_iter().flatten() {let dpi = match resolution {@@ -692,8 +714,9 @@ pub fn from_images_with_resolution(images: &[(String, Vec<u8>)], resolution: Imalet mut res = Dict::new();res.set(b"XObject".to_vec(), Object::Dict(xobj));let content = format!("q {w:.3} 0 0 {h:.3} 0 0 cm /Im0 Do Q\n").into_bytes();- add_page(&mut doc, w, h, res, Some(content))?;+ tree.add(&mut doc, w, h, res, Some(content));}+ tree.finish(&mut doc)?;if let Some((name, _)) = images.first() {set_title(&mut doc, name.rsplit_once('.').map_or(name.as_str(), |(s, _)| s));}@@ -787,6 +810,7 @@ fn set_text(title: &str, text: &str, page: (f64, f64), font_size: f64) -> Resultfont.set(b"BaseFont".to_vec(), Object::name("Helvetica"));font.set(b"Encoding".to_vec(), Object::name("WinAnsiEncoding"));let fr = doc.add(font);+ let mut tree = Pages::of(&doc)?;let mut page_lines: Vec<Vec<String>> = vec![Vec::new()];for l in lines.iter().take(lines.len().saturating_sub(1)) {if l == "\u{c}" || page_lines.last().is_some_and(|p| p.len() >= per_page) {@@ -810,8 +834,9 @@ fn set_text(title: &str, text: &str, page: (f64, f64), font_size: f64) -> Resultfonts.set(b"F1".to_vec(), Object::Ref(fr));let mut res = Dict::new();res.set(b"Font".to_vec(), Object::Dict(fonts));- add_page(&mut doc, w, h, res, Some(c))?;+ tree.add(&mut doc, w, h, res, Some(c));}+ tree.finish(&mut doc)?;set_title(&mut doc, title);Ok(doc)}diff --git a/crates/create/src/tests.rs b/crates/create/src/tests.rsindex a7a5611ff..9e620c19c 100644--- a/crates/create/src/tests.rs+++ b/crates/create/src/tests.rs@@ -124,6 +124,27 @@ fn text_is_wrapped_and_paginated() {assert!(content(p.last().unwrap()).contains("(After a form feed) Tj"), "a form feed starts a page");}+#[test]+fn text_of_many_form_feeds_makes_its_pages_in_linear_time() {+ // Each form feed starts a page: adding each to the page tree copied all the pages before it,+ // which made forty thousand of them take over a minute in a debug build, against about two+ // seconds when the tree is written once.+ let text = "x\u{c}".repeat(40_000);+ let start = std::time::Instant::now();+ let doc = from_text("many", &text, LETTER, 11.0).unwrap();+ let took = start.elapsed();+ let tree = doc.get(doc.get(doc.root().unwrap()).as_dict().unwrap().reference(b"Pages").unwrap());+ let tree = tree.as_dict().unwrap();+ assert_eq!(tree.get(b"Kids").and_then(|k| k.as_array()).map(|a| a.len()), Some(40_001));+ assert_eq!(tree.int(b"Count"), Some(40_001));+ assert!(took < std::time::Duration::from_secs(30), "{took:?}");+ // Blank documents and pages made from images keep their pages, in order.+ let doc = reopen(&blank(200.0, 300.0, 3).unwrap());+ assert_eq!(pages(&doc).len(), 3);+ let doc = reopen(&from_images(&[("a.png".into(), png_bytes(false)), ("b.png".into(), png_bytes(true))]).unwrap());+ assert_eq!(pages(&doc).len(), 2);+}+#[test]fn text_keeps_leading_spaces_and_tabs() {let doc = reopen(&from_text("t", " indented\n\ttabbed\nplain", LETTER, 11.0).unwrap());