Reputation: 6505
_____ 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 _____
html2canvas
and jspdf
.
jspdf
works fine to convert the HTML, without styling, to pdf, but
I need the styling. So I tried getting a "screenshot" of my page with
html2canvas
first but that fails because the page is never
rendered.electron-pdf
, but I could not get this to work in my application. It works fine as a command line tool though, so an option would be to invoke the command line tool. I think that that should work, but it feels very hacky (so I'd prefer not going that route)._____ 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
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