type PrintHtmlDocumentParams = { title: string; html: string; widthMm?: number; styles?: string; }; const defaultStyles = ` * { box-sizing: border-box; } html, body { margin: 0; padding: 0; background: #fff; color: #111; font-family: Tahoma, Arial, sans-serif; direction: rtl; } @page { size: 80mm auto; margin: 4mm; } .receipt { width: 100%; } `; export const printHtmlDocument = ({ title, html, widthMm = 80, styles, }: PrintHtmlDocumentParams): void => { if (typeof window === "undefined") return; const printWindow = window.open("", "_blank"); if (!printWindow) return; const safeTitle = title.replace(//g, ">"); const pageStyles = styles ?? defaultStyles.replace("80mm", `${widthMm}mm`); const pageHtml = ` ${safeTitle} ${html} `; printWindow.document.open(); printWindow.document.write(pageHtml); printWindow.document.close(); const handlePrint = () => { printWindow.focus(); printWindow.print(); setTimeout(() => { printWindow.close(); }, 200); }; // Some browsers complete loading too fast for onload assignment. if (printWindow.document.readyState === "complete") { setTimeout(handlePrint, 50); return; } printWindow.addEventListener("load", () => { setTimeout(handlePrint, 50); }, { once: true }); };