Files
pdfcraft/crates/engine/src/print_raster.rs
T
d749fd8062 Print colour management: the app converts printed pictures into a printer profile (#6269) (#6853)
* Print: app-managed colour converts printed pictures into a printer profile (#6269)

doc_print takes color_management (printer, the default, or app). With app,
color_profile (an ICC file or an installed profile's name), rendering_intent
and black_point_compensation convert each rendered page picture from sRGB
into the printer's RGB or grey profile before it is sent. app prints the
pages as pictures; CMYK and non-destination profiles are refused.
print_color_profiles lists the installed RGB and grey profiles.

The conversion is craft-cms at craft-print's rev, in pdfcraft_print::colour,
hooked into print_raster::rasterize. Raster carries the colour and is Clone
rather than Copy.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Print colour: look for installed profiles inside the read root when confined

With automation roots, print_color_profiles and doc_print's color_profile
name lookup read the system's colour folders, outside the roots. They now
look in the read root instead (as text_font_files does), check each file
against it before reading it, and are refused without read authority.
Under --root they look in the root.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* automation: keep colour profile discovery inside --root, links followed

Under --root alone, print_color_profiles and the color_profile name
lookup listed the root's .icc files without checking each against the
root, so a link inside it could read a profile outside. Each discovered
file now goes through the same --root resolution as any other read
(links followed) before it is opened.

colour_profile_links_out_of_the_root_are_not_read makes such a link and
checks it is neither listed nor found by name; it fails without the
check (the link is listed).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* print: as_chunks for the grey fill; area print keeps managed colour

Clippy 1.99 (`chunks_exact_to_as_chunks`) flags the constant-width
`chunks_exact_mut(4)` in the grey conversion; use `as_chunks_mut::<4>()`.

main's print-area path built `Raster` without the new `colour` field;
build it through `PrintDraft::raster()` so a printed area is colour
managed like a printed page.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Lock craft-cms at the craft-libs commit craft-print now uses

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(print): read only regular files as printer profiles, and no more than the cap

A FIFO or device named `.icc`/`.icm` in a profile folder was listed and
read, and opening a FIFO for reading waits for a writer. The listing now
keeps regular files only (links followed), `PrinterProfile::read` refuses
anything else before opening it, and the read goes through a limit one
byte past `MAX_PROFILE_BYTES`, so a file that grew after it was measured
is refused rather than read whole.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: KenM76 <KenM76>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-12 06:28:18 +01:00

84 lines
4.7 KiB
Rust

//! 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) 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. With app-managed colour the pictures are converted into
//! the printer's ICC profile ([`pdfcraft_print::colour`]).
use pdfcraft_cos::{SaveOptions, write_incremental};
use pdfcraft_create::ImageResolution;
use pdfcraft_print::{Content, Raster};
use pdfcraft_render::{PRINT_TAG, PageRenderer, RenderRequest};
use crate::export::encode_png;
use crate::{Document, guard, print_layer_states};
/// `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, 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();
// The copy below holds only what prints, so the viewer's own comment hiding plays no part.
config.hide_comments = false;
// Printing is not the View event: a layer the auto state turns off on screen keeps its
// configured state on paper, as in a print that goes out as vectors.
config.for_print = true;
let (printed, layers) = guard(|| -> Result<(Vec<u8>, Option<Vec<pdfcraft_render::Layer>>), 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);
// The layers as the vector print sets them: as shown, then the Print event's auto state.
let layers = print_layer_states(&cos, &doc.info.layers);
Ok((write_incremental(&cos, &SaveOptions::default()).map_err(|e| e.to_string())?, layers))
})??;
if let Some(layers) = layers {
config.layers = std::sync::Arc::new(layers.iter().map(|l| (l.id.0 as i32, l.id.1 as i32, l.visible)).collect());
}
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 {
let (w, h) = src.sizes.get(page).copied().ok_or_else(|| format!("page {} does not exist", page + 1))?;
let scale = pdfcraft_render::effective_scale(w, h, (dpi / 72.0) as f32);
let page_dpi = f64::from(scale) * 72.0;
// Every page of the image document shares one resolution, so its pages keep the
// source's sizes; the lowest a page needed is used for all.
used = Some(used.map_or(page_dpi, |u: f64| u.min(page_dpi)));
let r = renderer.render(RenderRequest { page, scale, tag: PRINT_TAG, ..Default::default() });
if let Some(e) = r.error {
return Err(format!("page {}: {e}", page + 1));
}
let mut rgba = r.rgba.to_vec();
over_white(&mut rgba, raster.grayscale);
// App-managed colour: the picture's values become the printer's, so it is placed as
// device colour the driver passes on unconverted.
if let Some(colour) = &raster.colour {
colour.convert(&mut rgba).map_err(|e| format!("page {}: {e}", page + 1))?;
}
images.push((format!("page-{}.png", page + 1), encode_png(r.width, r.height, &rgba)?));
}
let dpi = used.unwrap_or(dpi);
let doc = pdfcraft_create::from_images_with_resolution(&images, ImageResolution::Dpi(dpi)).map_err(|e| e.to_string())?;
pdfcraft_cos::write_full(&doc, &pdfcraft_cos::SaveOptions::default()).map_err(|e| e.to_string())
}
/// Premultiplied RGBA composed over white paper (opaque), in grey when asked (Rec. 601 luma).
pub(crate) fn over_white(rgba: &mut [u8], grayscale: bool) {
for px in rgba.as_chunks_mut::<4>().0 {
let gap = 255 - u32::from(px[3]);
let (r, g, b) = ((u32::from(px[0]) + gap).min(255), (u32::from(px[1]) + gap).min(255), (u32::from(px[2]) + gap).min(255));
let (r, g, b) = if grayscale {
let y = ((299 * r + 587 * g + 114 * b) / 1000).min(255);
(y, y, y)
} else {
(r, g, b)
};
px[0] = r as u8;
px[1] = g as u8;
px[2] = b as u8;
px[3] = 255;
}
}