Skip to content

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

fix(engine): low-resolution printing prints only the chosen content

aiongg77480498b25f
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index fc1a8d207..817eb79a9 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -4541,8 +4541,7 @@ impl Session {
distinct.push(p);
}
}
- let hide_comments = matches!(settings.content, print::Content::Document | print::Content::FormFieldsOnly);
- let bytes = print_raster::rasterize(doc, &distinct, raster, hide_comments).map_err(EditError::Print)?;
+ let bytes = print_raster::rasterize(doc, &distinct, raster, settings.content).map_err(EditError::Print)?;
let pictures = pdfcraft_cos::Document::open(Arc::new(bytes)).map_err(|e| EditError::Print(e.to_string()))?;
let remapped = print::Settings {
pages: settings.pages.iter().map(|p| distinct.iter().position(|d| d == p).unwrap_or(0)).collect(),
diff --git a/crates/engine/src/print_raster.rs b/crates/engine/src/print_raster.rs
index 117c8e14c..4ed589586 100644
--- a/crates/engine/src/print_raster.rs
+++ b/crates/engine/src/print_raster.rs
@@ -1,25 +1,33 @@
//! Print as image (Acrobat's Advanced Print Setup ▸ Print As Image): every page
//! sent to the printer as a picture at a chosen resolution, for printers that skip text,
//! shading or transparency. The pages are rendered the way the viewer shows them (reading
-//! colours off, the print's own colours), made into an image-only document, and that document
-//! is imposed on the paper like any other. The print is no longer searchable text.
+//! colours off, the print's own colours) with only what the print's content choice keeps, made
+//! into an image-only document, and that document is imposed on the paper like any other. The
+//! print is no longer searchable text.
+use pdfcraft_cos::{SaveOptions, write_incremental};
use pdfcraft_create::ImageResolution;
-use pdfcraft_print::Raster;
+use pdfcraft_print::{Content, Raster};
use pdfcraft_render::{PRINT_TAG, PageRenderer, RenderRequest};
-use crate::Document;
use crate::export::encode_png;
+use crate::{Document, guard};
/// `doc`'s pages `pages` (0-based, each once, in the order given) as an image-only PDF, one
-/// page per entry, the size of the source page as displayed. Pages too large for the renderer
-/// at `raster.dpi` render at the largest resolution it allows.
-pub fn rasterize(doc: &Document, pages: &[usize], raster: &Raster, hide_comments: bool) -> Result<Vec<u8>, String> {
+/// page per entry, the size of the source page as displayed, drawing what `content` prints.
+/// Pages too large for the renderer at `raster.dpi` render at the largest resolution it allows.
+pub fn rasterize(doc: &Document, pages: &[usize], raster: &Raster, content: Content) -> Result<Vec<u8>, String> {
let dpi = raster.dpi.clamp(72.0, 600.0);
let src = doc.export_source();
let mut config = src.config.clone();
- config.hide_comments = hide_comments;
- let mut renderer = PageRenderer::new(src.bytes, config);
+ // The copy below holds only what prints, so the viewer's own comment hiding plays no part.
+ config.hide_comments = false;
+ let printed = guard(|| -> Result<Vec<u8>, String> {
+ let mut cos = pdfcraft_cos::Document::open_with_password(src.bytes.clone(), config.password.as_deref()).map_err(|e| e.to_string())?;
+ pdfcraft_print::keep_printed(&mut cos, content);
+ write_incremental(&cos, &SaveOptions::default()).map_err(|e| e.to_string())
+ })??;
+ let mut renderer = PageRenderer::new(std::sync::Arc::new(printed), config);
let mut images: Vec<(String, Vec<u8>)> = Vec::with_capacity(pages.len());
let mut used: Option<f64> = None;
for &page in pages {
diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs
index 217d8d166..3d347e649 100644
--- a/crates/engine/src/tests.rs
+++ b/crates/engine/src/tests.rs
@@ -1372,6 +1372,83 @@ fn low_resolution_printing_prints_pictures_of_at_most_150_dpi() {
assert!(page_texts(&s2, id2).iter().any(|t| !t.trim().is_empty()), "the owner prints the pages themselves");
}
+/// A 100 × 400 pt page with one band per kind of thing that prints, top to bottom: page content
+/// (blue), a filled text field (green), a stamp (red) and a square comment (yellow).
+fn print_content_pdf() -> Vec<u8> {
+ let content = "0 0 1 rg 0 300 100 100 re f";
+ let ap = |colour: &str| {
+ let ops = format!("{colour} rg 0 0 100 100 re f");
+ format!("<< /Type /XObject /Subtype /Form /BBox [0 0 100 100] /Length {} >> stream\n{ops}\nendstream", ops.len())
+ };
+ format!(
+ "%PDF-1.7\n\
+ 1 0 obj << /Type /Catalog /Pages 2 0 R /AcroForm << /Fields [5 0 R] >> >> endobj\n\
+ 2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj\n\
+ 3 0 obj << /Type /Page /Parent 2 0 R /MediaBox [0 0 100 400] /Contents 4 0 R /Annots [5 0 R 6 0 R 7 0 R] >> endobj\n\
+ 4 0 obj << /Length {} >> stream\n{content}\nendstream endobj\n\
+ 5 0 obj << /Type /Annot /Subtype /Widget /FT /Tx /T (Name) /V (Filled) /F 4 /P 3 0 R /Rect [0 200 100 300] /AP << /N 8 0 R >> >> endobj\n\
+ 6 0 obj << /Type /Annot /Subtype /Stamp /F 4 /P 3 0 R /Rect [0 100 100 200] /AP << /N 9 0 R >> >> endobj\n\
+ 7 0 obj << /Type /Annot /Subtype /Square /F 4 /P 3 0 R /Rect [0 0 100 100] /AP << /N 10 0 R >> >> endobj\n\
+ 8 0 obj {} endobj\n\
+ 9 0 obj {} endobj\n\
+ 10 0 obj {} endobj\n\
+ trailer << /Root 1 0 R >>\n%%EOF",
+ content.len(),
+ ap("0 1 0"),
+ ap("1 0 0"),
+ ap("1 1 0"),
+ )
+ .into_bytes()
+}
+
+/// Low-resolution printing prints what the chosen content prints when the pages themselves are
+/// printed: form fields only leaves out the page content and every comment, the document alone
+/// leaves out the comments, and the document with stamps keeps only the stamps.
+#[test]
+fn low_resolution_printing_prints_only_the_chosen_content() {
+ let mut cos = pdfcraft_cos::Document::open(Arc::new(print_content_pdf())).unwrap();
+ cos.set_encryption(&pdfcraft_cos::NewEncryption {
+ algorithm: pdfcraft_cos::Algorithm::Aes256,
+ user_password: "",
+ owner_password: "owner",
+ permissions: -1 ^ (1 << 11),
+ encrypt_metadata: true,
+ seed: [7; 32],
+ })
+ .unwrap();
+ let bytes = Arc::new(pdfcraft_cos::write_full(&cos, &Default::default()).unwrap());
+ let mut s = Session::new();
+ let low = s.open("low.pdf", None, bytes.clone(), None).unwrap();
+ let owner = s.open("low.pdf", None, bytes, Some("owner")).unwrap();
+ // Each band's centre, in pixels from the top of the sheet at 72 dpi, and its colour.
+ let bands = [("content", 50, [0, 0, 255]), ("field", 150, [0, 255, 0]), ("stamp", 250, [255, 0, 0]), ("comment", 350, [255, 255, 0])];
+ let all: &[&str] = &["content", "field", "stamp", "comment"];
+ for (content, shown) in [
+ (print::Content::DocumentAndMarkups, all),
+ (print::Content::Document, &["content", "field"][..]),
+ (print::Content::DocumentAndStamps, &["content", "field", "stamp"][..]),
+ (print::Content::FormFieldsOnly, &["field"][..]),
+ ] {
+ let settings = print::Settings {
+ pages: vec![0],
+ paper: (100.0, 400.0),
+ layout: print::Layout::Size(print::SizeMode::Actual),
+ content,
+ ..Default::default()
+ };
+ for (id, how) in [(owner, "pages"), (low, "pictures")] {
+ let (w, h, rgba) = printed_pixels(s.print_pdf(id, &settings).unwrap());
+ assert_eq!((w, h), (100, 400), "{content:?} as {how}");
+ for (band, y, colour) in bands {
+ let px = rgba.get((y * w as usize + 50) * 4..).and_then(|p| p.get(..3)).unwrap();
+ let near = |c: [u8; 3]| px.iter().zip(c).all(|(&a, b)| a.abs_diff(b) < 40);
+ let expected = shown.contains(&band);
+ assert!(if expected { near(colour) } else { near([255; 3]) }, "{content:?} as {how}: {band} drawn {expected} expected, pixel {px:?}");
+ }
+ }
+ }
+}
+
#[test]
fn the_permissions_password_unlocks_an_open_document() {
// Only a permissions password (#995, #1077): opens without asking. Changes are allowed,
diff --git a/crates/print/src/lib.rs b/crates/print/src/lib.rs
index e935cb938..6839e5f6b 100644
--- a/crates/print/src/lib.rs
+++ b/crates/print/src/lib.rs
@@ -696,6 +696,25 @@ fn decoded_contents(doc: &Document, page: &Dict) -> Vec<u8> {
out
}
+/// Reduce `doc`'s pages to what [`impose`] draws of them under `content`: the annotations that
+/// don't print are dropped, and with [`Content::FormFieldsOnly`] the page content too. For
+/// printing pages as pictures, where a renderer draws each page as it stands.
+pub fn keep_printed(doc: &mut Document, content: Content) {
+ for page in pdfcraft_model::pages(doc) {
+ let annots = page.dict.get(b"Annots").and_then(|a| doc.resolve(a).as_array().cloned()).unwrap_or_default();
+ let kept: Vec<Object> = annots.into_iter().filter(|a| doc.resolve(a).as_dict().is_some_and(|d| prints(doc, d, content))).collect();
+ // Fails only when the page object isn't a dictionary, and such a page draws nothing.
+ let _ = doc.update_dict(page.obj, |d| {
+ if content == Content::FormFieldsOnly {
+ d.remove(b"Contents");
+ }
+ if d.contains(b"Annots") {
+ d.set(b"Annots".to_vec(), Object::Array(kept));
+ }
+ });
+ }
+}
+
/// Does annotation `d` print under `content`?
fn prints(doc: &Document, d: &Dict, content: Content) -> bool {
const HIDDEN: i64 = 2;