How to print a DIV in ElectronJS

后端 未结 2 444
执念已碎
执念已碎 2020-12-08 11:40

i\'m trying to convert my web into an app made in ElectronJS

in my web i print a div with a barcode. this works pretty fine, but in electronjs i can\'t reach this.

2条回答
  •  隐瞒了意图╮
    2020-12-08 11:57

    You have printed this page before loading is finished.

    My approach: 1. create a mainwindow and a (invisible) worker window

    import {app, BrowserWindow, Menu, ipcMain, shell} from "electron";
    const os = require("os");
    const fs = require("fs");
    const path = require("path");
    
    let mainWindow: Electron.BrowserWindow = undefined;
    let workerWindow: Electron.BrowserWindow = undefined;
    
    async function createWindow() {
    
        mainWindow = new BrowserWindow();
        mainWindow.loadURL("file://" + __dirname + "/index.html");
        mainWindow.webContents.openDevTools();
        mainWindow.on("closed", () => {
            // close worker windows later
            mainWindow = undefined;
        });
    
        workerWindow = new BrowserWindow();
        workerWindow.loadURL("file://" + __dirname + "/worker.html");
        // workerWindow.hide();
        workerWindow.webContents.openDevTools();
        workerWindow.on("closed", () => {
            workerWindow = undefined;
        });
    }
    
    // retransmit it to workerWindow
    ipcMain.on("printPDF", (event: any, content: any) => {
        console.log(content);
        workerWindow.webContents.send("printPDF", content);
    });
    // when worker window is ready
    ipcMain.on("readyToPrintPDF", (event) => {
        const pdfPath = path.join(os.tmpdir(), 'print.pdf');
        // Use default printing options
        workerWindow.webContents.printToPDF({}).then((data) {
            fs.writeFile(pdfPath, data, function (error) {
                if (error) {
                    throw error
                }
                shell.openItem(pdfPath)
                event.sender.send('wrote-pdf', pdfPath)
            })
        }).catch((error) => {
           throw error;
        })
    });
    

    2, mainWindow.html

    
    
    
        
        
    
    

    3, worker.html

     
    
        
    
    

提交回复
热议问题