mirror of
https://github.com/storytold/pdfcraft.git
synced 2026-12-04 13:03:19 -05:00
fix(print): tell CUPS how the marked sheets run (doc_print marks) (#9135)
* Print: tell CUPS how the marked sheets run With printer marks, doc_print laid the sheets out from the pages as the document shows them, while print_pdf_marked prints the pages the marks widen. A page the marks widen from portrait to landscape was spooled without orientation-requested 4, so CUPS would shrink its landscape sheet onto portrait paper. Session::check_printer_marks, the scratch-copy check that already runs before Will Print, now returns each page's displayed size on that copy, and doc_print lays the sheets out from them. The sheet count and the automatic CUPS orientation follow the printed sheets, and nothing is rendered twice. spool_job's argument checks still run before Will Print; an orientation in options still stands, and a mixed job still gets none. The marks test now also prints the same page at the same layout with and without trim and registration marks, and checks for ink at a trim mark and a registration target where the unmarked print has blank paper. Co-Authored-By: Claude Opus 5.5 <[email protected]> * Print: keep printed_sheets in the doc_print impl block Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_01SqmHYx8FiWM5PcsoiErgp9 --------- Co-authored-by: KenM76 <KenM76> Co-authored-by: Claude Opus 5.5 <[email protected]> Co-authored-by: KenM76 <[email protected]> Co-authored-by: FredApps <[email protected]>
This commit is contained in:
3 files changed
+93
-13
No files matched your search
@@ -455,7 +455,8 @@ impl Automation {
|
||||
return Err(bad("area prints part of a page, without printer marks: leave out one or the other"));
|
||||
}
|
||||
let settings = print::Settings { pages, paper, orientation, layout, content, raster, crops: Vec::new(), area };
|
||||
let laid_out = print::layout(&sizes, &settings).map_err(|e| bad(e.to_string()))?;
|
||||
let allows = self.doc(a)?.allows_printing();
|
||||
let laid_out = self.printed_sheets(id, &sizes, &settings, marks.as_ref().filter(|_| allows))?;
|
||||
let sheets = laid_out.len();
|
||||
// Where it goes is checked before the Will Print actions run, so a call that can't print
|
||||
// doesn't change the document.
|
||||
@@ -475,13 +476,6 @@ impl Automation {
|
||||
}
|
||||
_ => return Err(bad("pass either path (save the print-ready PDF) or printer (a name from printers, or \"default\")")),
|
||||
};
|
||||
// Marks that would widen a page past the largest page a PDF can have fail here, before
|
||||
// the Will Print actions run and could change the document for a print that then fails.
|
||||
if let Some(m) = marks.as_ref()
|
||||
&& self.doc(a)?.allows_printing()
|
||||
{
|
||||
self.session.check_printer_marks(id, &settings.pages, m).map_err(failed)?;
|
||||
}
|
||||
// The document's Will Print actions run first: what they change is printed (#269).
|
||||
let scripts = if self.doc(a)?.allows_printing() {
|
||||
self.session.run_document_actions(id, pdfcraft_engine::js::DocumentScriptEvent::WillPrint)
|
||||
@@ -512,6 +506,25 @@ impl Automation {
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The sheets `settings` lay the pages of `id` (displayed `sizes`) out on, as the print
|
||||
/// copy has them: with `marks`, the pages are measured on a scratch copy the marks widen, so a
|
||||
/// page the marks turn landscape lays out, and is spooled, as a landscape sheet. Marks that
|
||||
/// would widen a page past the largest page a PDF can have fail here, before the Will Print
|
||||
/// actions run and could change the document for a print that then fails.
|
||||
fn printed_sheets(
|
||||
&self,
|
||||
id: pdfcraft_engine::DocId,
|
||||
sizes: &[(f64, f64)],
|
||||
settings: &print::Settings,
|
||||
marks: Option<&PrinterMarks>,
|
||||
) -> Result<Vec<print::Sheet>> {
|
||||
let marked = match marks {
|
||||
Some(m) => Some(self.session.check_printer_marks(id, &settings.pages, m).map_err(failed)?),
|
||||
None => None,
|
||||
};
|
||||
print::layout(marked.as_deref().unwrap_or(sizes), settings).map_err(|e| bad(e.to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
/// Where `doc_print` sends the sheets: a print-ready PDF file, or a printer's queue.
|
||||
@@ -606,6 +619,49 @@ mod tests {
|
||||
assert_eq!(job(json!({ "options": { "orientation-requested": "5" } }), &landscape), [chosen, media], "the caller's own choice, once");
|
||||
}
|
||||
|
||||
/// #7158: a page shown portrait (crop box 400 x 600) inside a landscape media box. The
|
||||
/// marks need room above and below it, so the print copy's page grows to the media box's
|
||||
/// width and 72 points taller: 800 x 672, landscape. The job to a printer follows the marked
|
||||
/// sheet, not the page as the document shows it.
|
||||
#[test]
|
||||
fn marks_that_turn_a_page_landscape_turn_its_printer_job_too() {
|
||||
let objs = [
|
||||
"<< /Type /Catalog /Pages 2 0 R >>",
|
||||
"<< /Type /Pages /Kids [3 0 R] /Count 1 >>",
|
||||
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 800 600] /CropBox [200 0 600 600] >>",
|
||||
];
|
||||
let mut pdf = String::from("%PDF-1.7\n");
|
||||
let mut offsets = Vec::new();
|
||||
for (i, o) in objs.iter().enumerate() {
|
||||
offsets.push(pdf.len());
|
||||
pdf.push_str(&format!("{} 0 obj\n{o}\nendobj\n", i + 1));
|
||||
}
|
||||
let xref = pdf.len();
|
||||
pdf.push_str("xref\n0 4\n0000000000 65535 f \n");
|
||||
for o in offsets {
|
||||
pdf.push_str(&format!("{o:010} 00000 n \n"));
|
||||
}
|
||||
pdf.push_str(&format!("trailer\n<< /Size 4 /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n"));
|
||||
let mut a = Automation::new();
|
||||
let id = a.session.open("tall.pdf", None, std::sync::Arc::new(pdf.into_bytes()), None).unwrap();
|
||||
let sizes = [(400.0, 600.0)];
|
||||
let settings = print::Settings { pages: vec![0], ..Default::default() };
|
||||
let marks = PrinterMarks { color_bars: false, page_info: false, bleed: false, ..PrinterMarks::default() };
|
||||
let unmarked = a.printed_sheets(id, &sizes, &settings, None).unwrap();
|
||||
assert_eq!(print::cups_orientation(&unmarked), None, "the page itself prints portrait");
|
||||
let marked = a.printed_sheets(id, &sizes, &settings, Some(&marks)).unwrap();
|
||||
let landscape = ("orientation-requested".to_string(), "4".to_string());
|
||||
assert_eq!(
|
||||
print::cups_orientation(&marked),
|
||||
Some(landscape.clone()),
|
||||
"the marked sheet runs landscape: {:?}",
|
||||
marked.first().map(|s| s.size)
|
||||
);
|
||||
let job = spool_job(&Args(&json!({})), "Office", "tall.pdf".into(), None, Some("Letter"), None, &marked).unwrap();
|
||||
let media = ("media".to_string(), "Letter".to_string());
|
||||
assert_eq!(job.options, if cfg!(windows) { vec![media] } else { vec![media, landscape] });
|
||||
}
|
||||
|
||||
/// #3752: `doc_print` to a printer sent no paper, so the queue's default paper stood in for
|
||||
/// the one the sheets were laid out on (A4 under Letter sheets on the report's queue).
|
||||
#[test]
|
||||
|
||||
@@ -13463,9 +13463,31 @@ fn printing_with_printer_marks_through_tools() {
|
||||
let sheet = page_text(&mut a, printed).concat();
|
||||
assert!(sheet.contains("a.pdf") && sheet.contains("2 of 3"), "the page information line: {sheet}");
|
||||
ok(&mut a, "doc_close", json!({ "doc": printed }));
|
||||
ok(&mut a, "doc_print", json!({ "doc": doc, "pages": "2", "marks": ["trim", "registration"], "path": "trim.pdf" }));
|
||||
// Only the marks asked for, beside the page where an unmarked print of it at the same
|
||||
// size has blank paper: the 200 x 300 page sits centred on the Letter sheet either way.
|
||||
let print = json!({ "doc": doc, "pages": "2", "layout": "actual", "marks": ["trim", "registration"], "marks_weight": 1, "path": "trim.pdf" });
|
||||
ok(&mut a, "doc_print", print);
|
||||
ok(&mut a, "doc_print", json!({ "doc": doc, "pages": "2", "layout": "actual", "path": "plain.pdf" }));
|
||||
let trim = ok(&mut a, "doc_open", json!({ "path": "trim.pdf" }))["doc"].as_u64().unwrap();
|
||||
assert!(!page_text(&mut a, trim).concat().contains("2 of 3"), "only the marks asked for");
|
||||
let plain = ok(&mut a, "doc_open", json!({ "path": "plain.pdf" }))["doc"].as_u64().unwrap();
|
||||
let mut sheet = |doc: u64| {
|
||||
let rendered = a.call("page_render", &json!({ "doc": doc, "page": 1, "dpi": 72 })).unwrap();
|
||||
let Some(Content::Png { data, .. }) = rendered.first() else { panic!("expected a PNG") };
|
||||
decode_rgba(data)
|
||||
};
|
||||
let (marked, unmarked) = (sheet(trim), sheet(plain));
|
||||
assert_eq!((marked.0, marked.1), (612, 792));
|
||||
// Ink in the box from (x0, y0) to (x1, y1), top-left origin.
|
||||
let inked = |(w, _, rgba): &(u32, u32, Vec<u8>), [x0, y0, x1, y1]: [u32; 4]| {
|
||||
(y0..=y1).any(|y| (x0..=x1).any(|x| rgba_at(*w, rgba, x, y)[..3].iter().any(|c| *c < 200)))
|
||||
};
|
||||
// The page's top-left corner is at (206, 246): a trim mark runs left of it, 6 to 24 pt out,
|
||||
// and a registration target sits 16 pt above the middle of its top edge.
|
||||
for (what, at) in [("trim mark", [184, 245, 198, 247]), ("registration target", [304, 228, 308, 232])] {
|
||||
assert!(inked(&marked, at), "the {what} is printed");
|
||||
assert!(!inked(&unmarked, at), "an unmarked print has blank paper where the {what} goes");
|
||||
}
|
||||
// The document itself is untouched.
|
||||
assert_eq!(page_text(&mut a, doc), before);
|
||||
let info = ok(&mut a, "doc_info", json!({ "doc": doc }));
|
||||
|
||||
@@ -254,9 +254,11 @@ impl Session {
|
||||
|
||||
/// Whether printer's marks fit around `pages` (0-based): [`pdfcraft_edit::add_printer_marks`]
|
||||
/// run on a scratch copy, so a page the marks would widen past the largest page a PDF can
|
||||
/// have is refused before anything (the Will Print actions) changes the document. The copy
|
||||
/// is dropped; [`Session::print_pdf_marked`] adds the marks again on the print copy.
|
||||
pub fn check_printer_marks(&self, id: DocId, pages: &[usize], marks: &crate::PrinterMarks) -> Result<(), EditError> {
|
||||
/// have is refused before anything (the Will Print actions) changes the document. Returns
|
||||
/// every page's displayed size on that copy, the pages [`Session::print_pdf_marked`] lays
|
||||
/// out, so a print job can be told which way its marked sheets run. The copy is dropped;
|
||||
/// [`Session::print_pdf_marked`] adds the marks again on the print copy.
|
||||
pub fn check_printer_marks(&self, id: DocId, pages: &[usize], marks: &crate::PrinterMarks) -> Result<Vec<(f64, f64)>, EditError> {
|
||||
let doc = self.get(id).ok_or(EditError::NoDocument)?;
|
||||
let mut cos = match doc.editor.as_ref() {
|
||||
Some(e) => e.cos.clone(),
|
||||
@@ -268,7 +270,7 @@ impl Session {
|
||||
pages.sort_unstable();
|
||||
pages.dedup();
|
||||
pdfcraft_edit::add_printer_marks(&mut cos, &pages, marks, true)?;
|
||||
Ok(())
|
||||
Ok(pdfcraft_model::pages(&cos).iter().map(|p| p.display_size(&cos)).collect())
|
||||
}
|
||||
|
||||
/// [`Session::print_pdf`] with printer's marks (Acrobat's Marks and Bleeds) drawn around each
|
||||
|
||||
Reference in new issue
Block a user