0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Electronでレシート印刷する

Posted at

 きっと似たようなことをしてる人はいて、情報は溢れてるとおもってたら、そうでもなくて、結構ハマったので、記録を残しておきます

システム

  • Windows 10
  • Electron 25.3.1
  • レジシステムはWebクラウドサーバ側
  • Electronアプリは、そのフロントエンド

手順

クラウド側JSから印刷指示と、レシートURLをイベント発火

window.dispatchEvent(new CustomEvent('print-recipt', { detail: { url: url, href: window.location.href } }));

クラウド側システムの都合でリファラがいるので、それも一緒に送る

Electronのpreloadプロセスでイベント中継

preload.js

window.addEventListener('print-recipt', function (e) {
    electron.ipcRenderer.send('print-recipt', e.detail);
});

印刷処理

main.js
ipcMain.on("print-recipt", function (ev, arg) {
    let printWindow = new BrowserWindow({
        parent: mainWindow,
        show: false
    });
    printWindow.webContents.on('dom-ready', () => {
        try {
            printWindow.webContents.print({
                silent: true,
                deviceName: config.receipt.printer,
                margins: {
                    marginType: 'custom'
                    , left: 0, right: 0, top: 0, bottom: 0
                },
                pageSize: { width: 72000, height: 100000 },
                dpi: { horizontal: 203, vertical: 203 },
            }, function () {
                printWindow.close();
            });
        } catch (error) {
            console.log("dom-ready:printCatch:" + error);
        }

    });
    printWindow.loadURL(config.url + arg.url, { httpReferrer: arg.href });
});
receipt.html
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <style type="text/css">
        <!--
        @page {}

        @media print {
            body {
                font-size: 12px;
                margin: 0;
                padding: 0;
                width: 100%;
            }

            div {
                padding: 0;
                margin: 0;
            }
        }

    </style>
    <title>レシート</title>
</head>

<body>

//以下略
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?