Skip to content

PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust

feat(automation): Automation::render_pixels returns a page as RGBA, without the PNG round trip (#2318)

bonfim6Pf87c143eb47b
diff --git a/crates/automation/src/lib.rs b/crates/automation/src/lib.rs
index 3e2dde314..6b0616aef 100644
--- a/crates/automation/src/lib.rs
+++ b/crates/automation/src/lib.rs
@@ -37,6 +37,7 @@ use pdfcraft_platform::staging::{StagingName, staging_suffixes};
use pdfcraft_render::{PageRenderer, PageText, RenderConfig, RenderRequest, RequestKind};
use serde_json::{Value, json};
+pub use pdfcraft_render::Pixels;
pub use tools::{ToolDef, tools};
/// One piece of a tool's result.
@@ -1782,6 +1783,27 @@ impl Automation {
Ok(Content::Png { data, width: out.width, height: out.height })
}
+ /// A page as RGBA pixels, without encoding a PNG. `page` is 1-based and `scale` is pixels
+ /// per point (1.0 = 72 dpi). For an embedder that paints the result straight onto a canvas:
+ /// the `page_render` tool only returns PNG, and encoding one to decode it again is wasted
+ /// work on every scroll. It uses the same renderer, and the same per-document cache, as
+ /// `page_render`.
+ pub fn render_pixels(&mut self, doc: u64, page: usize, scale: f32) -> Result<(u32, u32, pdfcraft_render::Pixels)> {
+ if !(scale.is_finite() && scale > 0.0 && scale <= (MAX_DPI / 72.0) as f32) {
+ return Err(ToolError::InvalidArgs(format!("scale must be between 0 and {}", MAX_DPI / 72.0)));
+ }
+ let id = DocId(doc);
+ let n = self.session.get(id).ok_or_else(|| failed(format!("no open document with id {doc} (see doc_list)")))?.info.pages.len();
+ if page < 1 || page > n {
+ return Err(ToolError::InvalidArgs(format!("page {page} is out of range: the document has {n} pages")));
+ }
+ let out = self.renderer(id)?.render(RenderRequest { page: page - 1, kind: RequestKind::Pixels, tile: None, scale, tag: 0, preview: false });
+ if let Some(e) = out.error {
+ return Err(failed(format!("page {page} could not be rendered: {e}")));
+ }
+ Ok((out.width, out.height, out.rgba))
+ }
+
fn page(&self, a: &Args) -> Result<usize> {
let n = self.doc(a)?.info.pages.len();
let p = a.int("page")?;
diff --git a/crates/automation/tests/automation.rs b/crates/automation/tests/automation.rs
index 59bb5f505..95d7269f9 100644
--- a/crates/automation/tests/automation.rs
+++ b/crates/automation/tests/automation.rs
@@ -244,6 +244,30 @@ fn autotag_preview_proposes_text_without_changing_the_pdf() {
assert!(preview["candidates"].as_array().unwrap().iter().any(|c| c["text"] == "First paragraph" && c["type"] == "P"));
}
+#[test]
+fn render_pixels_agrees_with_page_render_and_skips_the_png() {
+ let dir = workdir("render-pixels");
+ let mut a = auto(&dir);
+ let doc = ok(&mut a, "doc_open", json!({ "path": "a.pdf" }))["doc"].as_u64().unwrap();
+
+ let (width, height, pixels) = a.render_pixels(doc, 1, 1.0).unwrap();
+ let png = a.call("page_render", &json!({ "doc": doc, "page": 1, "dpi": 72 })).unwrap();
+ let Content::Png { width: png_width, height: png_height, .. } = png[0] else { panic!("expected an image") };
+ assert_eq!((width, height), (png_width, png_height), "scale 1.0 is 72 dpi, like the tool");
+ assert_eq!(pixels.as_ref().len(), width as usize * height as usize * 4, "RGBA, four bytes a pixel");
+ assert!(pixels.as_ref().as_chunks::<4>().0.iter().any(|p| p[..3] != [255, 255, 255]), "the page text is drawn, not a blank sheet");
+
+ let (double_width, _, _) = a.render_pixels(doc, 1, 2.0).unwrap();
+ assert_eq!(double_width, width * 2, "the scale is pixels per point");
+
+ for scale in [0.0_f32, -1.0, f32::NAN, f32::INFINITY, 1.0e6] {
+ assert!(matches!(a.render_pixels(doc, 1, scale), Err(ToolError::InvalidArgs(_))), "scale {scale} must be refused");
+ }
+ assert!(matches!(a.render_pixels(doc, 0, 1.0), Err(ToolError::InvalidArgs(_))), "pages are 1-based");
+ assert!(matches!(a.render_pixels(doc, 99, 1.0), Err(ToolError::InvalidArgs(_))), "a page past the end");
+ assert!(matches!(a.render_pixels(9_999, 1, 1.0), Err(ToolError::Failed(_))), "a document that is not open");
+}
+
#[test]
fn autotag_apply_writes_reviewable_tags_and_survives_save_reopen() {
let dir = workdir("autotag-apply");