webContents.printtoPDF() 总是返回长度为 661 字节的空数据

Joh*_*n O 0 javascript pdf node.js electron

我的代码如下所示:

function pdfSettings(h, w) {
  var MICRONS_PER_IN = 25400;

  var option = {
      landscape: false,
      marginsType: 0,
      printBackground: true,
      printSelectionOnly: false,
      pageSize:{width:(w * MICRONS_PER_IN), height:(h * MICRONS_PER_IN)},
  };
  return option;
}
Run Code Online (Sandbox Code Playgroud)

  win.webContents.printToPDF(pdfSettings('8.25','5.375'), function(err, data) {
    fs.writeFile('/Users/me/.myapp/test.pdf', data, function (error) {
      if (err) {
          return console.log(err.message);
      }
      else { 
        console.log("shouldn't be here"); 
        console.log(data.length);
      }
    });
  });
Run Code Online (Sandbox Code Playgroud)

这会生成一个具有正确尺寸的新 pdf 文件,但它是空白的。

win是一个新打开的 browserwindow 对象,可以看到里面的内容。我怀疑这是浏览器窗口内容尚不可用的问题,但将其放入就绪事件中似乎没有任何作用,甚至根本无法阻止它触发。

无论浏览器窗口的内容如何,​​数据的长度(和 pdf 文件大小)始终为 661 字节。可能是最小的pdf模板大小之类的。

我使用 wkhtmltopdf 的后备策略是不可行的(某些 css3 功能不可用),所以我必须使这项工作。

Joh*_*n O 5

我不明白点击“发布您的问题”30 秒后的心理,我总是自己弄清楚,我很想删除它.​​.....但似乎没有其他版本的SO ,就这样吧。

x.printToPDF() 需要包装在 webContents 对象的事件处理程序中,如下所示:

win.webContents.on('did-finish-load', function() {
Run Code Online (Sandbox Code Playgroud)

did-finish-load是此问题的正确事件。此外,复制粘贴事件名称以避免拼写错误也不可耻。