Native thermal printing via iframe — 80mm, RTL, no blank tail
Problem: window.print() on the main page used A4 height (blank paper
after receipt), no RTL direction, and Tailwind styles leaked into print.
Solution — iframe isolation:
- lib/thermal-print.ts: builds a self-contained HTML document
(@page { size: 80mm auto; margin: 0 }, html { direction: rtl })
and fires it through a hidden off-screen <iframe>. The iframe
document contains only the receipt so height == content height.
- pos-slip-modal.tsx: Print button calls printThermal(buildThermalDocument())
instead of window.print(). Preview panel is unchanged (screen only).
- pos-receipt-print.css: updated @page + direction as fallback for any
remaining window.print() callers.
Works with USB driver (Atom A300) as default printer — OS print spooler
receives the job exactly as if it were any other document.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -1,30 +1,62 @@
|
||||
/*
|
||||
* pos-receipt-print.css
|
||||
*
|
||||
* Fallback @media print styles for the slip preview panel.
|
||||
* The real thermal print job goes through thermal-print.ts (iframe) —
|
||||
* these rules only fire if window.print() is called on the main page directly.
|
||||
*/
|
||||
|
||||
@media print {
|
||||
body * {
|
||||
visibility: hidden;
|
||||
}
|
||||
#pos-slip-print-area,
|
||||
#pos-slip-print-area *,
|
||||
#receipt-print-area,
|
||||
#receipt-print-area * {
|
||||
visibility: visible;
|
||||
}
|
||||
#pos-slip-print-area,
|
||||
#receipt-print-area {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
/* 80 mm roll — height tracks the content, zero blank tail */
|
||||
@page {
|
||||
size: 80mm auto;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
/* Force RTL and thermal width on the document root */
|
||||
html {
|
||||
direction: rtl !important;
|
||||
width: 80mm !important;
|
||||
}
|
||||
|
||||
/* Hide everything except the slip */
|
||||
body > * {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
/* The modal overlay needs to be block but transparent */
|
||||
body > *:has(#pos-slip-print-area) {
|
||||
display: block !important;
|
||||
position: static !important;
|
||||
background: transparent !important;
|
||||
}
|
||||
|
||||
#pos-slip-print-area,
|
||||
#pos-slip-print-area * {
|
||||
visibility: visible !important;
|
||||
}
|
||||
|
||||
#pos-slip-print-area {
|
||||
display: block !important;
|
||||
position: static !important;
|
||||
width: 80mm !important;
|
||||
margin: 0 !important;
|
||||
padding: 3mm 4mm !important;
|
||||
border: none !important;
|
||||
border-radius: 0 !important;
|
||||
box-shadow: none !important;
|
||||
}
|
||||
}
|
||||
|
||||
#pos-slip-print-area,
|
||||
#receipt-print-area {
|
||||
width: 80mm;
|
||||
font-family: "Courier New", monospace;
|
||||
/* ── Screen preview styles ───────────────────────────────────────────────── */
|
||||
|
||||
#pos-slip-print-area {
|
||||
width: 100%;
|
||||
max-width: 76mm;
|
||||
font-family: "Tahoma", "Vazirmatn", "B Nazanin", "Courier New", monospace;
|
||||
font-size: 12px;
|
||||
direction: rtl;
|
||||
text-align: right;
|
||||
padding: 4mm;
|
||||
}
|
||||
|
||||
.receipt-divider {
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
"use client";
|
||||
|
||||
import { useTranslations, useLocale } from "next-intl";
|
||||
import { Printer } from "lucide-react";
|
||||
import type { Order } from "@/lib/api/types";
|
||||
import { formatCurrency } from "@/lib/format";
|
||||
import { formatOrderNumber } from "@/lib/order-number";
|
||||
import { buildThermalDocument, printThermal } from "@/lib/thermal-print";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import "./pos-receipt-print.css";
|
||||
|
||||
@@ -48,11 +50,15 @@ export function PosSlipModal({
|
||||
{ dateStyle: "short", timeStyle: "short" }
|
||||
).format(new Date(dateSource));
|
||||
|
||||
const table =
|
||||
order?.tableNumber ?? tableNumber ?? "—";
|
||||
const orderNo = order ? formatOrderNumber(order) : orderId ? formatOrderNumber({ id: orderId }) : null;
|
||||
const table = order?.tableNumber ?? tableNumber ?? "—";
|
||||
const orderNo = order
|
||||
? formatOrderNumber(order)
|
||||
: orderId
|
||||
? formatOrderNumber({ id: orderId })
|
||||
: null;
|
||||
const guest = order?.guestName ?? guestName;
|
||||
const printId = "pos-slip-print-area";
|
||||
|
||||
const activeBillItems = order?.items.filter((i) => !i.isVoided) ?? [];
|
||||
|
||||
const paymentKey = (method: string) => {
|
||||
const m = method.toLowerCase();
|
||||
@@ -62,13 +68,62 @@ export function PosSlipModal({
|
||||
return method;
|
||||
};
|
||||
|
||||
const activeBillItems = order?.items.filter((i) => !i.isVoided) ?? [];
|
||||
// ── Build meta row ─────────────────────────────────────────────────────────
|
||||
const metaParts: string[] = [];
|
||||
metaParts.push(`${t("table")}: ${table}`);
|
||||
if (orderNo) metaParts.push(`${t("order")}: #${orderNo}`);
|
||||
if (guest) metaParts.push(`${t("guest")}: ${guest}`);
|
||||
const metaRow = metaParts.join(" | ");
|
||||
|
||||
// ── Print handler ─────────────────────────────────────────────────────────
|
||||
const handlePrint = () => {
|
||||
const slipData =
|
||||
variant === "kitchen"
|
||||
? {
|
||||
cafeName,
|
||||
title: t("kitchenTitle"),
|
||||
date: formattedDate,
|
||||
metaRow,
|
||||
lines: kitchenLines.map((l) => ({
|
||||
name: l.name,
|
||||
quantity: l.quantity,
|
||||
notes: l.notes,
|
||||
})),
|
||||
footer: t("kitchenFooter"),
|
||||
locale,
|
||||
}
|
||||
: {
|
||||
cafeName,
|
||||
title: t("billTitle"),
|
||||
date: formattedDate,
|
||||
metaRow,
|
||||
lines: activeBillItems.map((item) => ({
|
||||
name: item.menuItemName,
|
||||
quantity: item.quantity,
|
||||
price: formatCurrency(item.unitPrice * item.quantity, numberLocale),
|
||||
})),
|
||||
totals: {
|
||||
total: formatCurrency(order!.total, numberLocale),
|
||||
payments: order!.payments?.map((p) => ({
|
||||
method: paymentKey(p.method),
|
||||
amount: formatCurrency(p.amount, numberLocale),
|
||||
})),
|
||||
},
|
||||
footer: t("thankYou"),
|
||||
locale,
|
||||
};
|
||||
|
||||
printThermal(buildThermalDocument(slipData));
|
||||
};
|
||||
|
||||
// ── Render ─────────────────────────────────────────────────────────────────
|
||||
return (
|
||||
<div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 p-4">
|
||||
<div className="w-full max-w-[340px] rounded-xl border border-border bg-background p-4 shadow-xl">
|
||||
|
||||
{/* ── Print preview ──────────────────────────────────────────────── */}
|
||||
<div
|
||||
id={printId}
|
||||
id="pos-slip-print-area"
|
||||
className="mb-4 rounded-md border border-dashed border-border p-3"
|
||||
>
|
||||
<div className="text-center text-base font-bold">{cafeName}</div>
|
||||
@@ -78,20 +133,7 @@ export function PosSlipModal({
|
||||
<div className="mb-2 text-center text-xs text-muted-foreground">
|
||||
{formattedDate}
|
||||
</div>
|
||||
<div className="text-xs">
|
||||
{t("table")}: {table}
|
||||
{orderNo ? (
|
||||
<>
|
||||
{" "}
|
||||
| {t("order")}: #{orderNo}
|
||||
</>
|
||||
) : null}
|
||||
</div>
|
||||
{guest ? (
|
||||
<div className="text-xs">
|
||||
{t("guest")}: {guest}
|
||||
</div>
|
||||
) : null}
|
||||
<div className="text-xs">{metaRow}</div>
|
||||
|
||||
<div className="receipt-divider" />
|
||||
|
||||
@@ -115,7 +157,7 @@ export function PosSlipModal({
|
||||
</div>
|
||||
))}
|
||||
|
||||
{variant === "bill" ? (
|
||||
{variant === "bill" && (
|
||||
<>
|
||||
<div className="receipt-divider" />
|
||||
<div className="receipt-row receipt-total">
|
||||
@@ -131,15 +173,19 @@ export function PosSlipModal({
|
||||
<div className="receipt-divider" />
|
||||
<div className="mt-2 text-center text-xs">{t("thankYou")}</div>
|
||||
</>
|
||||
) : (
|
||||
)}
|
||||
|
||||
{variant === "kitchen" && (
|
||||
<div className="mt-2 text-center text-[10px] text-muted-foreground">
|
||||
{t("kitchenFooter")}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* ── Actions ────────────────────────────────────────────────────── */}
|
||||
<div className="flex gap-2">
|
||||
<Button type="button" className="flex-1" onClick={() => window.print()}>
|
||||
<Button type="button" className="flex-1 gap-1.5" onClick={handlePrint}>
|
||||
<Printer className="h-4 w-4" />
|
||||
{t("print")}
|
||||
</Button>
|
||||
<Button type="button" variant="outline" className="flex-1" onClick={onClose}>
|
||||
@@ -162,6 +208,11 @@ export function PosReceiptModal({
|
||||
onClose: () => void;
|
||||
}) {
|
||||
return (
|
||||
<PosSlipModal variant="bill" order={order} cafeName={cafeName} onClose={onClose} />
|
||||
<PosSlipModal
|
||||
variant="bill"
|
||||
order={order}
|
||||
cafeName={cafeName}
|
||||
onClose={onClose}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,212 @@
|
||||
/**
|
||||
* thermal-print.ts
|
||||
*
|
||||
* Generates a self-contained 80 mm HTML document and fires it through a
|
||||
* hidden <iframe> so the browser's OS print spooler routes the job to the
|
||||
* default printer (e.g. Atom A300 USB driver).
|
||||
*
|
||||
* Why iframe instead of window.print() on the main page?
|
||||
* – The iframe document contains ONLY the receipt, so @page height = content
|
||||
* height. No blank A4 tail after the receipt.
|
||||
* – `html { direction: rtl }` is set unconditionally inside the iframe.
|
||||
* The main app's dir attribute never bleeds in.
|
||||
* – No `visibility: hidden` tricks needed — the print area IS the document.
|
||||
*/
|
||||
|
||||
export type ThermalLine = {
|
||||
name: string;
|
||||
quantity: number;
|
||||
price?: string;
|
||||
notes?: string;
|
||||
};
|
||||
|
||||
export type ThermalTotals = {
|
||||
subtotal?: string;
|
||||
discount?: string;
|
||||
tax?: string;
|
||||
total: string;
|
||||
payments?: { method: string; amount: string }[];
|
||||
};
|
||||
|
||||
export type ThermalSlipData = {
|
||||
cafeName: string;
|
||||
/** "فیش آشپزخانه" or "صورتحساب مشتری" */
|
||||
title: string;
|
||||
date: string;
|
||||
/** Pre-formatted row, e.g. "میز: ۳ | سفارش: #۱۰۵" */
|
||||
metaRow?: string;
|
||||
lines: ThermalLine[];
|
||||
totals?: ThermalTotals;
|
||||
footer?: string;
|
||||
/** 'fa' (default) → RTL, 'en' → LTR */
|
||||
locale?: string;
|
||||
};
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// Helpers
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
/** Escapes a string for safe injection into an HTML template. */
|
||||
function esc(str: string): string {
|
||||
return str
|
||||
.replace(/&/g, "&")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/"/g, """);
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// Document builder
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
export function buildThermalDocument(data: ThermalSlipData): string {
|
||||
const isRtl = (data.locale ?? "fa") !== "en";
|
||||
const dir = isRtl ? "rtl" : "ltr";
|
||||
const lang = data.locale ?? "fa";
|
||||
|
||||
const linesHtml = data.lines
|
||||
.map((l) => {
|
||||
const notePart = l.notes ? ` (${esc(l.notes)})` : "";
|
||||
return `<div class="row">
|
||||
<span>${esc(l.name)} × ${l.quantity}${notePart}</span>
|
||||
${l.price ? `<span class="price">${esc(l.price)}</span>` : ""}
|
||||
</div>`;
|
||||
})
|
||||
.join("\n");
|
||||
|
||||
let totalsHtml = "";
|
||||
if (data.totals) {
|
||||
const tt = data.totals;
|
||||
const subtotalLabel = isRtl ? "جمع اقلام" : "Subtotal";
|
||||
const discountLabel = isRtl ? "تخفیف" : "Discount";
|
||||
const taxLabel = isRtl ? "مالیات (۹٪)" : "Tax (9%)";
|
||||
const totalLabel = isRtl ? "مجموع" : "Total";
|
||||
totalsHtml = `
|
||||
<hr class="dashed">
|
||||
${tt.subtotal ? `<div class="row sm"><span>${subtotalLabel}</span><span>${esc(tt.subtotal)}</span></div>` : ""}
|
||||
${tt.discount ? `<div class="row sm"><span>${discountLabel}</span><span>- ${esc(tt.discount)}</span></div>` : ""}
|
||||
${tt.tax ? `<div class="row sm"><span>${taxLabel}</span><span>${esc(tt.tax)}</span></div>` : ""}
|
||||
<div class="row total"><span>${totalLabel}</span><span>${esc(tt.total)}</span></div>
|
||||
${(tt.payments ?? [])
|
||||
.map((p) => `<div class="row sm mt1"><span>${esc(p.method)}</span><span>${esc(p.amount)}</span></div>`)
|
||||
.join("")}
|
||||
`;
|
||||
}
|
||||
|
||||
const footerHtml = data.footer
|
||||
? `<hr class="dashed"><div class="center sm muted">${esc(data.footer)}</div>`
|
||||
: "";
|
||||
|
||||
return `<!DOCTYPE html>
|
||||
<html dir="${dir}" lang="${lang}">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<style>
|
||||
/* ── Page ─────────────────────────────────────────────────── */
|
||||
@page {
|
||||
/* 80 mm wide; height tracks the content — no blank tail */
|
||||
size: 80mm auto;
|
||||
margin: 0;
|
||||
}
|
||||
/* ── Reset ────────────────────────────────────────────────── */
|
||||
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
/* ── Root ─────────────────────────────────────────────────── */
|
||||
html, body {
|
||||
width: 80mm;
|
||||
direction: ${dir};
|
||||
font-family: 'Tahoma', 'Vazirmatn', 'B Nazanin', 'Arial', sans-serif;
|
||||
font-size: 12pt;
|
||||
color: #000;
|
||||
background: #fff;
|
||||
}
|
||||
/* ── Wrapper ──────────────────────────────────────────────── */
|
||||
.wrap { padding: 3mm 4mm 5mm; }
|
||||
/* ── Text helpers ─────────────────────────────────────────── */
|
||||
.center { text-align: center; }
|
||||
.bold { font-weight: 700; }
|
||||
.sm { font-size: 10pt; }
|
||||
.muted { color: #555; }
|
||||
.mt1 { margin-top: 1mm; }
|
||||
.mt2 { margin-top: 2mm; }
|
||||
/* ── Divider ──────────────────────────────────────────────── */
|
||||
hr.dashed { border: none; border-top: 1px dashed #000; margin: 2.5mm 0; }
|
||||
hr.solid { border: none; border-top: 1px solid #000; margin: 2.5mm 0; }
|
||||
/* ── Rows ─────────────────────────────────────────────────── */
|
||||
.row {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: baseline;
|
||||
gap: 2mm;
|
||||
line-height: 1.6;
|
||||
}
|
||||
.row .price { white-space: nowrap; }
|
||||
/* ── Totals ───────────────────────────────────────────────── */
|
||||
.total {
|
||||
font-size: 14pt;
|
||||
font-weight: 700;
|
||||
margin-top: 1mm;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="wrap">
|
||||
<div class="center bold">${esc(data.cafeName)}</div>
|
||||
<div class="center bold sm mt1">${esc(data.title)}</div>
|
||||
<div class="center sm muted mt1">${esc(data.date)}</div>
|
||||
${data.metaRow ? `<div class="sm mt2">${esc(data.metaRow)}</div>` : ""}
|
||||
<hr class="dashed">
|
||||
${linesHtml}
|
||||
${totalsHtml}
|
||||
${footerHtml}
|
||||
</div>
|
||||
</body>
|
||||
</html>`;
|
||||
}
|
||||
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
// Print trigger
|
||||
// ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
const IFRAME_ID = "meezi-thermal-print-frame";
|
||||
|
||||
/**
|
||||
* Injects (or reuses) a hidden <iframe>, writes the thermal HTML document
|
||||
* into it, then calls `iframe.contentWindow.print()`.
|
||||
*
|
||||
* The iframe is positioned off-screen so it is invisible but still mounted
|
||||
* in the DOM — required for Chrome/Edge to render it before printing.
|
||||
*/
|
||||
export function printThermal(html: string): void {
|
||||
if (typeof window === "undefined") return;
|
||||
|
||||
let frame = document.getElementById(IFRAME_ID) as HTMLIFrameElement | null;
|
||||
|
||||
if (!frame) {
|
||||
frame = document.createElement("iframe");
|
||||
frame.id = IFRAME_ID;
|
||||
frame.setAttribute("aria-hidden", "true");
|
||||
frame.setAttribute("tabindex", "-1");
|
||||
frame.style.cssText =
|
||||
"position:fixed;top:-9999px;left:-9999px;width:80mm;height:1px;" +
|
||||
"border:0;opacity:0;pointer-events:none;";
|
||||
document.body.appendChild(frame);
|
||||
}
|
||||
|
||||
const doc = frame.contentDocument ?? frame.contentWindow?.document;
|
||||
if (!doc) return;
|
||||
|
||||
doc.open();
|
||||
doc.write(html);
|
||||
doc.close();
|
||||
|
||||
// rAF gives the iframe one layout pass before we trigger the print dialog
|
||||
requestAnimationFrame(() => {
|
||||
try {
|
||||
frame!.contentWindow?.focus();
|
||||
frame!.contentWindow?.print();
|
||||
} catch {
|
||||
// Safari throws if the frame was cross-origin — shouldn't happen for
|
||||
// same-origin same-page iframes, but guard just in case.
|
||||
}
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user