Skip to content

Commit 11c41e1

Browse files
committed
web: print straight to the system print dialog, not just export
The web build had no way to actually print — Ctrl+P (Cmd+P, declared on file.print's shortcut) did nothing at all, and the ribbon's "Print…" menu item ran file.print and silently discarded the result. file.print already builds a PDF and returns it as base64 specifically "for the UI to hand to the system print dialog" per its own doc comment — this wires that up. - ui-egui: new Services::print hook (web: hand PDF bytes to the browser's print flow directly, no download); SheetApp::print_now runs file.print, decodes the base64 result, and calls the hook. - ui-egui: Key::P now dispatches to print_now (was unbound); the ribbon's "Print…" menu item calls print_now instead of discarding file.print's result. - gridcraft-web: implements the hook (Blob -> object URL -> hidden iframe -> iframe.contentWindow.print() on load). Desktop builds are unaffected (no Services::print set there; print_now falls back to the existing alert-on-error behaviour with no UI action on success, same as before this change).
1 parent 13664fe commit 11c41e1

4 files changed

Lines changed: 77 additions & 2 deletions

File tree

‎apps/gridcraft-web/Cargo.toml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,4 +26,4 @@ rfd = { workspace = true }
2626
wasm-bindgen = "0.2"
2727
wasm-bindgen-futures = "0.4"
2828
js-sys = "0.3"
29-
web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "HtmlAnchorElement", "Blob", "BlobPropertyBag", "Url", "Location", "CssStyleDeclaration"] }
29+
web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "HtmlAnchorElement", "HtmlIFrameElement", "Blob", "BlobPropertyBag", "Url", "Location", "CssStyleDeclaration"] }

