首页 > 解决方案 > 我正在尝试在 electronjs 上打印页面,但是当我按照复制代码时它不会打印或给出任何错误

问题描述

我正在尝试在 electronjs 上打印页面,我尝试按照 youtube 上的分步视频进行操作,并且我尝试复制人们说它有效的每个代码,但是当我尝试它时没有任何反应,没有打印页面,控制台日志上没有错误。是电子网站上的文档不再起作用还是我在代码上做错了什么?

下面的这段代码是我从某个 youtube 视频中遵循的,从我看到的应该可以工作

这是我的 main.js

const electron = require('electron');
const { Menu } = require('electron');
const app = electron.app;
const BrowserWindow = electron.BrowserWindow; 
const path = require('path');
const url = require('url');
const isDev = require('electron-is-dev');

const fs = require('fs');
const os  = require('os');
const ipc = electron.ipcMain;
const shell =electron.shell;

let mainWindow;

ipc.on('print-to-pdf', function(event){
  const pdfpath = path.join(os.tmpdir(), 'print.pdf');
  const win = BrowserWindow.fromWebContents(event.sender);
  win.webContents.printToPDF({}, function(error, data){
    if(error) return console.log(error.message);

    fs.writeFile(pdfpath, data, function(err){
      if(err) return console.log(err.message);
      shell.openExternal('file://'+pdfpath );
      event.sender.send('wrote-pdf', pdfpath);
    })
  })
});

这是我的 renderer.js

const ipc = require('electron').ipcRenderer;

const printpdfbutton  = document.getElementById('print-pdf');

printpdfbutton.addEventListener('click', function(event){
    ipc.send('print-to-pdf');
});

ipc.on('wrote-pdf', function(event, path){
    const message = `wrote PDF to : ${path}`;
    document.getElementById('pdf-path').innerHTML = message;
});

这是我的 index.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="podium.png" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta name="theme-color" content="#000000" />
    <meta
      name="description"
      content="Web site created using create-react-app"
    />
    <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
    <link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
    <title>React App</title>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
    <button id='print-pdf'>Convert to PDF</button>
    <label id='pdf-path'></label>
      <!-- Don't go beyond this -->
  </body>

    <script>
      require('./renderer.js');
    </script>
</html>

也许解决方案是使用依赖关系或者还有其他代码有效?

请帮助我,谢谢

标签: javascriptreactjselectron

解决方案


推荐阅读