Bram  Vanbilsen
Bram Vanbilsen

Reputation: 6505

Converting HTML string, including style, to PDF (Electron - React - Typescript)

_____ Project Overview _____

I am building an Electron application, using React and Typescript, in which I read a plain HTML string to memory to then adjust some elements in it and finally convert it to a pdf.

_____ Problem Description _____

Because the html is never really rendered (it is just in memory), I am uncertain on how to convert the html (with style) to a pdf without rendering the html first.

_____ What I've tried _____

_____ Code _____

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

Upvotes: 0

Views: 2102

Answers (1)

user8022331
user8022331

Reputation:

According to Generating PDF with Electron.js, it seems possible to use the webContents method printToPDF in a new BrowserWindow without actually showing the window:

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

So, in your case, you may have to write your generated HTML to a temporary file anylink.html then use loadURL or preferably loadFile to load it in the "off-screen" window.

Upvotes: 2

Related Questions