|
| 1 | +import type { Instance } from "@nutrient-sdk/viewer"; |
| 2 | +import { baseOptions } from "../../shared/base-options"; |
| 3 | + |
| 4 | +window.NutrientViewer.load({ |
| 5 | + ...baseOptions, |
| 6 | + theme: window.NutrientViewer.Theme.DARK, |
| 7 | +}).then((instance: Instance) => { |
| 8 | + const panel = document.createElement("div"); |
| 9 | + panel.style.cssText = |
| 10 | + "position:fixed;top:10px;right:10px;z-index:99999;background:#2d2d2d;color:#e0e0e0;padding:12px;border:1px solid #555;border-radius:8px;font:12px system-ui;max-width:280px"; |
| 11 | + panel.innerHTML = ` |
| 12 | + <div style="font-weight:600;margin-bottom:8px">Print selected pages</div> |
| 13 | + <button id="btn-print-current" style="width:100%;padding:8px;margin-bottom:8px;background:#007aff;color:#fff;border:0;border-radius:4px;cursor:pointer">Print current page</button> |
| 14 | + <input id="inp-range" placeholder="e.g. 1,3-5,8" style="width:100%;box-sizing:border-box;padding:7px;border-radius:4px;border:1px solid #555;background:#1a1a1a;color:#e0e0e0;margin-bottom:6px" /> |
| 15 | + <button id="btn-print-range" style="width:100%;padding:8px;margin-bottom:8px;background:#34c759;color:#fff;border:0;border-radius:4px;cursor:pointer">Print selected pages</button> |
| 16 | + <label style="display:block;margin-bottom:4px"><input type="radio" name="m" value="tab" checked /> New tab</label> |
| 17 | + <label style="display:block;margin-bottom:8px"><input type="radio" name="m" value="iframe" /> Iframe auto-print (best effort)</label> |
| 18 | + <div id="log" style="background:#1a1a1a;border-radius:4px;padding:8px;font:11px ui-monospace, SFMono-Regular, Menlo, monospace;max-height:140px;overflow:auto;color:#aaa"></div> |
| 19 | +`; |
| 20 | + document.body.appendChild(panel); |
| 21 | + |
| 22 | + const logEl = panel.querySelector("#log") as HTMLElement; |
| 23 | + const log = (msg: string, level: "info" | "error" | "success" = "info") => { |
| 24 | + const c = |
| 25 | + level === "error" |
| 26 | + ? "#ff3b30" |
| 27 | + : level === "success" |
| 28 | + ? "#34c759" |
| 29 | + : "#4aa3ff"; |
| 30 | + const line = document.createElement("div"); |
| 31 | + line.style.color = c; |
| 32 | + line.textContent = `[${new Date().toLocaleTimeString()}] ${msg}`; |
| 33 | + logEl.appendChild(line); |
| 34 | + logEl.scrollTop = logEl.scrollHeight; |
| 35 | + console.log("[PrintPages]", msg); |
| 36 | + }; |
| 37 | + |
| 38 | + async function getTotalPages(): Promise<number> { |
| 39 | + if (typeof instance.totalPageCount === "number") |
| 40 | + return instance.totalPageCount; |
| 41 | + if ( |
| 42 | + instance.document && |
| 43 | + typeof instance.document.getPageCount === "function" |
| 44 | + ) |
| 45 | + return await instance.document.getPageCount(); |
| 46 | + throw new Error("Unable to determine page count from SDK instance."); |
| 47 | + } |
| 48 | + |
| 49 | + function parseRange(str: string, totalPages: number): number[] { |
| 50 | + const parts = str |
| 51 | + .split(",") |
| 52 | + .map((s) => s.trim()) |
| 53 | + .filter(Boolean); |
| 54 | + const set = new Set<number>(); |
| 55 | + |
| 56 | + for (const part of parts) { |
| 57 | + if (part.includes("-")) { |
| 58 | + const [a, b] = part |
| 59 | + .split("-") |
| 60 | + .map((s) => Number.parseInt(s.trim(), 10)); |
| 61 | + if (!Number.isInteger(a) || !Number.isInteger(b)) |
| 62 | + throw new Error(`Invalid range: "${part}"`); |
| 63 | + if (a > b) throw new Error(`Invalid range (start > end): "${part}"`); |
| 64 | + for (let p = a; p <= b; p++) { |
| 65 | + if (p < 1 || p > totalPages) |
| 66 | + throw new Error(`Page ${p} out of bounds (1-${totalPages})`); |
| 67 | + set.add(p - 1); |
| 68 | + } |
| 69 | + } else { |
| 70 | + const p = Number.parseInt(part, 10); |
| 71 | + if (!Number.isInteger(p)) throw new Error(`Invalid page: "${part}"`); |
| 72 | + if (p < 1 || p > totalPages) |
| 73 | + throw new Error(`Page ${p} out of bounds (1-${totalPages})`); |
| 74 | + set.add(p - 1); |
| 75 | + } |
| 76 | + } |
| 77 | + |
| 78 | + return Array.from(set).sort((x, y) => x - y); |
| 79 | + } |
| 80 | + |
| 81 | + async function exportSubset(pageIndexes: number[]): Promise<ArrayBuffer> { |
| 82 | + log( |
| 83 | + `Exporting pages (1-based): ${pageIndexes.map((i) => i + 1).join(", ")}`, |
| 84 | + ); |
| 85 | + const buf = await instance.exportPDFWithOperations([ |
| 86 | + { type: "keepPages", pageIndexes }, |
| 87 | + ]); |
| 88 | + log(`Export complete (${Math.round(buf.byteLength / 1024)} KB)`, "success"); |
| 89 | + return buf; |
| 90 | + } |
| 91 | + |
| 92 | + function printNewTabWithPopupSafeNavigation( |
| 93 | + buf: ArrayBuffer, |
| 94 | + preOpenedWindow: Window | null, |
| 95 | + ): void { |
| 96 | + const blob = new Blob([buf], { type: "application/pdf" }); |
| 97 | + const url = URL.createObjectURL(blob); |
| 98 | + |
| 99 | + // If we successfully opened a window synchronously, navigate it now. |
| 100 | + if (preOpenedWindow && !preOpenedWindow.closed) { |
| 101 | + preOpenedWindow.location.href = url; |
| 102 | + log("Opened subset PDF in the pre-opened tab.", "success"); |
| 103 | + } else { |
| 104 | + // Fallback attempt (may be blocked depending on browser) |
| 105 | + const w = window.open(url, "_blank", "noopener,noreferrer"); |
| 106 | + if (!w) { |
| 107 | + log( |
| 108 | + "Popup blocked. Please allow popups, or switch to iframe method.", |
| 109 | + "error", |
| 110 | + ); |
| 111 | + } else { |
| 112 | + log("Opened subset PDF in a new tab.", "success"); |
| 113 | + } |
| 114 | + } |
| 115 | + |
| 116 | + // Conservative cleanup: do not revoke quickly. |
| 117 | + setTimeout(() => { |
| 118 | + try { |
| 119 | + URL.revokeObjectURL(url); |
| 120 | + } catch (_) {} |
| 121 | + log("Blob URL revoked (cleanup)."); |
| 122 | + }, 120000); |
| 123 | + } |
| 124 | + |
| 125 | + function printViaIframe(buf: ArrayBuffer): void { |
| 126 | + const blob = new Blob([buf], { type: "application/pdf" }); |
| 127 | + const url = URL.createObjectURL(blob); |
| 128 | + |
| 129 | + const iframe = document.createElement("iframe"); |
| 130 | + iframe.style.cssText = |
| 131 | + "position:fixed;left:-9999px;top:0;width:1px;height:1px;border:0"; |
| 132 | + iframe.src = url; |
| 133 | + |
| 134 | + const cleanup = () => { |
| 135 | + setTimeout(() => { |
| 136 | + try { |
| 137 | + URL.revokeObjectURL(url); |
| 138 | + } catch (_) {} |
| 139 | + try { |
| 140 | + iframe.remove(); |
| 141 | + } catch (_) {} |
| 142 | + log("Iframe cleaned up."); |
| 143 | + }, 120000); |
| 144 | + }; |
| 145 | + |
| 146 | + iframe.onload = () => { |
| 147 | + log("PDF loaded in iframe. Trying print()..."); |
| 148 | + try { |
| 149 | + iframe.contentWindow?.focus(); |
| 150 | + iframe.contentWindow?.print(); |
| 151 | + log("Print dialog triggered (iframe).", "success"); |
| 152 | + } catch (e) { |
| 153 | + log(`Iframe print failed: ${(e as Error)?.message || e}`, "error"); |
| 154 | + } finally { |
| 155 | + cleanup(); |
| 156 | + } |
| 157 | + }; |
| 158 | + |
| 159 | + iframe.onerror = () => { |
| 160 | + log("Iframe failed to load PDF.", "error"); |
| 161 | + cleanup(); |
| 162 | + }; |
| 163 | + |
| 164 | + document.body.appendChild(iframe); |
| 165 | + } |
| 166 | + |
| 167 | + async function runPrint( |
| 168 | + pageIndexes: number[], |
| 169 | + clickEvent: MouseEvent, |
| 170 | + ): Promise<void> { |
| 171 | + // Determine method and pre-open tab synchronously if needed (avoids popup blockers) |
| 172 | + const method = panel.querySelector<HTMLInputElement>( |
| 173 | + 'input[name="m"]:checked', |
| 174 | + )?.value; |
| 175 | + |
| 176 | + let preOpenedWindow: Window | null = null; |
| 177 | + if (method === "tab") { |
| 178 | + // Must happen synchronously during the click handler call stack |
| 179 | + preOpenedWindow = window.open("about:blank", "_blank"); |
| 180 | + if (!preOpenedWindow) |
| 181 | + log( |
| 182 | + "Popup blocked when opening blank tab. Will try direct open later.", |
| 183 | + "error", |
| 184 | + ); |
| 185 | + } |
| 186 | + |
| 187 | + try { |
| 188 | + const buf = await exportSubset(pageIndexes); |
| 189 | + if (method === "tab") { |
| 190 | + printNewTabWithPopupSafeNavigation(buf, preOpenedWindow); |
| 191 | + } else { |
| 192 | + printViaIframe(buf); |
| 193 | + } |
| 194 | + } catch (e) { |
| 195 | + log((e as Error)?.message || String(e), "error"); |
| 196 | + try { |
| 197 | + if (preOpenedWindow && !preOpenedWindow.closed) preOpenedWindow.close(); |
| 198 | + } catch (_) {} |
| 199 | + } |
| 200 | + } |
| 201 | + |
| 202 | + // Wire buttons |
| 203 | + panel |
| 204 | + .querySelector("#btn-print-current") |
| 205 | + ?.addEventListener("click", async (ev) => { |
| 206 | + const idx = instance.viewState?.currentPageIndex; |
| 207 | + if (typeof idx !== "number") |
| 208 | + return log("Could not read currentPageIndex from viewState.", "error"); |
| 209 | + await runPrint([idx], ev as MouseEvent); |
| 210 | + }); |
| 211 | + |
| 212 | + panel |
| 213 | + .querySelector("#btn-print-range") |
| 214 | + ?.addEventListener("click", async (ev) => { |
| 215 | + const input = ( |
| 216 | + panel.querySelector("#inp-range") as HTMLInputElement |
| 217 | + )?.value.trim(); |
| 218 | + if (!input) return log("Enter a page list, e.g. 1,3-5,8", "error"); |
| 219 | + |
| 220 | + const total = await getTotalPages(); |
| 221 | + const indexes = parseRange(input, total); |
| 222 | + if (!indexes.length) |
| 223 | + return log("No pages selected after parsing.", "error"); |
| 224 | + await runPrint(indexes, ev as MouseEvent); |
| 225 | + }); |
| 226 | + |
| 227 | + log("Print controls ready.", "success"); |
| 228 | +}); |
0 commit comments