use std::collections::BTreeMap;
use std::io::{BufRead, Lines};
use lopdf::content::{Content, Operation};
use lopdf::{Document, Object};
use lopdf::Error::ObjectType;
fn main() -> Result<(), Box<dyn std::error::Error>> {
println!("Hello, world!");
let mut doc = Document::load("C:\\template_xml_invoice\\example_2.pdf").unwrap();
doc.decompress();
for page_id in doc.get_pages().values() {
//println!("page_id: {:?}", doc.get_page_content(*page_id));
let content_stream = doc.get_page_content(*page_id);
let content = Content::decode(&content_stream.as_slice()).unwrap();
let mut content_modified = content.to_owned();
/* for mut c in content.to_owned().operations {
if c.operator == "TJ"{
if let Some(first_operand) = c.operands.first_mut() {
match first_operand {
// If it's a PDF string containing raw bytes/text
Object::String(bytes, _format) => {
println!("\"{}\"", String::from_utf8_lossy(bytes));
*bytes = b"NewBytesValue".to_vec();
},
// If it's a PDF Name object (e.g., /FontName)
Object::Name(bytes) => {
*bytes = b"NewName".to_vec();
},
// Handle other types or numeric/array variants as needed
_ => {}
}
}}}
let modified_bytes = content.encode().unwrap();
doc.change_page_content(*page_id, modified_bytes).unwrap();
}*/
//println!("Content => {:#?}", content);
let mut j = 0;
for mut c in content.operations {
if c.operator == "TJ" {
let mut i = 0;
if let Some(lopdf::Object::Array(arr)) = c.operands.first_mut() {
for mut obj in arr.to_owned() {
match obj {
Object::Integer(i) => {},
Object::String(mut bytes, _format) => {
let byte_to_string = String::from_utf8_lossy(bytes.as_slice()).to_string();
for (i,b) in bytes.to_owned().as_slice().iter().enumerate() {
if *b == 66u8 && bytes.len() > 1 {
println!(" Before String: {} Bytes: {:?}", byte_to_string, bytes);
bytes[i] = 91u8;
println!(" After String: {} Bytes: {:?}", byte_to_string, bytes);
}
}
arr[i] = Object::String(bytes.to_owned(), _format.to_owned());
},
_ => todo!()
}
i += 1;
}
}
}
content_modified.operations[j] = c;
j += 1;
}
let modified_bytes = content_modified.encode().unwrap();
doc.change_page_content(*page_id, modified_bytes).unwrap();
}
// doc.replace_partial_text(1, "Yo", "Yo, Javier Augusto Murcia Beltran", Some("TJ")).unwrap();
doc.save("C:\\template_xml_invoice\\example_2_modified_bytes.pdf").unwrap();
Ok(())
}
Is there a question here or do you just want to showcase your code snippet?

