Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
feat(print): print render notes as they are displayed
Elian Doranceed71f21b07
diff --git a/apps/client/src/services/live_print.css b/apps/client/src/services/live_print.cssnew file mode 100644index 0000000000..1c31890226--- /dev/null+++ b/apps/client/src/services/live_print.css@@ -0,0 +1,33 @@+@media print {+ html:has(> body.print-live),+ body.print-live,+ body.print-live :has(.print-live-target) {+ display: block !important;+ position: static !important;+ overflow: visible !important;+ width: auto !important;+ min-width: 0 !important;+ max-width: none !important;+ height: auto !important;+ min-height: 0 !important;+ max-height: none !important;+ margin: 0 !important;+ padding: 0 !important;+ border: 0 !important;+ contain: none !important;+ transform: none !important;+ background: none !important;+ box-shadow: none !important;+ }++ body.print-live .print-live-target {+ overflow: visible !important;+ height: auto !important;+ max-height: none !important;+ contain: none !important;+ }++ body.print-live :not(:has(.print-live-target), .print-live-target, .print-live-target *) {+ display: none !important;+ }+}diff --git a/apps/client/src/services/live_print.spec.ts b/apps/client/src/services/live_print.spec.tsnew file mode 100644index 0000000000..3540ede324--- /dev/null+++ b/apps/client/src/services/live_print.spec.ts@@ -0,0 +1,91 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import { buildNote } from "../test/easy-froca";+import { endLivePrint, printLiveInBrowser, startLivePrint } from "./live_print";++function addThemeLink(href: string, media?: string) {+ const link = document.createElement("link");+ link.rel = "stylesheet";+ link.href = href;+ if (media) link.media = media;+ link.setAttribute("data-theme-stylesheet", "true");+ document.head.appendChild(link);+ return link;+}++describe("live print", () => {+ beforeEach(() => {+ // Let happy-dom report the stylesheets it does not fetch as loaded.+ const happyDOM = (window as any).happyDOM;+ happyDOM.settings.disableCSSFileLoading = true;+ happyDOM.settings.handleDisabledFileLoadingAsSuccess = true;+ (document as any).fonts = { ready: Promise.resolve() };+ });++ afterEach(() => {+ endLivePrint();+ for (const link of document.head.querySelectorAll("link")) link.remove();+ document.body.replaceChildren();+ });++ it("marks the target, prints the light baseline and applies printCss, then restores everything", async () => {+ const plainTheme = addThemeLink("theme-dark.css");+ const autoTheme = addThemeLink("theme-next-dark.css", "(prefers-color-scheme: dark)");+ const css = buildNote({ id: "live-css", title: "CSS", type: "code" });+ const text = buildNote({ id: "live-text", title: "Not CSS", type: "text" });+ const note = buildNote({ id: "live-host", title: "Host", type: "render" });+ note.getRelationTargets = async () => [ css, text ];+ const target = document.createElement("div");+ document.body.appendChild(target);++ await startLivePrint(note, target);++ expect(document.body.classList.contains("print-live")).toBe(true);+ expect(target.classList.contains("print-live-target")).toBe(true);+ expect(plainTheme.media).toBe("screen");+ expect(autoTheme.media).toBe("screen and (prefers-color-scheme: dark)");+ const printCss = [ ...document.head.querySelectorAll<HTMLLinkElement>("link[data-live-print-css]") ];+ expect(printCss.map((link) => [ link.getAttribute("href"), link.media ])).toEqual([ [ "api/notes/live-css/download", "print" ] ]);++ endLivePrint();++ expect(document.body.classList.contains("print-live")).toBe(false);+ expect(target.classList.contains("print-live-target")).toBe(false);+ expect(plainTheme.media).toBe("");+ expect(autoTheme.media).toBe("(prefers-color-scheme: dark)");+ expect(plainTheme.hasAttribute("data-live-print-media")).toBe(false);+ expect(document.head.querySelector("link[data-live-print-css]")).toBeNull();+ });++ it("keeps a single target when a second live print starts before the first ended", async () => {+ const theme = addThemeLink("theme-dark.css");+ const note = buildNote({ id: "live-twice", title: "Twice", type: "render" });+ const first = document.createElement("div");+ const second = document.createElement("div");+ document.body.append(first, second);++ await startLivePrint(note, first);+ await startLivePrint(note, second);++ expect(first.classList.contains("print-live-target")).toBe(false);+ expect(second.classList.contains("print-live-target")).toBe(true);+ expect(theme.media).toBe("screen");+ });++ it("prints through the browser dialog and restores the window afterwards", async () => {+ const note = buildNote({ id: "live-browser", title: "Browser", type: "render" });+ const target = document.createElement("div");+ document.body.appendChild(target);+ const print = vi.fn(() => {+ expect(target.classList.contains("print-live-target")).toBe(true);+ });+ window.print = print;++ await printLiveInBrowser(note, target);+ expect(print).toHaveBeenCalledOnce();+ expect(target.classList.contains("print-live-target")).toBe(true);++ window.dispatchEvent(new Event("afterprint"));+ expect(target.classList.contains("print-live-target")).toBe(false);+ });+});diff --git a/apps/client/src/services/live_print.ts b/apps/client/src/services/live_print.tsnew file mode 100644index 0000000000..4a08d00336--- /dev/null+++ b/apps/client/src/services/live_print.ts@@ -0,0 +1,85 @@+import "./live_print.css";++import type FNote from "../entities/fnote";++/**+ * Prints an element of the app window as it is on screen instead of rendering its note again on the+ * `?print` page, so a render note keeps its script's state. `live_print.css` hides the rest of the+ * window under `@media print` only.+ */++const ACTIVE_CLASS = "print-live";+const TARGET_CLASS = "print-live-target";+/** Holds the `media` a theme stylesheet had before {@link startLivePrint} limited it to the screen. */+const ORIGINAL_MEDIA_ATTR = "data-live-print-media";+const PRINT_CSS_ATTR = "data-live-print-css";++let activeTarget: HTMLElement | undefined;++/** Prepares the window to print `target`, ending any live print still active. */+export async function startLivePrint(note: FNote, target: HTMLElement) {+ endLivePrint();+ activeTarget = target;+ document.body.classList.add(ACTIVE_CLASS);+ target.classList.add(TARGET_CLASS);++ // Paper gets the light baseline (`theme-light.css`), as on the `?print` page, which loads no theme.+ for (const link of document.querySelectorAll<HTMLLinkElement>("link[data-theme-stylesheet]")) {+ link.setAttribute(ORIGINAL_MEDIA_ATTR, link.media);+ link.media = link.media ? `screen and ${link.media}` : "screen";+ }++ await loadPrintCss(note);+ await document.fonts.ready;+}++/** Restores the window after a live print. Does nothing when none is active. */+export function endLivePrint() {+ if (!activeTarget) return;++ activeTarget.classList.remove(TARGET_CLASS);+ activeTarget = undefined;+ document.body.classList.remove(ACTIVE_CLASS);++ for (const link of document.querySelectorAll<HTMLLinkElement>(`link[${ORIGINAL_MEDIA_ATTR}]`)) {+ link.media = link.getAttribute(ORIGINAL_MEDIA_ATTR) ?? "";+ link.removeAttribute(ORIGINAL_MEDIA_ATTR);+ }++ for (const link of document.querySelectorAll(`link[${PRINT_CSS_ATTR}]`)) {+ link.remove();+ }+}++/** Prints `target` through the browser's own print dialog. */+export async function printLiveInBrowser(note: FNote, target: HTMLElement) {+ await startLivePrint(note, target);+ window.addEventListener("afterprint", endLivePrint, { once: true });+ window.print();+}++/** Applies the note's `~printCss` stylesheets to printing only. */+async function loadPrintCss(note: FNote) {+ const printCssNotes = await note.getRelationTargets("printCss");+ const loads: Promise<void>[] = [];++ for (const printCssNote of printCssNotes) {+ if (!printCssNote || (printCssNote.type !== "code" && printCssNote.mime !== "text/css")) continue;++ const link = document.createElement("link");+ link.rel = "stylesheet";+ link.media = "print";+ link.href = `api/notes/${printCssNote.noteId}/download`;+ link.setAttribute(PRINT_CSS_ATTR, "true");+ loads.push(new Promise((resolve) => {+ link.onload = () => resolve();+ link.onerror = () => {+ console.warn(`Unable to load the print stylesheet ${printCssNote.noteId}; printing without it.`);+ resolve();+ };+ }));+ document.head.appendChild(link);+ }++ await Promise.all(loads);+}diff --git a/apps/client/src/widgets/NoteDetail.tsx b/apps/client/src/widgets/NoteDetail.tsxindex 4ea0379e01..bf5f2ffeeb 100644--- a/apps/client/src/widgets/NoteDetail.tsx+++ b/apps/client/src/widgets/NoteDetail.tsx@@ -13,6 +13,7 @@ import attributes from "../services/attributes";import dialog from "../services/dialog";import froca from "../services/froca";import { t } from "../services/i18n";+import { endLivePrint, printLiveInBrowser } from "../services/live_print";import { stopBackgroundMedia } from "../services/media_playback";import protected_session_holder from "../services/protected_session_holder";import toast from "../services/toast.js";@@ -152,6 +153,7 @@ export default function NoteDetail() {if (!api) return;api.onPrintProgress(({ progress, action }) => showToast(action as "printing" | "exporting_pdf", progress));api.onPrintDone((printReport) => {+ endLivePrint();toast.closePersistent("printing");handlePrintReport(printReport as PrintReport);});@@ -182,8 +184,18 @@ export default function NoteDetail() {// PDF printing is handled by the PDF viewer's own print mechanism.if (note.type === "file" && note.mime === "application/pdf") return;+ // A render note prints from the screen, keeping its script's state.+ const liveTarget = note.type === "render"+ ? containerRef.current?.querySelector<HTMLElement>(".note-detail-render-content") ?? undefined+ : undefined;+if (isElectron() && noteContext.notePath) {- appContext.triggerCommand("showPrintPreview", { note, notePath: noteContext.notePath });+ appContext.triggerCommand("showPrintPreview", { note, notePath: noteContext.notePath, liveTarget });+ return;+ }++ if (liveTarget) {+ void printLiveInBrowser(note, liveTarget);return;}diff --git a/apps/client/src/widgets/dialogs/print_preview.spec.tsx b/apps/client/src/widgets/dialogs/print_preview.spec.tsxindex 11813b89ce..5e0401a185 100644--- a/apps/client/src/widgets/dialogs/print_preview.spec.tsx+++ b/apps/client/src/widgets/dialogs/print_preview.spec.tsx@@ -2,6 +2,7 @@ import { act } from "preact/test-utils";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import Component from "../../components/component";+import { endLivePrint } from "../../services/live_print";import { buildNote } from "../../test/easy-froca";import { renderInto } from "../../test/render";import { ParentComponent } from "../react/react_utils";@@ -43,9 +44,12 @@ describe("PrintPreviewDialog", () => {(window as any).electronApi = { printing };URL.createObjectURL = vi.fn(() => `blob:preview-${++urlCount}`);URL.revokeObjectURL = vi.fn();+ // happy-dom has no FontFaceSet, which a live print waits on.+ (document as any).fonts = { ready: Promise.resolve() };});afterEach(() => {+ endLivePrint();delete (window as any).electronApi;});@@ -87,4 +91,46 @@ describe("PrintPreviewDialog", () => {deliver({ requestId: firstId as number, buffer: new Uint8Array([ 2 ]) });expect(viewer()?.getAttribute("data-url")).toBe(currentUrl);});++ it("prints a live target from the window, keeping it prepared until the print is done", async () => {+ const note = buildNote({ id: "print-live", title: "Live", type: "render" });+ const host = new Component();+ renderInto(+ <ParentComponent.Provider value={host}>+ <PrintPreviewDialog />+ </ParentComponent.Provider>+ );+ const show = async () => {+ const liveTarget = document.createElement("div");+ document.body.appendChild(liveTarget);+ await act(async () => {+ await host.handleEvent("showPrintPreview", { note, notePath: "root/print-live", liveTarget });+ });+ await vi.waitFor(() => expect(printing.exportAsPdfPreview).toHaveBeenCalled());+ return liveTarget;+ };+ const close = () => {+ const closeButton = document.querySelector<HTMLButtonElement>(".print-preview-dialog .btn-close");+ expect(closeButton).toBeTruthy();+ act(() => closeButton?.click());+ };++ // Closing without printing restores the window.+ const cancelled = await show();+ expect(cancelled.classList.contains("print-live-target")).toBe(true);+ expect(printing.exportAsPdfPreview).toHaveBeenCalledWith(expect.objectContaining({ live: true }));+ close();+ await vi.waitFor(() => expect(cancelled.classList.contains("print-live-target")).toBe(false));++ // Printing leaves it prepared: `print-done` from the main process ends it.+ printing.exportAsPdfPreview.mockClear();+ const printed = await show();+ deliver({ requestId: requestIds().at(-1) as number, buffer: new Uint8Array([ 1 ]) });+ const systemPrint = document.querySelector<HTMLAnchorElement>(".print-preview-dialog .modal-footer a");+ expect(systemPrint).toBeTruthy();+ act(() => systemPrint?.click());+ expect(printing.printFromPreview).toHaveBeenCalledWith(expect.objectContaining({ live: true, silent: false }));+ await vi.waitFor(() => expect(document.querySelector(".print-preview-dialog.show")).toBeNull());+ expect(printed.classList.contains("print-live-target")).toBe(true);+ });});diff --git a/apps/client/src/widgets/dialogs/print_preview.tsx b/apps/client/src/widgets/dialogs/print_preview.tsxindex 7039ba7481..57d109563e 100644--- a/apps/client/src/widgets/dialogs/print_preview.tsx+++ b/apps/client/src/widgets/dialogs/print_preview.tsx@@ -5,6 +5,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "preact/hooks"import FNote from "../../entities/fnote";import { getBuiltinLabelSelectOptions } from "../../services/attributes";import { t } from "../../services/i18n";+import { endLivePrint, startLivePrint } from "../../services/live_print";import toast from "../../services/toast";import Button, { ButtonGroup } from "../react/Button";import Dropdown from "../react/Dropdown";@@ -82,6 +83,8 @@ function isValidPageRanges(value: string): boolean {export interface PrintPreviewData {note: FNote;notePath: string;+ /** An element of the app window to print as it is on screen, instead of rendering the note again. */+ liveTarget?: HTMLElement;}interface PreviewOpts {@@ -102,7 +105,9 @@ export default function PrintPreviewDialog() {const notePathRef = useRef("");const pdfUrlRef = useRef<string | undefined>(undefined);const requestIdRef = useRef(0);-+ const isLiveRef = useRef(false);+ /** A live print sent to the printer keeps the window prepared until `print-done` ends it. */+ const isLivePrintSentRef = useRef(false);const [landscape, setLandscape] = useNoteLabelBoolean(note, "printLandscape");const [pageSize, setPageSize] = useNoteLabelWithDefault(note, "printPageSize", "Letter");@@ -145,9 +150,15 @@ export default function PrintPreviewDialog() {setLoading(false);}, []);- useTriliumEvent("showPrintPreview", (data: PrintPreviewData) => {+ useTriliumEvent("showPrintPreview", async (data: PrintPreviewData) => {if (shown) return;+ isLiveRef.current = !!data.liveTarget;+ isLivePrintSentRef.current = false;+ if (data.liveTarget) {+ await startLivePrint(data.note, data.liveTarget);+ }+setNote(data.note);notePathRef.current = data.notePath;setLoading(true);@@ -193,6 +204,7 @@ export default function PrintPreviewDialog() {api.exportAsPdfPreview({requestId: ++requestIdRef.current,notePath: notePathRef.current,+ live: isLiveRef.current,pageSize: opts.pageSize,landscape: opts.landscape,scale: opts.scale,@@ -216,6 +228,10 @@ export default function PrintPreviewDialog() {}, [shown, landscape, pageSize, scale, marginsStr, pageRanges, pageRangesValid, regeneratePreview]);function handleClose() {+ if (isLiveRef.current && !isLivePrintSentRef.current) {+ endLivePrint();+ }+ isLiveRef.current = false;requestIdRef.current++;setShown(false);isFirstGenerationRef.current = true;@@ -240,8 +256,10 @@ export default function PrintPreviewDialog() {}function handlePrint(silent: boolean, deviceName?: string) {+ isLivePrintSentRef.current = isLiveRef.current;window.electronApi?.printing.printFromPreview({notePath: notePathRef.current,+ live: isLiveRef.current,pageSize,landscape,scale,diff --git a/apps/client/src/widgets/layout/NoteActions.spec.tsx b/apps/client/src/widgets/layout/NoteActions.spec.tsxindex 84deec4b4d..3af99b3c68 100644--- a/apps/client/src/widgets/layout/NoteActions.spec.tsx+++ b/apps/client/src/widgets/layout/NoteActions.spec.tsx@@ -120,6 +120,35 @@ describe("NoteContextMenu", () => {}});+ it("offers to print a render note only while it has a render target", async () => {+ const isPrintEnabled = async (note: FNote) => {+ const noteContext = new NoteContext("ntx-render");+ noteContext.noteId = note.noteId;+ noteContext.viewScope = { viewMode: "default" };+ render((+ <ParentComponent.Provider value={new Component()}>+ <NoteContextContext.Provider value={noteContext}>+ <NoteContextMenu note={note} noteContext={noteContext} />+ </NoteContextContext.Provider>+ </ParentComponent.Provider>+ ), host);+ host.querySelector<HTMLButtonElement>("button")?.click();+ const printItem = await vi.waitFor(() => {+ const item = document.querySelector<HTMLElement>(".tn-popup li.dropdown-item:has(.bx-printer)");+ expect(item).toBeTruthy();+ return item;+ });+ const enabled = !printItem?.classList.contains("disabled");+ render(null, host);+ return enabled;+ };++ const script = buildNote({ title: "Script", type: "code" });+ expect(await isPrintEnabled(buildNote({ title: "Render", type: "render", "~renderNote": script.noteId }))).toBe(true);+ expect(await isPrintEnabled(buildNote({ title: "Unset", type: "render" }))).toBe(false);+ expect(await isPrintEnabled(buildNote({ title: "Disabled", type: "render", "~disabled:renderNote": script.noteId }))).toBe(false);+ });+it("opens on the Basic Properties shortcut only for its own note context", async () => {const note = buildNote({ title: "Text", type: "text", content: "<p>Hi</p>" });const noteContext = new NoteContext("ntx-split-2");diff --git a/apps/client/src/widgets/layout/NoteActions.tsx b/apps/client/src/widgets/layout/NoteActions.tsxindex a4be5f0e16..73d19de722 100644--- a/apps/client/src/widgets/layout/NoteActions.tsx+++ b/apps/client/src/widgets/layout/NoteActions.tsx@@ -23,7 +23,7 @@ import { showImageCompressionDialog } from "../dialogs/image_compression/image_cimport { isAlwaysFullWidthByType } from "../note_wrapper";import Dropdown, { type DropdownHandle } from "../react/Dropdown";import { FormDropdownDivider, FormDropdownSubmenu, FormListHeader, FormListItem, FormListToggleableItem } from "../react/FormList";-import { useIsNoteReadOnly, useNoteContext, useNoteLabel, useNoteLabelBoolean, useNoteLabelOptionalBool, useNoteProperty, useSyncedRef, useTriliumEvent, useTriliumOption } from "../react/hooks";+import { useIsNoteReadOnly, useNoteContext, useNoteLabel, useNoteLabelBoolean, useNoteLabelOptionalBool, useNoteProperty, useNoteRelation, useSyncedRef, useTriliumEvent, useTriliumOption } from "../react/hooks";import { ParentComponent, POPUP_EDITOR_NTX_ID, useCommandTrigger } from "../react/react_utils";import NoteActionsCustom from "./NoteActionsCustom";import { useShareState } from "./NoteBadges";@@ -61,6 +61,7 @@ export function NoteContextMenu({ note, noteContext, itemsAtStart, itemsNearNoteconst parentComponent = useContext(ParentComponent);const noteType = useNoteProperty(note, "type") ?? "";const [viewType] = useNoteLabel(note, "viewType");+ const [renderNote] = useNoteRelation(note, "renderNote");const canBeConvertedToAttachment = note?.isEligibleForConversionToAttachment();const isSourceView = noteContext?.viewScope?.viewMode === "source";const isSearchable = isSourceView@@ -73,6 +74,7 @@ export function NoteContextMenu({ note, noteContext, itemsAtStart, itemsNearNoteconst isContentAvailable = note.isContentAvailable();const isPrintable = isContentAvailable && (["text", "code", "spreadsheet", "llmChat"].includes(noteType) ||+ (noteType === "render" && !!renderNote) ||(noteType === "book" && ["presentation", "list", "table"].includes(viewType ?? "")) ||(noteType === "file" && note.mime === "application/pdf"));diff --git a/apps/desktop/src/services/printing.spec.ts b/apps/desktop/src/services/printing.spec.tsindex f0069595b8..8022d3f375 100644--- a/apps/desktop/src/services/printing.spec.ts+++ b/apps/desktop/src/services/printing.spec.ts@@ -467,4 +467,39 @@ describe("setupPrintingHandlers", () => {expect(e2.sender.send).toHaveBeenCalledWith("print-done", { type: "error", message: "load string", stack: undefined });});});++ describe("live printing", () => {+ async function fireLive(channel: string, payload: object) {+ const fn = h.on.get(channel);+ if (!fn) throw new Error(`no on-handler for ${channel}`);+ const sender = {+ send: vi.fn(),+ printToPDF: vi.fn(async () => Buffer.from("live-pdf")),+ print: vi.fn((_opts: unknown, cb: (success: boolean) => void) => cb(true))+ };+ await fn({ sender }, { ...payload, live: true });+ return sender;+ }++ it("previews the sender's own window, leaving it prepared", async () => {+ const sender = await fireLive("export-as-pdf-preview", PDF_OPTS);++ expect(h.loadURL).not.toHaveBeenCalled();+ expect(h.printToPDF).not.toHaveBeenCalled();+ expect(sender.printToPDF).toHaveBeenCalledOnce();+ expect(sender.send).toHaveBeenCalledWith("export-as-pdf-preview-result", expect.objectContaining({ requestId: 7, buffer: Buffer.from("live-pdf") }));+ expect(sender.send).not.toHaveBeenCalledWith("print-done", expect.anything());+ expect(h.destroy).not.toHaveBeenCalled();+ });++ it("prints the sender's own window and reports print-done so it is restored", async () => {+ const sender = await fireLive("print-from-preview", { ...PDF_OPTS, silent: true, deviceName: "HP" });++ expect(h.loadURL).not.toHaveBeenCalled();+ expect(h.print).not.toHaveBeenCalled();+ expect(sender.print).toHaveBeenCalledWith(expect.objectContaining({ silent: true, deviceName: "HP" }), expect.any(Function));+ expect(sender.send).toHaveBeenCalledWith("print-done", { type: "single-note" });+ expect(h.destroy).not.toHaveBeenCalled();+ });+ });});diff --git a/apps/desktop/src/services/printing.ts b/apps/desktop/src/services/printing.tsindex 4986acf530..44ea427ab6 100644--- a/apps/desktop/src/services/printing.ts+++ b/apps/desktop/src/services/printing.ts@@ -41,6 +41,8 @@ interface PrintOpts {interface ExportAsPdfOpts {notePath: string;+ /** Prints the sender's own window, which the renderer prepared for printing, instead of `notePath`. */+ live?: boolean;title: string;landscape: boolean;pageSize: "A0" | "A1" | "A2" | "A3" | "A4" | "A5" | "A6" | "Legal" | "Letter" | "Tabloid" | "Ledger";@@ -176,6 +178,19 @@ async function getBrowserWindowForPrinting(e: IpcMainEvent, notePath: string, ac}}+/**+ * Returns the page a print job prints: the sender's own window for a live print, otherwise a new+ * window rendering `notePath`. `dispose` releases it once the job is done.+ */+async function getPrintTarget(e: IpcMainEvent, notePath: string, action: "printing" | "exporting_pdf", live?: boolean) {+ if (live) {+ return { webContents: e.sender, printReport: undefined, dispose: () => {} };+ }++ const { browserWindow, printReport } = await getBrowserWindowForPrinting(e, notePath, action);+ return { webContents: browserWindow.webContents, printReport, dispose: () => browserWindow.destroy() };+}+/** Loads the print page into `browserWindow` and resolves with its report once the note is ready. */async function loadPrintPage(browserWindow: Electron.BrowserWindow, notePath: string): Promise<unknown> {// Load through the custom protocol so the print window is same-origin@@ -319,12 +334,12 @@ export function setupPrintingHandlers() {}});- electron.ipcMain.on("export-as-pdf-preview", async (e, { notePath, requestId, landscape, pageSize, scale, margins, pageRanges }: PreviewOpts) => {+ electron.ipcMain.on("export-as-pdf-preview", async (e, { notePath, live, requestId, landscape, pageSize, scale, margins, pageRanges }: PreviewOpts) => {try {- const { browserWindow, printReport } = await getBrowserWindowForPrinting(e, notePath, "exporting_pdf");+ const { webContents, printReport, dispose } = await getPrintTarget(e, notePath, "exporting_pdf", live);try {- const buffer = await browserWindow.webContents.printToPDF({+ const buffer = await webContents.printToPDF({landscape,pageSize,scale,@@ -347,8 +362,9 @@ export function setupPrintingHandlers() {const message = err instanceof Error ? err.message : String(err);e.sender.send("export-as-pdf-preview-result", { notePath, requestId, error: message });} finally {- e.sender.send("print-done", printReport);- browserWindow.destroy();+ // A live print stays prepared until the print itself is done.+ if (!live) e.sender.send("print-done", printReport);+ dispose();}} catch (err) {// The preview dialog reports the error itself, so no `print-done` goes out.@@ -400,9 +416,9 @@ export function setupPrintingHandlers() {}});- electron.ipcMain.on("print-from-preview", async (e, { notePath, landscape, pageSize, scale, margins, pageRanges, silent, deviceName }: PrintFromPreviewOpts) => {+ electron.ipcMain.on("print-from-preview", async (e, { notePath, live, landscape, pageSize, scale, margins, pageRanges, silent, deviceName }: PrintFromPreviewOpts) => {try {- const { browserWindow, printReport } = await getBrowserWindowForPrinting(e, notePath, "printing");+ const { webContents, printReport, dispose } = await getPrintTarget(e, notePath, "printing", live);// print() accepts most of the same options as printToPDF, but typing differs// slightly (e.g. no "Ledger" pageSize). Cast to keep this concise.@@ -419,13 +435,14 @@ export function setupPrintingHandlers() {printBackground: true};- browserWindow.webContents.print(printOpts, (success, failureReason) => {+ webContents.print(printOpts, (success, failureReason) => {if (!success && failureReason !== "Print job canceled") {electron.dialog.showErrorBox(t("pdf.unable-to-print"), failureReason);}e.sender.send("print-from-preview-done");- e.sender.send("print-done", printReport);- browserWindow.destroy();+ // Also sent for a live print: it is what restores the sender's window.+ e.sender.send("print-done", printReport ?? { type: "single-note" });+ dispose();});} catch (err) {e.sender.send("print-from-preview-done");diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/Notes/Printing & Exporting as PDF.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/Notes/Printing & Exporting as PDF.htmlindex 4b547fabc1..7200880573 100644--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/Notes/Printing & Exporting as PDF.html+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/Notes/Printing & Exporting as PDF.html@@ -138,6 +138,9 @@is enforced.</li></ul></li>+ <li>A <a class="reference-link" href="#root/_help_HcABDtFCkbFN">Render Note</a> is+ printed as it is displayed, without running its script again, once its <code>~renderNote</code> relation+ is set.</li><li>For <a class="reference-link" href="#root/_help_GTwFsgaA0lCt">Collections</a>,the following are supported:<ul>diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Render Note.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Render Note.htmlindex ba21f0cf74..93fc8014e1 100644--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Render Note.html+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Note Types/Render Note.html@@ -76,6 +76,20 @@ $dateEl.text(new Date());</code></pre><li>The “Render active note” <a href="#root/_help_A9Oc6YKKc65v">keyboard shortcut</a> (notassigned by default).</li></ul>+<h2>Printing</h2>+<p>A render note can be printed or exported as PDF from the <a class="reference-link"+ href="#root/_help_8YBEPzcpUgxw">Note menu</a> once its <code>~renderNote</code> relation+ is set (see <a class="reference-link" href="#root/_help_NRnIZmSMc5sj">Printing & Exporting as PDF</a>).+ Unlike other notes, it is printed exactly as it is displayed: the script+ does not run again, so what was typed, selected or loaded in the note is+ kept.</p>+<ul>+ <li>The content is laid out again at the width of the page, so elements sized+ by the script for the screen (such as charts) might not fit.</li>+ <li>Containers with a fixed height and scrolling are cut off on paper. Use+ a <code>~printCss</code> relation to give them an automatic height.</li>+ <li>The light colors are used for printing, whatever the current theme.</li>+</ul><h2>Examples</h2><ul><li><a class="reference-link" href="#root/_help_R7abl2fc6Mxi">Weight Tracker</a> whichdiff --git a/docs/User Guide/User Guide/Basic Concepts and Features/Notes/Printing & Exporting as PDF.md b/docs/User Guide/User Guide/Basic Concepts and Features/Notes/Printing & Exporting as PDF.mdindex b72374172d..48b58cb37c 100644--- a/docs/User Guide/User Guide/Basic Concepts and Features/Notes/Printing & Exporting as PDF.md+++ b/docs/User Guide/User Guide/Basic Concepts and Features/Notes/Printing & Exporting as PDF.md@@ -99,6 +99,7 @@ Not all <a class="reference-link" href="../../Note%20Types.md">Note Types</a>* For <a class="reference-link" href="../../Note%20Types/Code.md">Code</a> notes:* Line numbers are not printed.* Syntax highlighting is enabled, however a default theme (Visual Studio) is enforced.+* A <a class="reference-link" href="../../Note%20Types/Render%20Note.md">Render Note</a> is printed as it is displayed, without running its script again, once its `~renderNote` relation is set.* For <a class="reference-link" href="../../Collections.md">Collections</a>, the following are supported:* <a class="reference-link" href="../../Collections/List%20View.md">List View</a>, allowing to print multiple notes at once while preserving hierarchy (similar to a book).* <a class="reference-link" href="../../Collections/Presentation.md">Presentation</a>, where each slide/sub-note is displayed.diff --git a/docs/User Guide/User Guide/Note Types/Render Note.md b/docs/User Guide/User Guide/Note Types/Render Note.mdindex 90e95c35eb..135814ee23 100644--- a/docs/User Guide/User Guide/Note Types/Render Note.md+++ b/docs/User Guide/User Guide/Note Types/Render Note.md@@ -67,6 +67,14 @@ It's possible to refresh the note via:* The <span class="tn-icon bx bx-refresh"></span> button in the <a class="reference-link" href="../Basic%20Concepts%20and%20Features/UI%20Elements/Note%20buttons.md">Note buttons</a> area.* The “Render active note” [keyboard shortcut](../Basic%20Concepts%20and%20Features/Keyboard%20Shortcuts.md) (not assigned by default).+## Printing++A render note can be printed or exported as PDF from the <a class="reference-link" href="../Basic%20Concepts%20and%20Features/UI%20Elements/Note%20menu.md">Note menu</a> once its `~renderNote` relation is set (see <a class="reference-link" href="../Basic%20Concepts%20and%20Features/Notes/Printing%20%26%20Exporting%20as%20PDF.md">Printing & Exporting as PDF</a>). Unlike other notes, it is printed exactly as it is displayed: the script does not run again, so what was typed, selected or loaded in the note is kept.++* The content is laid out again at the width of the page, so elements sized by the script for the screen (such as charts) might not fit.+* Containers with a fixed height and scrolling are cut off on paper. Use a `~printCss` relation to give them an automatic height.+* The light colors are used for printing, whatever the current theme.+## Examples* <a class="reference-link" href="../Advanced%20Usage/Advanced%20Showcases/Weight%20Tracker.md">Weight Tracker</a> which is present in the <a class="reference-link" href="../Advanced%20Usage/Database/Demo%20Notes.md">Demo Notes</a>.\ No newline at end of file