//! Fixtures built in code (nothing in git) and helpers shared by the pdf tests. #![allow(dead_code)] use lopdf::{Document, Object, ObjectId, Stream, StringFormat, dictionary}; use std::path::PathBuf; pub fn engine() -> &'static pictor_pdf::Engine { let dir = std::env::var_os("PDFIUM_DYNAMIC_LIB_PATH") .map(PathBuf::from) .unwrap_or_else(|| PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../third_party/pdfium/bin")); pictor_pdf::Engine::load(Some(&dir)).expect("pdfium: run scripts/fetch-pdfium.ps1 first") } /// Every string that sits under the redaction box (or in a hidden place of the document) in [`secret_pdf`]. pub const SECRETS: &[&str] = &[ "TOP-SECRET-ALPHA", "HIDDEN-LAYER-SECRET", "ANNOT-SECRET", "FORM-SECRET", "META-SECRET-TITLE", "META-SECRET-AUTHOR", "XMP-SECRET", "OUTLINE-SECRET", "STRUCT-SECRET", "ATTACH-SECRET", "IMAGE-SECRET", "123.456 654.321", ]; /// The redaction box over page 1 in view space (points, top-left origin): it covers everything secret on page 1 /// (y 590..760 in PDF space) and leaves "PUBLIC-LINE" (y 300) outside. pub fn secret_box() -> pictor_pdf::ViewRect { pictor_pdf::ViewRect { x: 50.0, y: 30.0, w: 500.0, h: 180.0 } } pub const PAGE_TWO_CONTENT: &[u8] = b"BT /F2 14 Tf 72 720 Td (PAGE-TWO-KEEP) Tj ET\n"; fn s(text: &str) -> Object { Object::String(text.as_bytes().to_vec(), StringFormat::Literal) } #[derive(Default)] pub struct Options { pub compress: bool, /// /Rotate on page 1. pub rotate: i64, /// Put Resources and Rotate on the Pages node (inherited) instead of page 1. pub inherited: bool, } /// Two US-Letter pages. Page 1 holds text, an image, a vector shape, a hidden layer, a note, a form field, all in /// the box; the document holds Info, XMP, an outline, a struct tree and an attachment with secret strings. /// Page 2 holds "PAGE-TWO-KEEP" and must come out byte-equal. pub fn secret_pdf(opts: &Options) -> Vec { let mut doc = Document::with_version("1.7"); let pages_id = doc.new_object_id(); let f1 = doc.add_object(dictionary! {"Type" => "Font", "Subtype" => "Type1", "BaseFont" => "Helvetica"}); let f2 = doc.add_object(dictionary! {"Type" => "Font", "Subtype" => "Type1", "BaseFont" => "Times-Roman"}); let mut pixels = Vec::new(); while pixels.len() < 8 * 8 * 3 { pixels.extend_from_slice(b"IMAGE-SECRET-PIXEL-DATA-"); } pixels.truncate(8 * 8 * 3); let mut im = Stream::new( dictionary! {"Type" => "XObject", "Subtype" => "Image", "Width" => 8, "Height" => 8, "ColorSpace" => "DeviceRGB", "BitsPerComponent" => 8}, pixels, ); im.allows_compression = false; let im1 = doc.add_object(im); let oc1 = doc.add_object(dictionary! {"Type" => "OCG", "Name" => s("Hidden notes")}); let content1 = b"BT /F1 18 Tf 72 720 Td (TOP-SECRET-ALPHA) Tj ET\n\ q 1 0 0 rg 123.456 654.321 m 300.5 650.25 l 300 600 l h f Q\n\ q 100 0 0 50 72 610 cm /Im1 Do Q\n\ /OC /oc1 BDC BT /F1 12 Tf 72 690 Td (HIDDEN-LAYER-SECRET) Tj ET EMC\n\ BT /F1 12 Tf 72 300 Td (PUBLIC-LINE) Tj ET\n" .to_vec(); let c1 = doc.add_object(Stream::new(dictionary! {}, content1)); let c2 = doc.add_object(Stream::new(dictionary! {}, PAGE_TWO_CONTENT.to_vec())); let helv = doc.add_object(dictionary! {"Type" => "Font", "Subtype" => "Type1", "BaseFont" => "Helvetica", "Encoding" => "WinAnsiEncoding"}); let field_ap = doc.add_object(Stream::new( dictionary! {"Type" => "XObject", "Subtype" => "Form", "BBox" => vec![0.into(), 0.into(), 200.into(), 20.into()], "Resources" => dictionary! {"Font" => dictionary! {"Helv" => helv}}}, b"/Tx BMC BT /Helv 10 Tf 0 g 2 6 Td (FORM-SECRET) Tj ET EMC".to_vec(), )); let page1_id = doc.new_object_id(); let field = doc.add_object(dictionary! { "Type" => "Annot", "Subtype" => "Widget", "FT" => "Tx", "T" => s("Account"), "V" => s("FORM-SECRET"), "DA" => s("/Helv 10 Tf 0 g"), "F" => 4, "P" => page1_id, "Rect" => vec![300.into(), 700.into(), 500.into(), 720.into()], "AP" => dictionary! {"N" => field_ap}, }); let note = doc.add_object(dictionary! { "Type" => "Annot", "Subtype" => "Text", "Rect" => vec![80.into(), 700.into(), 100.into(), 720.into()], "Contents" => s("ANNOT-SECRET"), "F" => 4, }); let resources1 = dictionary! { "Font" => dictionary! {"F1" => f1}, "XObject" => dictionary! {"Im1" => im1}, "Properties" => dictionary! {"oc1" => oc1}, }; let mut page1 = dictionary! { "Type" => "Page", "Parent" => pages_id, "Contents" => c1, "Annots" => vec![note.into(), field.into()], "StructParents" => 0, }; if !opts.inherited { page1.set("Resources", resources1.clone()); if opts.rotate != 0 { page1.set("Rotate", opts.rotate); } } doc.objects.insert(page1_id, Object::Dictionary(page1)); let page2_id = doc.add_object(dictionary! { "Type" => "Page", "Parent" => pages_id, "Contents" => c2, "Resources" => dictionary! {"Font" => dictionary! {"F2" => f2}}, }); let mut pages = dictionary! { "Type" => "Pages", "Kids" => vec![page1_id.into(), page2_id.into()], "Count" => 2, "MediaBox" => vec![0.into(), 0.into(), 612.into(), 792.into()], }; if opts.inherited { pages.set("Resources", resources1); if opts.rotate != 0 { pages.set("Rotate", opts.rotate); } // Page 2 has its own Resources and must not inherit the rotation. if let Ok(Object::Dictionary(p2)) = doc.get_object_mut(page2_id) { p2.set("Rotate", 0); } } doc.objects.insert(pages_id, Object::Dictionary(pages)); let xmp = doc.add_object(Stream::new( dictionary! {"Type" => "Metadata", "Subtype" => "XML"}, b"\ XMP-SECRET\ " .to_vec(), )); let outlines_id = doc.new_object_id(); let item = doc.add_object(dictionary! { "Title" => s("OUTLINE-SECRET"), "Parent" => outlines_id, "Dest" => vec![page1_id.into(), "Fit".into()], }); doc.objects.insert( outlines_id, Object::Dictionary(dictionary! {"Type" => "Outlines", "First" => item, "Last" => item, "Count" => 1}), ); let struct_root_id = doc.new_object_id(); let elem = doc.add_object(dictionary! { "Type" => "StructElem", "S" => "P", "P" => struct_root_id, "Pg" => page1_id, "ActualText" => s("STRUCT-SECRET"), "K" => 0, }); doc.objects .insert(struct_root_id, Object::Dictionary(dictionary! {"Type" => "StructTreeRoot", "K" => vec![elem.into()]})); let attach = doc.add_object(Stream::new(dictionary! {"Type" => "EmbeddedFile"}, b"ATTACH-SECRET inside".to_vec())); let filespec = doc.add_object(dictionary! { "Type" => "Filespec", "F" => s("notes.txt"), "EF" => dictionary! {"F" => attach}, }); let catalog = doc.add_object(dictionary! { "Type" => "Catalog", "Pages" => pages_id, "Metadata" => xmp, "Outlines" => outlines_id, "PageMode" => "UseOutlines", "StructTreeRoot" => struct_root_id, "MarkInfo" => dictionary! {"Marked" => true}, "OCProperties" => dictionary! { "OCGs" => vec![oc1.into()], "D" => dictionary! {"OFF" => vec![oc1.into()], "Order" => vec![oc1.into()]}, }, "AcroForm" => dictionary! {"Fields" => vec![field.into()], "DA" => s("/Helv 10 Tf 0 g"), "DR" => dictionary! {"Font" => dictionary! {"Helv" => helv}}}, "Names" => dictionary! {"EmbeddedFiles" => dictionary! {"Names" => vec![s("notes.txt"), filespec.into()]}}, }); let info = doc.add_object(dictionary! { "Title" => s("META-SECRET-TITLE"), "Author" => s("META-SECRET-AUTHOR"), "Producer" => s("fixture"), }); doc.trailer.set("Root", catalog); doc.trailer.set("Info", info); if opts.compress { doc.compress(); } let mut out = Vec::new(); doc.save_to(&mut out).unwrap(); out } /// A simple n-page document; page i says "Page i+1" (for page operations, merge and split). pub fn numbered_pdf(n: usize, label: &str) -> Vec { let mut doc = Document::with_version("1.7"); let pages_id = doc.new_object_id(); let font = doc.add_object(dictionary! {"Type" => "Font", "Subtype" => "Type1", "BaseFont" => "Helvetica"}); let mut kids = Vec::new(); for i in 0..n { let content = format!("BT /F1 24 Tf 72 700 Td ({label} page {}) Tj ET", i + 1).into_bytes(); let c = doc.add_object(Stream::new(dictionary! {}, content)); let p = doc.add_object(dictionary! { "Type" => "Page", "Parent" => pages_id, "Contents" => c, "Resources" => dictionary! {"Font" => dictionary! {"F1" => font}}, }); kids.push(Object::Reference(p)); } doc.objects.insert( pages_id, Object::Dictionary(dictionary! {"Type" => "Pages", "Kids" => kids, "Count" => n as i64, "MediaBox" => vec![0.into(), 0.into(), 595.into(), 842.into()]}), ); let catalog = doc.add_object(dictionary! {"Type" => "Catalog", "Pages" => pages_id}); doc.trailer.set("Root", catalog); let mut out = Vec::new(); doc.save_to(&mut out).unwrap(); out } /// Every byte string an "object scan" can see: string objects, names, and stream contents both raw and decompressed. pub fn scan_objects(bytes: &[u8]) -> Vec> { let doc = Document::load_mem(bytes).expect("lopdf reloads the output"); let mut found = Vec::new(); fn walk(o: &Object, found: &mut Vec>) { match o { Object::String(v, _) | Object::Name(v) => found.push(v.clone()), Object::Array(a) => a.iter().for_each(|x| walk(x, found)), Object::Dictionary(d) => d.iter().for_each(|(k, v)| { found.push(k.clone()); walk(v, found) }), Object::Stream(st) => { st.dict.iter().for_each(|(k, v)| { found.push(k.clone()); walk(v, found) }); found.push(st.content.clone()); if let Ok(d) = st.decompressed_content() { found.push(d); } } _ => {} } } for o in doc.objects.values() { walk(o, &mut found); } walk(&Object::Dictionary(doc.trailer.clone()), &mut found); found } pub fn contains(hay: &[u8], needle: &str) -> bool { hay.windows(needle.len()).any(|w| w == needle.as_bytes()) } /// The page dictionaries of a document, in order. pub fn page_ids(doc: &Document) -> Vec { doc.get_pages().values().copied().collect() } /// A page's content, decompressed and concatenated. pub fn page_content(doc: &Document, page: ObjectId) -> Vec { doc.get_page_content(page) }