javascript - 使用 JavaScript 或 Jquery 库或插件从 HTML 页面生成 PDF
问题描述
我正在尝试将 html 页面转换为 PDF,其中包含使用 css 样式设计的图像和一些数据表。我已经尝试过 JSPDF 和 html2canvas 库,但图像不会以 PDF 格式显示,而且它们不允许我在长页面上创建 PDF,因为我的 html 是动态的,它可以增长到四页。我在网上搜索了很多论坛,但找不到任何可以解决我问题的东西。我正在实施的网站是 shopify 网站。因此,有关此参考的任何线索都可能有所帮助。任何形式的帮助将不胜感激。谢谢
解决方案
将您的 html 内容转换为图像,然后将其转换为 PDF :
https://html2canvas.hertzen.com/
https://parall.ax/products/jspdf
var doc = new jsPDF();
var specialElementHandlers = {
'': function (element, renderer) {
return true;
}
};
$('#btn-download').click(function () {
html2canvas($('#container').html).then(function (canvas) { DownloadPDF(canvas) });
});
function DownloadPDF(canvas) {
var imgData = canvas.toDataURL(
'image/png');
var doc = new jsPDF('p', 'mm');
doc.addImage(imgData, 'PNG', 10, 10, parseInt($(canvas).attr('width')) / 9, parseInt($(canvas).attr('height')) / 9);
doc.save('name.pdf');
}
#test
{
width: 500px;
height : 500px;
background-image: url("https://www.wikichat.fr/wp-content/uploads/sites/2/comment-soigner-une-plaie-dun-chat.jpg");
background-size: contain;
background-repeat: no-repeat;
}
#btn-download
{
cursor:pointer;
position:fixed;
}
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.4.1/jspdf.min.js"></script>
<script src="https://html2canvas.hertzen.com/dist/html2canvas.min.js"></script>
</head>
<body>
<div id="btn-download">Download</div>
<br/>
<div id="container">
<div id="test">
</div>
</div>
</body>
</html>
推荐阅读
- r - 如何在众多 CSV 中测试某些列名的存在
- javascript - Accessing any element in a useRef is throwing 'undefined'
- c# - 在 CustomEntry 中将视觉对象设置为材质
- oracle - 如何连接到 PDB 并在 oracle 中创建表空间用户备份?
- express - 我无法在 ejs 中显示数据库的输出值?
- c# - 无法使用 EnableRaisingEvents 打开图片
- sql - 在 SQL 中,在 XML 数据类型字段中,如何像简单的 sql 记录一样查询数据?
- java - 适合 java htmlunit 的简单表单
- regex - 无法使用 grep-command 和正则表达式提取 jdk-version
- java - 如何将 GOOGLE_APPLICATION_CREDENTIALS 指向我的 JSON 文件?