electron-pos-printer

repository·master·Indexed 19 days ago

https://github.com/hubertformin/electron-pos-printer

A customizable Electron.js plugin for thermal receipt printers supporting widths of 80mm, 78mm, 76mm, 58mm, 57mm, and 44mm. It enables the generation and printing of structured content including text, images, barcodes, QR codes, and tables. The library provides APIs for printing via PosPrinter.print(), opening cash drawers, and sending raw ESC/POS commands. Requires Electron >= 6.x.x.

Tokens
5.2K
Snippets
14
Records
20
Agent score
63%

What's inside electron-pos-printer

  1. Define Print Data types

    master

    The data array passed to PosPrinter.print consists of objects with a type property. Supported types include:

    • text: Renders plain text. Supports a style object for CSS-like styling (e.g., fontSize, textAlign, color).
    • image: Renders an image via url or path. Supports position ('left' | 'center' | 'right'), width, and height.
    • barCode: Renders a barcode. Supports value, height, width, displayValue (boolean), and fontsize.
    • qrCode: Renders a QR code. Supports value, height, width, and style.
    • table: Renders a structured table. Supports tableHeader, tableBody, tableFooter (which can be arrays of strings or arrays of complex objects like text or image), and specific styling for each section (tableHeaderStyle, tableBodyStyle, tableFooterStyle).
    // Example of various data types
    const data = [
        { type: 'image', url: '...', position: 'center', width: '160px', height: '60px' },
        { type: 'text', value: 'TITLE', style: { fontWeight: '700', textAlign: 'center' } },
        { type: 'barCode', value: '12345', height: 40, width: 2, displayValue: true },
        { type: 'qrCode', value: 'https://...', height: 55, width: 55 },
        {
            type: 'table',
            tableHeader: ['Col1', 'Col2'],
            tableBody: [['Val1', 'Val2']],
            style: { border: '1px solid #ddd' }
        }
    ];
  2. Use PosPrinter with TypeScript

    master

    The library provides built-in types for better developer experience. Import PosPrinter, PosPrintData, and PosPrintOptions from electron-pos-printer to ensure type safety when constructing your print jobs.

    import {PosPrinter, PosPrintData, PosPrintOptions} from "electron-pos-printer";
    
    const options: PosPrintOptions = {
       preview: false,
       margin: '0 0 0 0',
       copies: 1,
       printerName: 'XP-80C',
       timeOutPerLine: 400,
       pageSize: '80mm'
    };
    
    const data: PosPrintData[] = [
        { type: 'text', value: 'TS Example' }
    ];
    
    PosPrinter.print(data, options).then(console.log);
  3. Install electron-pos-printer

    master

    You can install the package using npm or yarn to add thermal receipt printing capabilities to your Electron application. It supports thermal printers with widths such as 80mm, 78mm, 76mm, 58mm, 57mm, and 44mm. Requires Electron >= 6.x.x.

    $ npm install electron-pos-printer
    $ yarn add electron-pos-printer
  4. Configure external for Webpack or Vue-CLI

    master

    Because electron-pos-printer uses native Node APIs and must run in the Electron main process, you must mark it as an external in your bundler to prevent it from being bundled into the renderer process.

    For Webpack: Add to your webpack.config.js:

    module.exports = {
      externals: {
        'electron-pos-printer': 'commonjs electron-pos-printer',
      },
    };

    For Vue-CLI: Add to your vue.config.js:

    module.exports = {
      pluginOptions: {
        electronBuilder: {
          externals: ['electron-pos-printer'],
        },
      },
    };
    // webpack.config.js
    module.exports = {
      externals: {
        'electron-pos-printer': 'commonjs electron-pos-printer',
      },
    };
  5. Import PosPrinter in different Electron processes

    master

    Depending on where you are executing the print command, the import method for PosPrinter varies.

    In the Main Process

    Use standard require.

    In the Render Process

    If you are using Electron's remote module, use the appropriate path based on your Electron version.

    • Electron < v10.x.x: Use electron.remote.require.
    • Electron >= v10.x.x: Use @electron/remote.
    // In main process
    const {PosPrinter} = require("electron-pos-printer");
    
    // In render process (Electron < v10.x.x)
    const {PosPrinter} = require('electron').remote.require("electron-pos-printer");
    
    // In render process (Electron >= v10.x.x)
    const {PosPrinter} = require('@electron/remote').remote.require("electron-pos-printer");
  6. Send raw ESC/POS commands

    master

    You can send arbitrary ESC/POS raw bytes to the printer using PosPrinter.sendRawCommand(printerName, buffer). This is useful for manual commands like paper cutting.

    Example: Sending a manual paper cut command (ESC/POS full cut: GS V 0).

    // Send a manual paper cut command (ESC/POS full cut: GS V 0)
    PosPrinter.sendRawCommand("XP-80C", Buffer.from([0x1d, 0x56, 0x00]))
      .then(() => console.log("Paper cut sent"))
      .catch(console.error);
  7. Use PosPrinter.print() to print data

    master

    The core API is PosPrinter.print(data, options). It returns a Promise that resolves when printing is successful or rejects with an error.

    • data: An array of PosPrintData objects defining the content (text, images, barcodes, etc.).
    • options: A PosPrintOptions object defining printer settings like printerName, pageSize, and margin.
    const {PosPrinter} = require("electron-pos-printer");
    
    const options = {
        preview: false,
        margin: '0 0 0 0',
        copies: 1,
        printerName: 'XP-80C',
        timeOutPerLine: 400,
        pageSize: '80mm'
    };
    
    const data = [
        { type: 'text', value: 'Hello World' }
    ];
    
    PosPrinter.print(data, options)
     .then(console.log)
     .catch((error) => {
        console.error(error);
      });
  8. Open the cash drawer

    master

    Use PosPrinter.openCashDrawer(printerName, [options]) to send an ESC/POS cash-drawer kick command.

    Options:

    • pin: The drawer kick pin. Either 2 or 5 (default: 2).
    • onTime: Pulse on-time in milliseconds (default: 25).
    • offTime: Pulse off-time in milliseconds (default: 250).

    Platform Notes:

    • macOS / Linux: Uses lp -d <printer> -o raw.
    • Windows: Uses PowerShell. Pass the printer display name exactly as shown in Devices and Printers (e.g., "XP-80C").
    const { PosPrinter } = require("electron-pos-printer");
    
    // Open drawer on pin 2 (default)
    PosPrinter.openCashDrawer("XP-80C")
      .then(() => console.log("Cash drawer opened"))
      .catch(console.error);
    
    // Open drawer on pin 5 with custom pulse timing
    PosPrinter.openCashDrawer("XP-80C", { pin: 5, onTime: 50, offTime: 300 })
      .then(() => console.log("Cash drawer opened"))
      .catch(console.error);
  9. Structure the Print data object

    master

    The print job is composed of data objects representing rows of content.

    Important: The css property is deprecated. Use the style property instead, which accepts JSX-like syntax (e.g., {fontSize: '24px', fontWeight: '700'}).

    Supported Types:

    • text: Can be a plain string or an HTML string.
    • qrCode: Generates a QR code. Requires value, height, and width.
    • barCode: Generates a barcode. Requires value, height, and width.
    • image: Displays an image. Use path for local files or url for URLs/Base64.
    • table: Renders a table. Requires tableHeader, tableBody, and optionally tableFooter.

    Property Reference:

    PropertyTypeDescription
    typestringtext, qrCode, barCode, image, table
    valuestringThe content value
    stylePrintDataStyleCSS styles in JSX syntax (e.g., {backgroundColor: '#2196f3'})
    displayValuebooleanFor barcodes: display value below the code
    positionstringleft, center, right (for qrCode and image)
    pathstringPath or URL to image asset
    urlstringURL or Base64 encoding of image
    tableHeaderarrayColumns for the header (PosPrintTableField[] or string[])
    tableBodyarrayColumns for the body (PosPrintTableField[][] or string[][])
    tableFooterarrayColumns for the footer (PosPrintTableField[] or string[])
    tableHeaderStylestringCustom style for table header
    tableBodyStylestringCustom style for table body
    tableFooterStylestringCustom style for table footer
  10. Configure printing options

    master

    When calling the print function, you can pass an options object to control the printer behavior and page layout. Key options include:

    • printerName: The printer's name. If omitted, the system default is used.
    • copies: Number of copies to print.
    • preview: If true, shows a print preview window (default: false).
    • silent: If true, prints without showing the system printer selection window (default: true).
    • pageSize: Paper size. Supported values: 80mm, 78mm, 76mm, 58mm, 57mm, 44mm, or an object with { width, height } in pixels.
    • width / margin: Page content width and CSS-style margins (e.g., 0 10px).
    • landscape: Whether to print in landscape mode (default: false).
    • pathTemplate: Path to a custom HTML template for custom styles.
    • header / footer: Text to be printed at the top/bottom of the page.
    • timeOutPerLine: Timeout per line in milliseconds (default: 400).
    • scaleFactor: Scale factor for the web page.
    • pagesPerSheet: Number of pages per sheet.
    • collate: Whether to collate pages.
    • duplexMode: Set the duplex mode (refer to Electron's contentsPrintOptions documentation).
    • pageRanges: The page range to print (refer to Electron's contentsPrintOptions documentation).
    • margins / dpi: Advanced margin and DPI settings (refer to Electron's contentsPrintOptions documentation).
  11. Troubleshoot PosPrinter printing errors

    master

    Common reasons for PosPrinter failures:

    1. Missing Printer Name: If options.preview is false and options.silent is false, you must provide options.printerName. Otherwise, it will reject with: A printer name is required, if you don't want to specify a printer name, set silent to true.
    2. Invalid Page Size: If options.pageSize is an object, both height and width must be defined. If they are missing, it rejects with: height and width properties are required for options.pageSize.
    3. Disconnected Printer: If the print job hangs, the internal timeout will trigger, rejecting with: [TimedOutError] Make sure your printer is connected.
    4. Image Errors: If a line has type: 'image', you must provide either a path or a url. If both are missing, it rejects with: An Image url/path is required for type image.
    5. Deprecated CSS/Styles:
      • Using line.css is no longer supported. Use options.style instead.
      • line.style must be an object (e.g., { fontSize: 12 }), not a string. If a string is provided, it rejects with: `options.styles` at "${line.style}" should be an object.
    6. Renderer Process Usage: If you try to import PosPrinter directly in the Electron renderer process, it will throw: electron-pos-printer: use remote.require("electron-pos-printer") in the render process.