From 18149483f22b0ae56ebc2786424a7c659e90351f Mon Sep 17 00:00:00 2001 From: Timothy Jaeryang Baek Date: Sun, 4 May 2025 16:59:41 +0400 Subject: [PATCH] refac: note pdf export --- src/lib/components/notes/Notes.svelte | 21 ++++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/src/lib/components/notes/Notes.svelte b/src/lib/components/notes/Notes.svelte index 6fc98ede9..ea4c96c99 100644 --- a/src/lib/components/notes/Notes.svelte +++ b/src/lib/components/notes/Notes.svelte @@ -97,8 +97,20 @@ const virtualWidth = 1024; // Fixed width (adjust as needed) const virtualHeight = 1400; // Fixed height (adjust as needed) + // STEP 1. Get a DOM node to render + const html = note.data?.content?.html ?? ''; + let node; + if (html instanceof HTMLElement) { + node = html; + } else { + // If it's HTML string, render to a temporary hidden element + node = document.createElement('div'); + node.innerHTML = html; + document.body.appendChild(node); + } + // Render to canvas with predefined width - const canvas = await html2canvas(note.data.content.html, { + const canvas = await html2canvas(node, { useCORS: true, scale: 2, // Keep at 1x to avoid unexpected enlargements width: virtualWidth, // Set fixed virtual screen width @@ -106,6 +118,11 @@ windowHeight: virtualHeight }); + // Remove hidden node if needed + if (!(html instanceof HTMLElement)) { + document.body.removeChild(node); + } + const imgData = canvas.toDataURL('image/png'); // A4 page settings @@ -133,6 +150,8 @@ pdf.save(`${note.title}.pdf`); } catch (error) { console.error('Error generating PDF', error); + + toast.error(`${error}`); } };