将HTML字符串(包括样式)转换为PDF(电子-React-打字稿)

时间:2018-12-29 03:09:25

标签: javascript reactjs typescript pdf electron

_____项目概述_____

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

_____问题描述_____

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

_____我尝试过的_____

  • 我尝试使用html2canvasjspdf的组合。 jspdf可以很好地将HTML(不带样式)转换为pdf,但是 我需要样式。因此,我尝试使用 html2canvas首先,但失败,因为该页面从不 呈现。
  • 我尝试使用electron-pdf,但无法在我的应用程序中使用它。不过,它可以很好地用作命令行工具,因此可以选择调用命令行工具。我认为这应该可行,但是感觉很hacky(所以我宁愿不走那条路)。

_____代码_____

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...
};

1 个答案:

答案 0 :(得分:1)

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

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将其加载到“屏幕外”窗口。