‎apps/gridcraft-web/src/web.rs‎

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,6 +112,11 @@ fn services(inbox: Inbox, ctx: egui::Context) -> Services {
112112
log::error!("download of {name} failed: {e}");
113113
}
114114
})),
115+
print: Some(Box::new(|bytes: &[u8]| {
116+
if let Err(e) = print_pdf(bytes) {
117+
log::error!("print failed: {e}");
118+
}
119+
})),
115120
open_url: Some(Box::new(|url: &str| {
116121
if let Some(w) = web_sys::window() {
117122
let _ = w.open_with_url_and_target(url, "_blank");
@@ -122,6 +127,41 @@ fn services(inbox: Inbox, ctx: egui::Context) -> Services {
122127
}
123128
}
124129

130+
/// Opens `bytes` (a PDF) as an object URL in a hidden iframe and calls the
131+
/// iframe's own `print()` once it has finished loading — the standard way
132+
/// to drive the browser's native print dialog on a PDF without a download
133+
/// or a popup window the browser might block. The object URL is
134+
/// deliberately never revoked: the iframe (and its only reference to the
135+
/// blob) lives for the rest of the page session, same lifetime as the app.
136+
fn print_pdf(bytes: &[u8]) -> Result<(), String> {
137+
let js = |e: wasm_bindgen::JsValue| format!("{e:?}");
138+
let window = web_sys::window().ok_or("no window")?;
139+
let document = window.document().ok_or("no document")?;
140+
141+
let parts = js_sys::Array::of1(&js_sys::Uint8Array::from(bytes));
142+
let opts = web_sys::BlobPropertyBag::new();
143+
opts.set_type("application/pdf");
144+
let blob = web_sys::Blob::new_with_u8_array_sequence_and_options(&parts, &opts).map_err(js)?;
145+
let url = web_sys::Url::create_object_url_with_blob(&blob).map_err(js)?;
146+
147+
let iframe: web_sys::HtmlIFrameElement = document.create_element("iframe").map_err(js)?.dyn_into().map_err(|_| "not an iframe")?;
148+
iframe.style().set_property("display", "none").map_err(js)?;
149+
document.body().ok_or("no body")?.append_child(&iframe).map_err(js)?;
150+
151+
// `onload` fires once the PDF has actually rendered inside the iframe;
152+
// printing before that would show a blank page. Set the handler BEFORE
153+
// `src` so a fast/cached load can't fire before we're listening.
154+
let iframe_for_load = iframe.clone();
155+
let on_load = wasm_bindgen::closure::Closure::once_into_js(move || {
156+
if let Some(w) = iframe_for_load.content_window() {
157+
let _ = w.print();
158+
}
159+
});
160+
iframe.set_onload(Some(on_load.unchecked_ref()));
161+
iframe.set_src(&url);
162+
Ok(())
163+
}
164+
125165
/// Triggers a browser download of `bytes`.
126166
fn download(name: &str, bytes: &[u8]) -> Result<(), String> {
127167
let js = |e: wasm_bindgen::JsValue| format!("{e:?}");

‎crates/ui-egui/src/lib.rs‎

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,9 @@ pub struct Services {
7575
pub open_async: Option<Box<dyn Fn()>>,
7676
/// Files delivered asynchronously (name, bytes), opened on the next frame.
7777
pub inbox: Option<Inbox>,
78+
/// Web: hand PDF bytes to the browser's print flow directly (no download,
79+
/// no intermediate file) — opens the system print dialog on that PDF.
80+
pub print: Option<Box<dyn Fn(&[u8])>>,
7881
}
7982

8083
/// Shared queue of files read asynchronously (browser file picker, drag and drop).
@@ -167,6 +170,32 @@ impl SheetApp {
167170
}
168171
}
169172

173+
/// Runs `file.print`, builds the PDF and (where the host provides the hook — the web
174+
/// build) hands the bytes straight to the browser's print flow; errors show the usual
175+
/// alert. Desktop builds have no `services.print`, so this falls back to `run_or_alert`
176+
/// (which still produces the PDF — just without a UI to act on the result yet).
177+
pub fn print_now(&mut self) {
178+
match self.run("file.print", json!({})) {
179+
Ok(r) => {
180+
let Some(b64) = r.get("base64").and_then(Json::as_str) else { return };
181+
let Some(bytes) = gridcraft_engine::io::base64_decode(b64) else {
182+
self.message = Some(("GridCraft".into(), "Couldn't decode the generated PDF.".into()));
183+
return;
184+
};
185+
if let Some(print) = &self.services.print {
186+
print(&bytes);
187+
}
188+
}
189+
Err(e) => {
190+
if e.contains("is not available right now") {
191+
self.toast = Some((e, now_ms()));
192+
} else {
193+
self.message = Some(("GridCraft".into(), clean_error(&e)));
194+
}
195+
}
196+
}
197+
}
198+
170199
/// UI-only commands (dialogs, view toggles that aren't saved in the file).
171200
fn run_ui_command(&mut self, id: &str, p: &Json) -> Option<Result<Json, String>> {
172201
let r = match id {

‎crates/ui-egui/src/ribbon.rs‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -76,14 +76,16 @@ pub fn title_bar(app: &mut SheetApp, ui: &mut Ui) {
7676
("New Workbook", "file.new"),
7777
("Open…", "file.open"),
7878
("Save As…", "file.saveAs"),
79-
("Print…", "file.print"),
8079
("Sort A to Z", "data.sortAscending"),
8180
("Calculate Now", "formulas.calculateNow"),
8281
] {
8382
if ui.button(label).clicked() {
8483
app.run_or_alert(id, json!({}));
8584
}
8685
}
86+
if ui.button("Print…").clicked() {
87+
app.print_now();
88+
}
8789
});
8890
// Centered title.
8991
let title = app.session.active().map(|d| d.display_title()).unwrap_or_default();
@@ -1715,6 +1717,10 @@ pub fn shortcut(app: &mut SheetApp, key: Key, m: Modifiers) {
17151717
Key::O => Some(("file.open", json!({}))),
17161718
Key::N => Some(("file.new", json!({}))),
17171719
Key::W => Some(("file.close", json!({}))),
1720+
Key::P => {
1721+
app.print_now();
1722+
None
1723+
}
17181724
Key::K => {
17191725
app.open_dialog("insertLink", json!({}));
17201726
None

0 commit comments

Comments
 (0)