4,554
edits
No edit summary |
No edit summary Tag: Reverted |
||
Line 1,428: | Line 1,428: | ||
waitSpecificFont(1200), | waitSpecificFont(1200), | ||
nextFrame(), // settle layout | nextFrame(), // settle layout | ||
]).then(function () { | ]).then(async function () { | ||
try { | try { | ||
// === Dynamically set page height to match content === | |||
function pxToMm(px) { | |||
return (px * 25.4) / 96; | |||
} | |||
// 1) Locate wrapper inside the print iframe | |||
var wrapper = | |||
doc.querySelector(".entry-wrapper.print-a4-narrow") || | |||
doc.querySelector(".print-only") || | |||
doc.body; | |||
// Force reflow | |||
void wrapper.offsetHeight; | |||
// 2) Measure height in px | |||
var contentPx = wrapper.scrollHeight; | |||
var contentMm = Math.ceil(pxToMm(contentPx) + 2); // +2mm buffer | |||
// 3) Account for @page margins (12mm top + bottom) | |||
var topBottomMarginsMm = 24; | |||
var targetPageMm = contentMm + topBottomMarginsMm; | |||
// 4) Clamp so it never exceeds A4 height (297mm), | |||
// but don’t go below a minimal height either | |||
targetPageMm = Math.min(Math.max(targetPageMm, 120), 297); | |||
// 5) Inject overriding @page rule | |||
var dyn = doc.createElement("style"); | |||
dyn.setAttribute("id", "dynamic-print-size"); | |||
dyn.textContent = | |||
"@page { size: 93mm " + targetPageMm + "mm; margin: 12mm; }"; | |||
doc.head.appendChild(dyn); | |||
// 6) Let the iframe layout with the new page size | |||
await new Promise(function (res) { | |||
( | |||
iframe.contentWindow.requestAnimationFrame || setTimeout | |||
)(res, 0); | |||
}); | |||
// 7) Print! | |||
iframe.contentWindow.focus(); | |||
iframe.contentWindow.print(); | |||
} catch (e) { | |||
console.warn("[print] dynamic sizing failed:", e); | |||
iframe.contentWindow.focus(); | iframe.contentWindow.focus(); | ||
iframe.contentWindow.print(); | iframe.contentWindow.print(); | ||
} finally { | } finally { | ||
// fallback cleanup in case onafterprint | // fallback cleanup in case onafterprint doesn’t fire | ||
setTimeout(function () { | setTimeout(function () { | ||
if (iframe.parentNode) iframe.parentNode.removeChild(iframe); | if (iframe.parentNode) iframe.parentNode.removeChild(iframe); |