javascript - 将 HTML 字符串(包括样式)转换为 PDF(Electron - React - Typescript)

标签 javascript reactjs typescript pdf electron

_____ 项目概述 _____

我正在使用 React 和 Typescript 构建一个 Electron 应用程序,其中我将一个纯 HTML 字符串读取到内存中,然后调整其中的一些元素,最后将其转换为 pdf。

_____ 问题描述 _____

因为 html 从未真正渲染过(它只是在内存中),所以我不确定如何将 html(带样式)转换为 pdf,而不先渲染 html。

_____ 我尝试过的 _____

  • 我尝试结合使用 html2canvasjspdfjspdf 可以很好地将 HTML(不带样式)转换为 pdf,但是 我需要造型。所以我尝试获取我的页面的“屏幕截图” 首先是 html2canvas 但失败了,因为页面永远不会 渲染。
  • 我尝试使用 Electron pdf,但我无法让它在我的应用程序中工作。不过,它作为命令行工具工作得很好,因此一个选项是调用命令行工具。我认为这应该可行,但感觉很老套(所以我不想走那条路)。

_____ 代码 _____

const createPDF = async (invoiceData: IInvoiceFields) => {
  const invoiceTemplate = fs
    .readFileSync(
      resolve(
        remote.app.getAppPath(),
        "src",
        "invoice_templates",
        "invoice_EN.html"
      )
    )
    .toString();
  const invoiceHTMLString = fillInInvoice(invoiceTemplate, invoiceData);
  const domParser = new DOMParser();
  const invoiceHTMLDocument = domParser.parseFromString(
    invoiceHTMLString,
    "text/html"
  );
  // TODO: Create actual pdf...
};

最佳答案

根据Generating PDF with Electron.js ,似乎可以使用 webContents方法printToPDF在新的 BrowserWindow 中而不实际显示窗口:

window_to_PDF = new BrowserWindow({show : false});//to just open the browser in background

window_to_PDF.loadURL('anylink.html'); //give the file link you want to display

function pdfSettings() {
    var paperSizeArray = ["A4", "A5"];
    var option = {
        landscape: false,
        marginsType: 0,
        printBackground: false,
        printSelectionOnly: false,
        pageSize: paperSizeArray[settingCache.getPrintPaperSize()-1],
    };
  return option;
}

window_to_PDF.webContents.on("did-finish-load", function() {
  window_to_PDF.webContents.printToPDF(pdfSettings(), function(err, data) {
      if (err) {
          //do whatever you want
          return;
      }
      try{
          fs.writeFileSync('./generated_pdf.pdf', data);
      }catch(err){
          //unable to save pdf..
      }
  });
});

因此,就您的情况而言,您可能必须将生成的 HTML 写入临时文件 anylink.html,然后使用 loadURL或者最好loadFile将其加载到“离屏”窗口中。

关于javascript - 将 HTML 字符串(包括样式)转换为 PDF(Electron - React - Typescript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53966376/

相关文章:

javascript - Ember-data 观察困惑

javascript - 将 JSON 字符串从 jsp 传递到 js 文件

javascript - 如何通过两行的数量来限制我的标题?

JavaScript 或 JQuery 问题 Div 不切换

javascript - 通过 ReactJS 中的组件传递属性,ES6 示例

javascript - 如何在 React Router 中正确使用 IndexRoute?

typescript - TSLint 似乎不适用服装规则?

javascript - 如何将语义 ui 图标颜色更改为 ReactJs 中定义的颜色?

javascript - 如何使用 jest 测试 void 函数

javascript - 无法使用 Protractor 选择组件按钮