javascript - jsPDF 不适用于 Django - 将 HTML 页面渲染为 PDF
问题描述
我正在使用下面的这个函数来生成和下载这样一个页面的 pdf 版本。
<script>
function getPDF() {
var HTML_Width = $(".canvas_div_pdf").width();
var HTML_Height = $(".canvas_div_pdf").height();
var top_left_margin = 15;
var PDF_Width = HTML_Width + (top_left_margin * 2);
var PDF_Height = (PDF_Width * 1.5) + (top_left_margin * 2);
var canvas_image_width = HTML_Width;
var canvas_image_height = HTML_Height;
var totalPDFPages = Math.ceil(HTML_Height / PDF_Height) - 1;
html2canvas($(".canvas_div_pdf")[0], {
allowTaint: true
}).then(function(canvas) {
canvas.getContext('2d');
console.log(canvas.height + " " + canvas.width);
var imgData = canvas.toDataURL("image/jpeg", 1.0);
var pdf = new jsPDF('p', 'pt', [PDF_Width, PDF_Height]);
pdf.addImage(imgData, 'JPG', top_left_margin, top_left_margin, canvas_image_width, canvas_image_height);
for (var i = 1; i <= totalPDFPages; i++) {
pdf.addPage(PDF_Width, PDF_Height);
pdf.addImage(imgData, 'JPG', top_left_margin, -(PDF_Height * i) + (top_left_margin * 4), canvas_image_width, canvas_image_height);
}
pdf.save("HTML-Document.pdf");
});
};
</script>
这是该功能起作用的示例:
<button onclick="getPDF()" id="downloadbtn" style="display: inline-block;"><b>Click to Download HTML as PDF</b></button>
<div class="canvas_div_pdf" style="margin-left:100px;">
<p> Something to render.</p>
</div>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.3/jspdf.min.js"></script>
<script src="https://html2canvas.hertzen.com/dist/html2canvas.js"></script>
但是当我尝试使用 Django 变量时,如下所示,它不起作用,我单击按钮并没有任何反应:
<button onclick="getPDF()" id="downloadbtn" style="display: inline-block;"><b>Click to Download HTML as PDF</b></button>
<div class="canvas_div_pdf" style="margin-left:100px;">
<p> {{ Something from Django }}</p>
</div>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.3/jspdf.min.js"></script>
<script src="https://html2canvas.hertzen.com/dist/html2canvas.js"></script>
我试图以一种形式使用它,但没有任何改变。
解决方案
推荐阅读
- azure - 适用于 Sharepoint 和 Office365 的 Bot Framework Azure 连接提供程序
- sql - 如何在 SQL Server 中获取 0 值的缺失日期?
- python - Python 在特定时间启动一个进程并在特定时间结束它
- xml - 如何将 xml 文件从 hdfs 加载到 hbase 表
- git - 2FA + openssh 安全服务器上的 Gitlab
- php - Silverstripe 4 Fluent Locale Menu - 如何确定页面是否存在于实际语言环境中?
- javascript - ngx-bootstrap 轮播 - 如何修改指标,提高可访问性
- php - 如何在 Yii 2 ActiveRecord 中比较日期和时间?
- laravel - 无法使用 laravel 在刀片文件中显示数据库中的值
- ios - iOS:如何删除侧面的灰色条?