| 1 |
use lopdf::{Document, Result}; |
| 2 |
|
| 3 |
#[cfg(feature = "async")] |
| 4 |
use tokio::runtime::Builder; |
| 5 |
|
| 6 |
#[cfg(not(feature = "async"))] |
| 7 |
fn load_document(path: &str) -> Result<Document> { |
| 8 |
Document::load(path) |
| 9 |
} |
| 10 |
|
| 11 |
#[cfg(feature = "async")] |
| 12 |
fn load_document(path: &str) -> Result<Document> { |
| 13 |
Builder::new_current_thread() |
| 14 |
.enable_all() |
| 15 |
.build() |
| 16 |
.unwrap() |
| 17 |
.block_on(async move { |
| 18 |
Document::load(path).await |
| 19 |
}) |
| 20 |
} |
| 21 |
|
| 22 |
fn main() -> Result<()> { |
| 23 |
// Load a PDF document |
| 24 |
let mut doc = load_document("example.pdf")?; |
| 25 |
|
| 26 |
println!("Loaded PDF document"); |
| 27 |
|
| 28 |
// Get all pages |
| 29 |
let pages = doc.get_pages(); |
| 30 |
let mut total_replacements = 0; |
| 31 |
|
| 32 |
// Example 1: Replace "Hello" with "Hi" on all pages |
| 33 |
println!("\n=== Replacing 'Hello' with 'Hi' ==="); |
| 34 |
for page_num in pages.keys() { |
| 35 |
match doc.replace_partial_text(*page_num, "Hello", "Hi", Some("?")) { |
| 36 |
Ok(count) => { |
| 37 |
if count > 0 { |
| 38 |
println!("Page {}: Replaced {} occurrences", page_num, count); |
| 39 |
total_replacements += count; |
| 40 |
} |
| 41 |
} |
| 42 |
Err(e) => eprintln!("Error on page {}: {}", page_num, e), |
| 43 |
} |
| 44 |
} |
| 45 |
|
| 46 |
// Example 2: Replace "World" with "Earth" on page 1 |
| 47 |
println!("\n=== Replacing 'World' with 'Earth' on page 1 ==="); |
| 48 |
match doc.replace_partial_text(1, "World", "Earth", None) { |
| 49 |
Ok(count) => { |
| 50 |
println!("Replaced {} occurrences of 'World' with 'Earth'", count); |
| 51 |
total_replacements += count; |
| 52 |
} |
| 53 |
Err(e) => eprintln!("Error during replacement: {}", e), |
| 54 |
} |
| 55 |
|
| 56 |
// Example 3: Replace partial text in a specific pattern |
| 57 |
println!("\n=== Replacing email domains ==="); |
| 58 |
match doc.replace_partial_text(1, "@example.com", "@company.org", Some("?")) { |
| 59 |
Ok(count) => { |
| 60 |
println!("Replaced {} email domains", count); |
| 61 |
total_replacements += count; |
| 62 |
} |
| 63 |
Err(e) => eprintln!("Error during replacement: {}", e), |
| 64 |
} |
| 65 |
|
| 66 |
println!("\n=== Summary ==="); |
| 67 |
println!("Total replacements made: {}", total_replacements); |
| 68 |
|
| 69 |
// Save the modified document if any replacements were made |
| 70 |
if total_replacements > 0 { |
| 71 |
doc.save("example_modified.pdf")?; |
| 72 |
println!("Saved modified document to example_modified.pdf"); |
| 73 |
} else { |
| 74 |
println!("No replacements were made, document not saved"); |
| 75 |
} |
| 76 |
|
| 77 |
// Example 4: Demonstrating the difference between replace_text and replace_partial_text |
| 78 |
println!("\n=== Comparison with original replace_text ==="); |
| 79 |
|
| 80 |
// This would fail with replace_text because it requires exact match |
| 81 |
let mut doc2 = load_document("example.pdf")?; |
| 82 |
|
| 83 |
// Original replace_text - needs exact match |
| 84 |
match doc2.replace_text(1, "Hello World!", "Hi Earth!", None) { |
| 85 |
Ok(_) => println!("replace_text: Successfully replaced exact text"), |
| 86 |
Err(e) => println!("replace_text: Failed - {}", e), |
| 87 |
} |
| 88 |
|
| 89 |
// New replace_partial_text - can replace partial matches |
| 90 |
match doc2.replace_partial_text(1, "Hello", "Hi", None) { |
| 91 |
Ok(count) => println!("replace_partial_text: Replaced {} partial matches", count), |
| 92 |
Err(e) => println!("replace_partial_text: Failed - {}", e), |
| 93 |
} |
| 94 |
|
| 95 |
Ok(()) |
| 96 |
} |
| 97 |
|
| 98 |
#[cfg(test)] |
| 99 |
mod tests { |
| 100 |
use super::*; |
| 101 |
use lopdf::{dictionary, content::{Content, Operation}, Stream, Object}; |
| 102 |
|
| 103 |
#[test] |
| 104 |
fn test_partial_replacement() -> Result<()> { |
| 105 |
// Create a test document |
| 106 |
let mut doc = Document::with_version("1.5"); |
| 107 |
|
| 108 |
// Create a simple page with text |
| 109 |
let pages_id = doc.new_object_id(); |
| 110 |
let font_id = doc.add_object(dictionary! { |
| 111 |
"Type" => "Font", |
| 112 |
"Subtype" => "Type1", |
| 113 |
"BaseFont" => "Helvetica", |
| 114 |
}); |
| 115 |
|
| 116 |
let resources_id = doc.add_object(dictionary! { |
| 117 |
"Font" => dictionary! { |
| 118 |
"F1" => font_id, |
| 119 |
}, |
| 120 |
}); |
| 121 |
|
| 122 |
let content = Content { |
| 123 |
operations: vec![ |
| 124 |
Operation::new("BT", vec![]), |
| 125 |
Operation::new("Tf", vec!["F1".into(), 12.into()]), |
| 126 |
Operation::new("Td", vec![100.into(), 700.into()]), |
| 127 |
Operation::new("Tj", vec![Object::string_literal("Hello World! Hello Universe!")]), |
| 128 |
Operation::new("ET", vec![]), |
| 129 |
], |
| 130 |
}; |
| 131 |
|
| 132 |
let content_id = doc.add_object(Stream::new(dictionary! {}, content.encode()?)); |
| 133 |
|
| 134 |
let page_id = doc.add_object(dictionary! { |
| 135 |
"Type" => "Page", |
| 136 |
"Parent" => pages_id, |
| 137 |
"Contents" => content_id, |
| 138 |
"Resources" => resources_id, |
| 139 |
}); |
| 140 |
|
| 141 |
doc.objects.insert(pages_id, Object::Dictionary(dictionary! { |
| 142 |
"Type" => "Pages", |
| 143 |
"Kids" => vec![page_id.into()], |
| 144 |
"Count" => 1, |
| 145 |
"MediaBox" => vec![0.into(), 0.into(), 612.into(), 792.into()], |
| 146 |
})); |
| 147 |
|
| 148 |
let catalog_id = doc.add_object(dictionary! { |
| 149 |
"Type" => "Catalog", |
| 150 |
"Pages" => pages_id, |
| 151 |
}); |
| 152 |
|
| 153 |
doc.trailer.set("Root", catalog_id); |
| 154 |
|
| 155 |
// Test partial replacement |
| 156 |
let replacements = doc.replace_partial_text(1, "Hello", "Greetings", None)?; |
| 157 |
assert_eq!(replacements, 2); // Should replace both occurrences |
| 158 |
|
| 159 |
// Extract text to verify |
| 160 |
let text = doc.extract_text(&[1])?; |
| 161 |
assert!(text.contains("Greetings World! Greetings Universe!")); |
| 162 |
|
| 163 |
Ok(()) |
| 164 |
} |
| 165 |
} |