브라우저에서 ESC/POS 인쇄: 개발자 가이드

브라우저 인쇄 문제

웹 앱에서 영수증을 인쇄하려고 시도해 본 적이 있다면 그 고통을 아실 겁니다. window.print()는 인쇄 대화 상자를 열고, 페이지를 PDF로 렌더링하며, 자동 절단 또는 사용자 정의 용지 너비와 같은 ESC/POS 명령을 전혀 지원하지 않습니다.

열전사 영수증 프린터의 경우 이는 치명적인 단점입니다. 다음이 필요합니다:

  • 자동 인쇄 — 대화 상자 없음, 사용자 상호 작용 없음
  • ESC/POS 명령 — 자동 절단, 굵은 글씨, 정렬, 바코드용
  • 안정적인 인코딩 — 프린터에 맞는 UTF-8에서 올바른 코드 페이지로
  • 크로스 플랫폼 지원 — Mac, Windows, Linux

해결책은 로컬 WebSocket 브릿지입니다. 이는 사용자 컴퓨터에서 실행되는 작은 백그라운드 앱으로, 웹 앱에서 인쇄 작업을 수락하고 원시 ESC/POS 명령을 프린터로 보냅니다.


WebSocket 브릿지 작동 방식

귀하의 웹 앱  →  WebSocket (ws://localhost:8765)  →  인쇄 에이전트  →  열전사 프린터

흐름은 간단합니다:

  1. 귀하의 웹 앱은 ws://localhost:8765로 WebSocket 연결을 엽니다.
  2. 영수증을 설명하는 JSON 페이로드를 보냅니다.
  3. 인쇄 에이전트가 이를 ESC/POS로 변환하여 프린터로 보냅니다.
  4. 프린터는 자동으로 인쇄합니다 — 대화 상자 없음, 드라이버 상호 작용 없음

MenuForma Print Agent는 이 브릿지를 구현합니다. 무료 오픈 소스이며 Mac, Windows, Linux에서 실행됩니다.


API 참조

연결

const ws = new WebSocket('ws://localhost:8765');

ws.onopen = () => {
  console.log('Print Agent connected');
};

ws.onerror = () => {
  console.log('Print Agent not running');
};

에이전트 상태 확인

에이전트가 실행 중인지 확인하기 위해 핑을 보냅니다:

ws.send(JSON.stringify({ type: 'ping' }));

ws.onmessage = (event) => {
  const data = JSON.parse(event.data);
  if (data.type === 'pong') {
    console.log('Agent version:', data.version);
  }
};

영수증 인쇄

const receipt = {
  type: 'print',
  printer: 'auto',   // 또는 '192.168.1.100'과 같은 특정 IP
  data: {
    storeName: 'My Restaurant',
    storeAddress: '123 Main St',
    orderNumber: '#1042',
    tableNumber: 'Table 5',
    items: [
      { name: 'Margherita Pizza', qty: 1, price: 14.90 },
      { name: 'Sparkling Water', qty: 2, price: 3.50 },
    ],
    subtotal: 21.90,
    tax: 1.97,
    total: 23.87,
    paymentMethod: 'Card',
    footer: 'Thank you for dining with us!',
  }
};

ws.send(JSON.stringify(receipt));

React 통합 예시

import { useEffect, useRef, useCallback, useState } from 'react';

function usePrintAgent() {
  const wsRef = useRef(null);
  const [connected, setConnected] = useState(false);

  useEffect(() => {
    const connect = () => {
      const ws = new WebSocket('ws://localhost:8765');
      ws.onopen = () => setConnected(true);
      ws.onclose = () => {
        setConnected(false);
        setTimeout(connect, 3000); // 재시도
      };
      wsRef.current = ws;
    };
    connect();
    return () => wsRef.current?.close();
  }, []);

const print = useCallback((receiptData) => { if (!wsRef.current || wsRef.current.readyState !== WebSocket.OPEN) { throw new Error('Print Agent not connected'); } wsRef.current.send(JSON.stringify({ type: 'print', data: receiptData })); }, []);

return { connected, print }; }


---

## Shopify 통합

Shopify 스토어의 경우, 주문 웹훅 또는 브라우저 확장 프로그램에서 인쇄를 트리거할 수 있습니다:

```javascript
// In your Shopify storefront or admin extension
async function printShopifyOrder(order) {
  const ws = new WebSocket('ws://localhost:8765');
  
  ws.onopen = () => {
    ws.send(JSON.stringify({
      type: 'print',
      data: {
        storeName: order.shop_name,
        orderNumber: order.name,
        items: order.line_items.map(item => ({
          name: item.title,
          qty: item.quantity,
          price: parseFloat(item.price),
        })),
        total: parseFloat(order.total_price),
        paymentMethod: order.payment_gateway,
      }
    }));
  };
}

프린터 구성

인쇄 페이로드의 "printer" 필드는 다음을 허용합니다:

설명
"auto" Print Agent 설정에 구성된 프린터 사용
"192.168.1.100" IP로 네트워크 프린터에 직접 연결
"USB" 처음 감지된 USB 프린터 사용

오류 처리

ws.onmessage = (event) => {
  const response = JSON.parse(event.data);
  
  if (response.type === 'print_success') {
    console.log('Printed successfully');
  } else if (response.type === 'print_error') {
    console.error('Print failed:', response.error);
    // Show fallback UI or retry
  }
};

Print Agent 설치 여부 감지

UI에 인쇄 기능을 표시하기 전에 에이전트가 실행 중인지 확인하십시오:

async function isPrintAgentAvailable() {
  return new Promise((resolve) => {
    const ws = new WebSocket('ws://localhost:8765');
    const timeout = setTimeout(() => {
      ws.close();
      resolve(false);
    }, 1000);
    ws.onopen = () => {
      clearTimeout(timeout);
      ws.close();
      resolve(true);
    };
    ws.onerror = () => {
      clearTimeout(timeout);
      resolve(false);
    };
  });
}

// Usage
const agentAvailable = await isPrintAgentAvailable();
if (!agentAvailable) {
  // Show download prompt
  window.open('/print-agent', '_blank');
}

Print Agent 다운로드

MenuForma Print Agent는 Mac, Windows 및 Linux에서 무료로 사용할 수 있습니다. USB, 네트워크 및 Bluetooth 감열식 프린터를 지원하며, 이 가이드에 설명된 전체 WebSocket API를 구현합니다.

전체 API 문서 및 오픈 소스 코드는 Print Agent 페이지를 참조하십시오.

Related Articles

MenuForma Products