[英]JavaScript generate PDF from HTML
我想从HTML生成PDF。 我尝试的库是print.js
, jsPDF
有了print.js
我有了HTML,并试图将其制作为PDF,但它成功了,但是PDF只是HTML,没有CSS。 但这不适合我。 样例
<table id="printJS-form">
<tr>
<th>Company</th>
<th>Contact</th>
<th>Country</th>
</tr>
<tr>
<td>Alfreds Futterkiste</td>
<td>Maria Anders</td>
<td>Germany</td>
</tr>
<tr>
<td>Centro comercial Moctezuma</td>
<td>Francisco Chang</td>
<td>Mexico</td>
</tr>
<tr>
<td>Ernst Handel</td>
<td>Roland Mendel</td>
<td>Austria</td>
</tr>
<tr>
<td>Island Trading</td>
<td>Helen Bennett</td>
<td>UK</td>
</tr>
<tr>
<td>Laughing Bacchus Winecellars</td>
<td>Yoshi Tannamuri</td>
<td>Canada</td>
</tr>
<tr>
<td>Magazzini Alimentari Riuniti</td>
<td>Giovanni Rovelli</td>
<td>Italy</td>
</tr>
</table>
<button type="button" onclick="printJS('printJS-form', 'html')">
Print Form
</button>
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
与成功最接近的事情是jsPDF
,我这次用所有CSS创建图像,然后从该图像PDF生成。 但是这里的问题是生成的PDF只是图像,我丢失了PDF中的所有元数据。 样例
<body>
<div id="printJS-form">
<h3 id='head-color'>Test heading</h3>
<button id='print-btn'>Start print process</button>
</div>
</body>
$('#print-btn').click(()=>{
var pdf = new jsPDF();
pdf.addHTML(document.body,function() {
pdf.save('web.pdf');
});
})
#head-color{
color: blue;
}
我尝试过并真的希望在这里做的另一件事,因为对我来说似乎更干净的选择是使用“ onbeforeprint”事件。 在要调用的window.print()
之前,激活了“ onbeforeprint”事件。 如果在“ onbeforeprint”中 ,已经生成了PDF,我想以某种方式访问它。 但是我无法弄清楚它是如何以及是否有可能。 样例
<html>
<body onbeforeprint="myFunction()">
<h1>Try to print this document</h1>
<p><b>Tip:</b> Keyboard shortcuts, such as Ctrl+P sets the page to print.</p>
<p><b>Note:</b> The onbeforeprint event is not supported in Safari and Opera.</p>
<button type="button" onclick="printWindow()">
Print Form
</button>
<script>
function myFunction() {
// get blob pdf
alert("You are about to print this document!");
}
function printWindow() {
window.print();
}
</script>
</body>
</html>
最后我问
有没有办法用print.js或jsPDF不仅获取html,而且获取CSS?
我可以从“ onbeforeprint”事件或任何其他javascript事件获取二进制PDF吗?
我认为您可以使用Puppeteer生成pdf。 我没有尝试过,但是这里有一些链接演示了这种方法:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.