Skip to content

Commit

Permalink
Add modify_text test
Browse files Browse the repository at this point in the history
  • Loading branch information
J-F-Liu committed Jan 29, 2017
1 parent a4f5c23 commit 5210eb3
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 4 deletions.
18 changes: 14 additions & 4 deletions src/object.rs
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,13 @@ impl Object {
_ => None
}
}

pub fn as_stream(&self) -> Option<&Stream> {
match *self {
Object::Stream(ref stream) => Some(stream),
_ => None
}
}
}

impl Dictionary {
Expand Down Expand Up @@ -201,6 +208,11 @@ impl Stream {
return None;
}

pub fn set_content(&mut self, content: Vec<u8>) {
self.content = content;
self.dict.set("Length", self.content.len() as i64);
}

pub fn compress(&mut self) {
use std::io::prelude::*;
use flate2::Compression;
Expand All @@ -211,9 +223,8 @@ impl Stream {
encoder.write(self.content.as_slice()).unwrap();
let compressed = encoder.finish().unwrap();
if compressed.len() + 19 < self.content.len() {
self.content = compressed;
self.dict.set("Filter", "FlateDecode");
self.dict.set("Length", self.content.len() as i64);
self.set_content(compressed);
}
}
}
Expand All @@ -230,9 +241,8 @@ impl Stream {
let mut decoder = ZlibDecoder::new(self.content.as_slice());
decoder.read_to_end(&mut data).unwrap();
}
self.content = data;
self.dict.remove("Filter");
self.dict.set("Length", self.content.len() as i64);
self.set_content(data);
},
_ => ()
}
Expand Down
28 changes: 28 additions & 0 deletions tests/modify.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
extern crate lopdf;

use lopdf::{Document, Object, StringFormat};
use std::io::Result;

fn modify_text() -> Result<Document> {
let mut doc = Document::load("assets/example.pdf")?;
if let Some(content_stream) = doc.objects.get_mut(&(3, 0)) {
match *content_stream {
Object::Stream(ref mut stream) => {
let mut content = stream.decode_content().unwrap();
content.operations[3].operands[0] = Object::String(
"Modified text!".as_bytes().to_vec(),
StringFormat::Literal);
stream.set_content(content.encode().unwrap());
},
_ => ()
}
}
doc.save("test_3_modify.pdf")?;
Ok(doc)
}


#[test]
fn test_modify() {
assert_eq!(modify_text().is_ok(), true);
}

0 comments on commit 5210eb3

Please sign in to comment.