# Receipt Printer

> A thermal receipt printer housing with recessed paper slot, high-contrast itemized slip, barcode, serrated edge, and reprint feed.

- Kind: ui · Category: Data display · Interactivity: script
- Install: `npx shadcn@latest add @haze/receipt-printer`
- File: `src/components/haze/ui/receipt-printer.astro`
- npm dependencies: @lucide/astro
- Registry dependencies: @haze/utils
- Docs page: https://hazeui.com/ui/receipt-printer

## Use when
- Presenting a point-of-sale slip, coffee shop receipt, or itemized order confirmation.
- A tactile thermal printer slot and paper slip make line items, tax, and total immediately scannable.

## Avoid when
- Invoices contain dozens of editable rows or require sorting and filtering. Use table instead.
- The data is general account metadata rather than a transaction slip. Use description-list.

## Alternatives
- [card](https://hazeui.com/ui/card.md)
- [description-list](https://hazeui.com/ui/description-list.md)
- [table](https://hazeui.com/ui/table.md)

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| printerTitle | `string` | "Cedar & Grain" | no | Short title displayed in the printer housing header. |
| merchant | `string` | "Cedar & Grain Roasters" | no | Store or business name printed at the top of the receipt. |
| location | `string` | "418 Alder St, Portland" | no | Optional merchant street address or branch label. |
| receiptNumber | `string` | "#RCP-0841" | no | Receipt reference code printed beneath the merchant address. |
| date | `string` | "Nov 22, 2026 · 09:14" | no | Formatted transaction date and timestamp. |
| items | `ReceiptItem[]` |  | no | Line items with name, optional quantity, and line price. |
| taxRate | `number` | 0.08 | no | Fractional tax rate applied to the subtotal. |
| currency | `string` | "USD" | no | ISO 4217 currency code for price formatting. |
| paymentMethod | `string` | "Card ··4821" | no | Optional payment method shown in the paper footer. |
| footerNote | `string` | "Thank you!" | no | Closing note below the barcode. |
| printLabel | `string` | "Reprint" | no | Label for the reprint feed trigger button. |
| headingLevel | `2 \| 3 \| 4` | 3 | no | Heading level for the printer title. |
| class | `string` |  | no | Additional classes on the outer printer housing. |

## Accessibility
- The full thermal receipt renders visibly on initial load and stays immediately readable without JavaScript or under prefers-reduced-motion.
- The printer slot, status LED, mini barcode, and serrated tear edge are marked aria-hidden.
- Activating Reprint updates the visible status text and announces completion in an aria-live polite region.
- Key Tab then Enter or Space: Trigger the Reprint button to feed the receipt out of the slot.

## Agent prompts

### Install and use

Install the Haze UI component "Receipt Printer" with `npx shadcn@latest add @haze/receipt-printer`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "https://hazeui.com/r/{name}.json" }. If src/styles/haze.css does not exist yet, run `npx shadcn@latest add @haze/theme` once and import it from the global stylesheet after Tailwind. The CLI stops at an overwrite question when a Haze file already exists and differs, even with --yes, and then installs nothing after it: read its output. If the user has not edited their Haze files, re-run with --overwrite to take the registry versions; if they have, ask them before overwriting. Then import ReceiptPrinter from "@/components/haze/ui/receipt-printer.astro" (or the relative path) and render it where it fits the page. Keep Haze token classes (bg-background, text-muted-foreground, border-border...) and never hardcode colors. Docs: https://hazeui.com/ui/receipt-printer.md

### Customize with real content

Adapt the Haze receipt-printer ui for our product. Replace the demo values of these props with our real content: printerTitle, merchant, location, receiptNumber, date, items, taxRate, currency, paymentMethod, footerNote, printLabel, headingLevel, class. Keep the layout, the heading level rules and these accessibility details: The full thermal receipt renders visibly on initial load and stays immediately readable without JavaScript or under prefers-reduced-motion. The printer slot, status LED, mini barcode, and serrated tear edge are marked aria-hidden. Activating Reprint updates the visible status text and announces completion in an aria-live polite region. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using receipt-printer, check it fits: use it when presenting a point-of-sale slip, coffee shop receipt, or itemized order confirmation.; a tactile thermal printer slot and paper slip make line items, tax, and total immediately scannable.. Avoid it when invoices contain dozens of editable rows or require sorting and filtering. use table instead.; the data is general account metadata rather than a transaction slip. use description-list.. Alternatives: @haze/card, @haze/description-list, @haze/table.

## Example requests that should lead here
- Show a thermal receipt printer slot with a high-contrast coffee shop slip, barcode, serrated bottom edge, and Reprint button.
- Add an order confirmation receipt card feeding out of a dark printer housing with subtotal, tax, and bold total.

## Source

```astro
---
import { Printer } from "@lucide/astro";
import { cn } from "../../../lib/haze/utils";

interface ReceiptItem {
  name: string;
  quantity?: number;
  price: number;
}

interface Props {
  printerTitle?: string;
  merchant?: string;
  location?: string;
  receiptNumber?: string;
  date?: string;
  items?: ReceiptItem[];
  taxRate?: number;
  currency?: string;
  paymentMethod?: string;
  footerNote?: string;
  printLabel?: string;
  headingLevel?: 2 | 3 | 4;
  class?: string;
}

const {
  printerTitle = "Cedar & Grain",
  merchant = "Cedar & Grain Roasters",
  location = "418 Alder St, Portland",
  receiptNumber = "#RCP-0841",
  date = "Nov 22, 2026 · 09:14",
  items = [
    { name: "Oat flat white", quantity: 2, price: 11.0 },
    { name: "Cardamom knot", quantity: 1, price: 5.5 },
    { name: "House blend 250g", quantity: 1, price: 18.0 },
  ],
  taxRate = 0.08,
  currency = "USD",
  paymentMethod = "Card ··4821",
  footerNote = "Thank you!",
  printLabel = "Reprint",
  headingLevel = 3,
  class: className,
} = Astro.props;

const Heading = ({ 2: "h2", 3: "h3", 4: "h4" } as const)[headingLevel];

const safeTaxRate = Number.isFinite(taxRate) && taxRate >= 0 ? taxRate : 0;
const subtotal = items.reduce((sum, item) => sum + (Number.isFinite(item.price) ? item.price : 0), 0);
const tax = subtotal * safeTaxRate;
const total = subtotal + tax;

const money = new Intl.NumberFormat("en-US", {
  style: "currency",
  currency,
  minimumFractionDigits: 2,
  maximumFractionDigits: 2,
});
const taxPct = `${(safeTaxRate * 100).toFixed(1).replace(/\.0$/, "")}%`;

// Build 18 crisp serrated paper teeth across a 240-unit wide SVG strip.
const teethCount = 18;
const step = 240 / teethCount;
const toothPoints: string[] = [];
for (let i = 0; i < teethCount; i++) {
  const x0 = i * step;
  const xMid = x0 + step / 2;
  const x1 = x0 + step;
  if (i === 0) toothPoints.push(`${x0},0`);
  toothPoints.push(`${xMid},9`, `${x1},0`);
}
const edgeFill = `0,0 ${toothPoints.join(" ")} 240,0`;
const edgeLine = toothPoints.join(" ");

// Deterministic mini barcode bars derived from receiptNumber.
const bars: { x: number; w: number }[] = [];
let cursor = 4;
const seed = receiptNumber.length ? receiptNumber : "RCP0841";
let idx = 0;
while (cursor < 172) {
  const code = seed.charCodeAt(idx % seed.length) + idx * 13;
  const w = (code % 3) + 1.25;
  const gap = ((code >> 1) % 3) + 1.5;
  if (cursor + w <= 176) bars.push({ x: cursor, w });
  cursor += w + gap;
  idx++;
}
---

<section
  data-haze-receipt-printer
  class={cn(
    "flex w-full max-w-[330px] min-w-0 flex-col rounded-xl border border-border bg-card p-4 text-card-foreground",
    className,
  )}
>
  <header class="mb-4 flex flex-wrap items-center justify-between gap-x-3 gap-y-2">
    <Heading class="min-w-0 text-xs/4 font-medium text-foreground">{printerTitle}</Heading>
    <div class="flex shrink-0 items-center gap-3">
      <span class="inline-flex items-center gap-1.5 text-xs/4 text-muted-foreground">
        <span
          data-receipt-led
          aria-hidden="true"
          class="size-1.5 shrink-0 rounded-full bg-success transition-colors duration-200 ease-snappy data-[printing]:bg-brand motion-safe:data-[printing]:animate-pulse"
        ></span>
        <span data-receipt-state>Ready</span>
      </span>
      <button
        type="button"
        data-receipt-print
        class="hidden h-8 cursor-pointer items-center gap-1.5 rounded-lg bg-muted px-3 text-xs/4 font-medium text-foreground transition-[color,background-color,scale] duration-150 ease-snappy active:scale-[0.97] active:duration-100 hover:bg-accent focus-visible:outline-2 focus-visible:outline-offset-1 focus-visible:outline-ring disabled:opacity-50 [[data-haze-receipt-printer][data-enhanced]_&]:inline-flex"
      >
        <Printer aria-hidden="true" class="size-3.5" />
        {printLabel}
      </button>
    </div>
  </header>

  <div aria-hidden="true" class="relative z-10 mx-1 h-1.5 rounded-full bg-muted"></div>

  <div class="mx-4 overflow-hidden">
    <div data-receipt-paper class="transition-transform duration-700 ease-snappy">
      <div class="grid min-w-0 gap-3 border-x border-transparent bg-primary px-4 pt-4 pb-3 font-mono text-xs/4 text-primary-foreground [[data-theme=light]_&]:border-border-strong [[data-theme=light]_&]:bg-muted [[data-theme=light]_&]:text-foreground">
        <div class="grid gap-1 text-center">
          <p class="font-semibold tracking-wider uppercase wrap-anywhere">{merchant}</p>
          {location && <p class="opacity-70 wrap-anywhere">{location}</p>}
          <p class="opacity-70 tabular-nums wrap-anywhere">
            {date} · {receiptNumber}
          </p>
        </div>

        <div aria-hidden="true" class="border-t border-dashed border-current/30"></div>

        <ul role="list" class="grid min-w-0 gap-1.5">
          {items.map((item) => (
            <li class="grid min-w-0 grid-cols-[minmax(0,1fr)_auto] items-baseline gap-2">
              <span class="min-w-0 wrap-anywhere">
                {item.name}
                {item.quantity && item.quantity > 1 ? (
                  <span class="ml-1 opacity-70 tabular-nums">×{item.quantity}</span>
                ) : null}
              </span>
              <span class="shrink-0 tabular-nums">{money.format(item.price)}</span>
            </li>
          ))}
        </ul>

        <div aria-hidden="true" class="border-t border-dashed border-current/30"></div>

        <dl class="grid gap-1">
          <div class="flex items-baseline justify-between gap-2 opacity-70">
            <dt>Subtotal</dt>
            <dd class="tabular-nums">{money.format(subtotal)}</dd>
          </div>
          <div class="flex items-baseline justify-between gap-2 opacity-70">
            <dt>Tax ({taxPct})</dt>
            <dd class="tabular-nums">{money.format(tax)}</dd>
          </div>
          <div class="mt-2 flex items-baseline justify-between gap-2 border-t border-dashed border-current/30 pt-2 text-sm/5 font-semibold">
            <dt>Total</dt>
            <dd class="tabular-nums">{money.format(total)}</dd>
          </div>
        </dl>

        <svg aria-hidden="true" viewBox="0 0 180 30" preserveAspectRatio="none" class="mx-auto h-7 w-full max-w-44 text-current">
          {bars.map(({ x, w }) => (
            <rect x={x} y="2" width={w} height="26" fill="currentColor" />
          ))}
        </svg>

        <footer class="grid gap-0.5 text-center opacity-70">
          {paymentMethod && <p class="tabular-nums">{paymentMethod}</p>}
          {footerNote && <p>{footerNote}</p>}
        </footer>
      </div>

      <svg aria-hidden="true" viewBox="0 0 240 10" preserveAspectRatio="none" class="-mt-px block h-2.5 w-full text-primary [[data-theme=light]_&]:text-muted">
        <polygon points={edgeFill} fill="currentColor" />
        <polyline points={edgeLine} fill="none" vector-effect="non-scaling-stroke" class="stroke-transparent [[data-theme=light]_&]:stroke-border-strong" />
      </svg>
    </div>
  </div>

  <p data-receipt-status aria-live="polite" class="sr-only"></p>
</section>

<script>
  function enhance(root: HTMLElement) {
    if (root.hasAttribute("data-enhanced")) return;
    const button = root.querySelector<HTMLButtonElement>("[data-receipt-print]");
    const paper = root.querySelector<HTMLElement>("[data-receipt-paper]");
    const stateEl = root.querySelector<HTMLElement>("[data-receipt-state]");
    const ledEl = root.querySelector<HTMLElement>("[data-receipt-led]");
    const status = root.querySelector<HTMLElement>("[data-receipt-status]");
    if (!button || !paper) return;

    let timer = 0;

    button.addEventListener("click", () => {
      window.clearTimeout(timer);

      if (window.matchMedia("(prefers-reduced-motion: reduce)").matches) {
        paper.classList.remove("transition-none", "-translate-y-full");
        if (stateEl) stateEl.textContent = "Ready";
        ledEl?.removeAttribute("data-printing");
        if (status) status.textContent = "Receipt reprinted.";
        return;
      }

      button.disabled = true;
      if (stateEl) stateEl.textContent = "Printing...";
      ledEl?.setAttribute("data-printing", "");
      if (status) status.textContent = "Printing receipt.";

      paper.classList.add("transition-none", "-translate-y-full");
      // Force layout flush so the paper snaps cleanly into the slot before feeding out.
      void paper.offsetHeight;
      paper.classList.remove("transition-none");
      paper.classList.remove("-translate-y-full");

      timer = window.setTimeout(() => {
        button.disabled = false;
        if (stateEl) stateEl.textContent = "Ready";
        ledEl?.removeAttribute("data-printing");
        if (status) status.textContent = "Receipt printed.";
      }, 740);
    });

    root.setAttribute("data-enhanced", "");
  }

  const init = () => document.querySelectorAll<HTMLElement>("[data-haze-receipt-printer]").forEach(enhance);
  init();
  if (!document.documentElement.hasAttribute("data-haze-receipt-printer-listener")) {
    document.documentElement.setAttribute("data-haze-receipt-printer-listener", "");
    document.addEventListener("astro:page-load", init);
  }
</script>
```
