_____ 项目概述 _____
我正在使用 React 和 Typescript 构建一个 Electron 应用程序,其中我将一个纯 HTML 字符串读取到内存中,然后调整其中的一些元素,最后将其转换为 pdf。
_____ 问题描述 _____
因为 html 从未真正渲染过(它只是在内存中),所以我不确定如何将 html(带样式)转换为 pdf,而不先渲染 html。
_____ 我尝试过的 _____
- 我尝试结合使用
html2canvas
和jspdf
。jspdf
可以很好地将 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/