| 1 |
// if you use nightly then you can enable this feature to gain a boost in read speed of PDF's" |
| 2 |
//#![feature(extend_one)] |
| 3 |
|
| 4 |
#[macro_use] |
| 5 |
extern crate lopdf; |
| 6 |
|
| 7 |
use std::collections::BTreeMap; |
| 8 |
|
| 9 |
use lopdf::content::{Content, Operation}; |
| 10 |
use lopdf::{Bookmark, Document, Object, ObjectId, Stream}; |
| 11 |
|
| 12 |
pub fn generate_fake_document() -> Document { |
| 13 |
let mut doc = Document::with_version("1.5"); |
| 14 |
let pages_id = doc.new_object_id(); |
| 15 |
let font_id = doc.add_object(dictionary! { |
| 16 |
"Type" => "Font", |
| 17 |
"Subtype" => "Type1", |
| 18 |
"BaseFont" => "Courier", |
| 19 |
}); |
| 20 |
let resources_id = doc.add_object(dictionary! { |
| 21 |
"Font" => dictionary! { |
| 22 |
"F1" => font_id, |
| 23 |
}, |
| 24 |
}); |
| 25 |
let content = Content { |
| 26 |
operations: vec![ |
| 27 |
Operation::new("BT", vec![]), |
| 28 |
Operation::new("Tf", vec!["F1".into(), 48.into()]), |
| 29 |
Operation::new("Td", vec![100.into(), 600.into()]), |
| 30 |
Operation::new("Tj", vec![Object::string_literal("Hello World!")]), |
| 31 |
Operation::new("ET", vec![]), |
| 32 |
], |
| 33 |
}; |
| 34 |
let content_id = doc.add_object(Stream::new(dictionary! {}, content.encode().unwrap())); |
| 35 |
let page_id = doc.add_object(dictionary! { |
| 36 |
"Type" => "Page", |
| 37 |
"Parent" => pages_id, |
| 38 |
"Contents" => content_id, |
| 39 |
"Resources" => resources_id, |
| 40 |
"MediaBox" => vec![0.into(), 0.into(), 595.into(), 842.into()], |
| 41 |
}); |
| 42 |
let pages = dictionary! { |
| 43 |
"Type" => "Pages", |
| 44 |
"Kids" => vec![page_id.into()], |
| 45 |
"Count" => 1, |
| 46 |
}; |
| 47 |
doc.objects.insert(pages_id, Object::Dictionary(pages)); |
| 48 |
let catalog_id = doc.add_object(dictionary! { |
| 49 |
"Type" => "Catalog", |
| 50 |
"Pages" => pages_id, |
| 51 |
}); |
| 52 |
doc.trailer.set("Root", catalog_id); |
| 53 |
|
| 54 |
doc |
| 55 |
} |
| 56 |
|
| 57 |
fn main() { |
| 58 |
// Generate a stack of Documents to merge |
| 59 |
// (The Bookmark layer, Document to merge) |
| 60 |
let documents = vec![ |
| 61 |
(1u32, generate_fake_document()), |
| 62 |
(2u32, generate_fake_document()), |
| 63 |
(2u32, generate_fake_document()), |
| 64 |
(3u32, generate_fake_document()), |
| 65 |
]; |
| 66 |
|
| 67 |
// We use this to keep track of the last Parent per layer depth. |
| 68 |
let mut layer_parent: [Option<u32>; 4] = [None; 4]; |
| 69 |
|
| 70 |
// This is the last layer ran. |
| 71 |
let mut last_layer = 0; |
| 72 |
|
| 73 |
// Define a starting max_id (will be used as start index for object_ids) |
| 74 |
let mut max_id = 1; |
| 75 |
let mut pagenum = 1; |
| 76 |
// Collect all Documents Objects grouped by a map |
| 77 |
let mut documents_pages = BTreeMap::new(); |
| 78 |
let mut documents_objects = BTreeMap::new(); |
| 79 |
let mut document = Document::with_version("1.5"); |
| 80 |
|
| 81 |
// Lets try to set these to be bigger to avoid multi allocations for faster handling of files. |
| 82 |
// We are just saying each Document it about 1000 objects in size. can be adjusted for better speeds. |
| 83 |
// This can only be used if you use nightly or the #![feature(extend_one)] is stablized. |
| 84 |
// documents_pages.extend_reserve(documents.len() * 1000); |
| 85 |
// documents_objects.extend_reserve(documents.len() * 1000); |
| 86 |
|
| 87 |
// Add a Table of Contents |
| 88 |
// We set the object page to (0,0) which means it will point to the first object after it. |
| 89 |
layer_parent[0] = Some(document.add_bookmark( |
| 90 |
Bookmark::new("Table of Contents".to_string(), [0.0, 0.0, 0.0], 0, (0, 0)), |
| 91 |
None, |
| 92 |
)); |
| 93 |
|
| 94 |
// Can set bookmark formatting and color per report bookmark added. |
| 95 |
// Formating is 1 for italic 2 for bold 3 for bold and italic |
| 96 |
// Color is RGB 0.0..255.0 |
| 97 |
for (layer, mut doc) in documents { |
| 98 |
let color = [0.0, 0.0, 0.0]; |
| 99 |
let format = 0; |
| 100 |
let mut display = String::new(); |
| 101 |
|
| 102 |
doc.renumber_objects_with(max_id); |
| 103 |
|
| 104 |
max_id = doc.max_id + 1; |
| 105 |
|
| 106 |
let mut first_object = None; |
| 107 |
|
| 108 |
let pages = doc.get_pages(); |
| 109 |
|
| 110 |
// This is actually better than extend as we use less allocations and cloning then. |
| 111 |
pages.into_values().map(|object_id| { |
| 112 |
// We use this as the return object for Bookmarking to deturmine what it points too. |
| 113 |
// We only want to do this for the first page though. |
| 114 |
if first_object.is_none() { |
| 115 |
first_object = Some(object_id); |
| 116 |
display = format!("Page {}", pagenum); |
| 117 |
pagenum += 1; |
| 118 |
} |
| 119 |
|
| 120 |
(object_id, doc.get_object(object_id).unwrap().to_owned()) |
| 121 |
}) |
| 122 |
.for_each(|(key, value)| { |
| 123 |
documents_pages.insert(key, value); |
| 124 |
}); |
| 125 |
|
| 126 |
documents_objects.extend(doc.objects); |
| 127 |
|
| 128 |
// Lets shadow our pointer back if nothing then set to (0,0) tto point to the next page |
| 129 |
let object = first_object.unwrap_or((0, 0)); |
| 130 |
|
| 131 |
// This will use the layering to implement children under Parents in the bookmarks |
| 132 |
// Example as we are generating it here. |
| 133 |
// Table of Contents |
| 134 |
// - Page 1 |
| 135 |
// -- Page 2 |
| 136 |
// -- Page 3 |
| 137 |
// --- Page 4 |
| 138 |
|
| 139 |
if layer == 0 { |
| 140 |
layer_parent[0] = Some(document.add_bookmark(Bookmark::new(display, color, format, object), None)); |
| 141 |
last_layer = 0; |
| 142 |
} else if layer == 1 { |
| 143 |
layer_parent[1] = |
| 144 |
Some(document.add_bookmark(Bookmark::new(display, color, format, object), layer_parent[0])); |
| 145 |
last_layer = 1; |
| 146 |
} else if last_layer >= layer || last_layer == layer - 1 { |
| 147 |
layer_parent[layer as usize] = Some(document.add_bookmark( |
| 148 |
Bookmark::new(display, color, format, object), |
| 149 |
layer_parent[(layer - 1) as usize], |
| 150 |
)); |
| 151 |
last_layer = layer; |
| 152 |
} else if last_layer > 0 { |
| 153 |
layer_parent[last_layer as usize] = Some(document.add_bookmark( |
| 154 |
Bookmark::new(display, color, format, object), |
| 155 |
layer_parent[(last_layer - 1) as usize], |
| 156 |
)); |
| 157 |
} else { |
| 158 |
layer_parent[1] = |
| 159 |
Some(document.add_bookmark(Bookmark::new(display, color, format, object), layer_parent[0])); |
| 160 |
last_layer = 1; |
| 161 |
} |
| 162 |
} |
| 163 |
|
| 164 |
// Catalog and Pages are mandatory |
| 165 |
let mut catalog_object: Option<(ObjectId, Object)> = None; |
| 166 |
let mut pages_object: Option<(ObjectId, Object)> = None; |
| 167 |
|
| 168 |
// Process all objects except "Page" type |
| 169 |
for (object_id, object) in documents_objects.into_iter() { |
| 170 |
// We have to ignore "Page" (as are processed later), "Outlines" and "Outline" objects |
| 171 |
// All other objects should be collected and inserted into the main Document |
| 172 |
match object.type_name().unwrap_or(b"") { |
| 173 |
b"Catalog" => { |
| 174 |
// Collect a first "Catalog" object and use it for the future "Pages" |
| 175 |
catalog_object = Some(( |
| 176 |
if let Some((id, _)) = catalog_object { |
| 177 |
id |
| 178 |
} else { |
| 179 |
object_id |
| 180 |
}, |
| 181 |
object, |
| 182 |
)); |
| 183 |
} |
| 184 |
b"Pages" => { |
| 185 |
// Collect and update a first "Pages" object and use it for the future "Catalog" |
| 186 |
// We have also to merge all dictionaries of the old and the new "Pages" object |
| 187 |
if let Ok(dictionary) = object.as_dict() { |
| 188 |
let mut dictionary = dictionary.clone(); |
| 189 |
if let Some((_, ref object)) = pages_object { |
| 190 |
if let Ok(old_dictionary) = object.as_dict() { |
| 191 |
dictionary.extend(old_dictionary); |
| 192 |
} |
| 193 |
} |
| 194 |
|
| 195 |
pages_object = Some(( |
| 196 |
if let Some((id, _)) = pages_object { |
| 197 |
id |
| 198 |
} else { |
| 199 |
object_id |
| 200 |
}, |
| 201 |
Object::Dictionary(dictionary), |
| 202 |
)); |
| 203 |
} |
| 204 |
} |
| 205 |
b"Page" => {} // Ignored, processed later and separately |
| 206 |
b"Outlines" => {} // Ignored, not supported yet |
| 207 |
b"Outline" => {} // Ignored, not supported yet |
| 208 |
_ => { |
| 209 |
document.objects.insert(object_id, object); |
| 210 |
} |
| 211 |
} |
| 212 |
} |
| 213 |
|
| 214 |
// If no "Pages" found abort |
| 215 |
if pages_object.is_none() { |
| 216 |
println!("Pages root not found."); |
| 217 |
|
| 218 |
return; |
| 219 |
} |
| 220 |
|
| 221 |
// Iter over all "Page" and collect with the parent "Pages" created before |
| 222 |
for (object_id, object) in documents_pages.iter() { |
| 223 |
if let Ok(dictionary) = object.as_dict() { |
| 224 |
let mut dictionary = dictionary.clone(); |
| 225 |
dictionary.set("Parent", pages_object.as_ref().unwrap().0); |
| 226 |
|
| 227 |
document.objects.insert(*object_id, Object::Dictionary(dictionary)); |
| 228 |
} |
| 229 |
} |
| 230 |
|
| 231 |
// If no "Catalog" found abort |
| 232 |
if catalog_object.is_none() { |
| 233 |
println!("Catalog root not found."); |
| 234 |
|
| 235 |
return; |
| 236 |
} |
| 237 |
|
| 238 |
let (catalog_id, catalog_object) = catalog_object.unwrap(); |
| 239 |
let (page_id, page_object) = pages_object.unwrap(); |
| 240 |
|
| 241 |
// Build a new "Pages" with updated fields |
| 242 |
if let Ok(dictionary) = page_object.as_dict() { |
| 243 |
let mut dictionary = dictionary.clone(); |
| 244 |
|
| 245 |
// Set new pages count |
| 246 |
dictionary.set("Count", documents_pages.len() as u32); |
| 247 |
|
| 248 |
// Set new "Kids" list (collected from documents pages) for "Pages" |
| 249 |
dictionary.set( |
| 250 |
"Kids", |
| 251 |
documents_pages.into_keys().map(|object_id| Object::Reference(object_id)) |
| 252 |
.collect::<Vec<_>>(), |
| 253 |
); |
| 254 |
|
| 255 |
document.objects.insert(page_id, Object::Dictionary(dictionary)); |
| 256 |
} |
| 257 |
|
| 258 |
// Build a new "Catalog" with updated fields |
| 259 |
if let Ok(dictionary) = catalog_object.as_dict() { |
| 260 |
let mut dictionary = dictionary.clone(); |
| 261 |
dictionary.set("Pages", page_id); |
| 262 |
dictionary.set("PageMode", "UseOutlines"); |
| 263 |
dictionary.remove(b"Outlines"); // Outlines not supported in merged PDFs |
| 264 |
|
| 265 |
document.objects.insert(catalog_id, Object::Dictionary(dictionary)); |
| 266 |
} |
| 267 |
|
| 268 |
document.trailer.set("Root", catalog_id); |
| 269 |
|
| 270 |
// Update the max internal ID as wasn't updated before due to direct objects insertion |
| 271 |
document.max_id = document.objects.len() as u32; |
| 272 |
|
| 273 |
// Reorder all new Document objects |
| 274 |
document.renumber_objects(); |
| 275 |
|
| 276 |
//Set any Bookmarks to the First child if they are not set to a page |
| 277 |
document.adjust_zero_pages(); |
| 278 |
|
| 279 |
//Set all bookmarks to the PDF Object tree then set the Outlines to the Bookmark content map. |
| 280 |
if let Some(outline_id) = document.build_outline() { |
| 281 |
if let Ok(Object::Dictionary(dict)) = document.get_object_mut(catalog_id) { |
| 282 |
dict.set("Outlines", Object::Reference(outline_id)); |
| 283 |
} |
| 284 |
} |
| 285 |
|
| 286 |
// Most of the time this does nothing unless there are a lot of streams |
| 287 |
// Can be disabled to speed up the process. |
| 288 |
// document.compress(); |
| 289 |
|
| 290 |
// Save the merged PDF |
| 291 |
// Store file in current working directory. |
| 292 |
document.save("merged.pdf").unwrap(); |
| 293 |
} |