From c8d557d3f8476635f20b75518f6f4ba2e39be730 Mon Sep 17 00:00:00 2001 From: NandeMD <76772692+NandeMD@users.noreply.github.com> Date: Fri, 15 Mar 2024 06:30:42 +0300 Subject: [PATCH] Added pages() iterator to PopplerDocument (#14) * added an iterator over pages * refactored code positioning --- src/lib.rs | 72 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) diff --git a/src/lib.rs b/src/lib.rs index 6446973..f8e6b71 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -115,6 +115,10 @@ impl PopplerDocument { ptr => Some(PopplerPage(ptr)), } } + + pub fn pages(&self) -> PagesIter { + PagesIter { total: self.get_n_pages(), index: 0, doc: self } + } } impl PopplerPage { @@ -153,6 +157,28 @@ impl PopplerPage { } } +#[derive(Debug)] +pub struct PagesIter<'a> { + total: usize, + index: usize, + doc: &'a PopplerDocument +} + +impl<'a> Iterator for PagesIter<'a> { + type Item = PopplerPage; + + fn next(&mut self) -> Option { + if self.index < self.total { + let page = self.doc.get_page(self.index); + self.index += 1; + page + } else { + None + } + } +} + + #[cfg(test)] mod tests { use crate::PopplerDocument; @@ -284,4 +310,50 @@ mod tests { assert!(PopplerDocument::new_from_data(&mut data[..], Some("upw")).is_err()); } + + #[test] + fn test4() { + let path = "test.pdf"; + let doc: PopplerDocument = PopplerDocument::new_from_file(path, None).unwrap(); + let total = doc.get_n_pages(); + + let mut count = 0; + let src_w = 595f64; + let src_h = 842f64; + + for (index, p) in doc.pages().enumerate() { + let (w, h) = p.get_size(); + assert!(w == src_w); + assert!(h == src_h); + + println!("page {}/{} -- {}x{}", index+1, total, w, h); + count += 1; + } + + assert!(count == 1); + + #[cfg(feature = "render")] + let count = 0; + + #[cfg(feature = "render")] + for (index, p) in doc.pages().enumerate() { + let (w, h) = p.get_size(); + + assert!(w == src_w); + assert!(h == src_h); + + let surface = ImageSurface::create(Format::ARgb32, w as i32, h as i32).unwrap(); + (|page: &PopplerPage, ctx: &Context| { + ctx.save().unwrap(); + page.render(ctx); + ctx.restore().unwrap(); + ctx.show_page().unwrap(); + })(&page, &ctx); + let mut f: File = File::create(format!("out{}.png", index)).unwrap(); + surface.write_to_png(&mut f).expect("Unable to write PNG"); + } + + #[cfg(feature = "render")] + assert!(count == 1) + } }