[英]Rendering HTML to PDF with images included Django
I have a django app where users would print some pages which include images as a part of Data processing.我有一个 django 应用程序,用户可以在其中打印一些页面,其中包含图像作为数据处理的一部分。
I tried jsPDF but it didn't render my images and I ended up with just text我尝试了 jsPDF 但它没有呈现我的图像,我最终只有文本
$(document).ready(function() {
$("#pdfDownloader").click(function() {
var doc = new jsPDF('p', 'pt', 'a4', true);
doc.fromHTML($('#renderMe').get(0), 15, 15, {
'width': 500
}, function (dispose) {
doc.save('thisMotion.pdf');
});
});
})
This was my code and it didn't render the images so do I need to change anything?这是我的代码,它没有渲染图像,所以我需要改变什么吗?
is using a Django view would solve this and is there any alternatives to xhtml2pdf
as with this I need to include my CSS in the HTML file ?使用 Django 视图可以解决这个问题,是否有xhtml2pdf
替代方案,因为我需要将我的 CSS 包含在 HTML 文件中?
fromHTML is used to get text from the HTML to form a PDF. fromHTML用于从 HTML 中获取文本以形成 PDF。 Try using html2canvas js library instead.尝试改用 html2canvas js 库。
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.5.0-beta4/html2canvas.min.js"></script>
You can create a canvas image and add it to the PDF with code like this,您可以创建一个画布图像并使用这样的代码将其添加到 PDF 中,
$(document).ready(function() {
$("#pdfDownloader").click(function() {
html2canvas($("#renderMe")).then(canvas => {
const contentDataURL = canvas.toDataURL('image/png')
let pdf = new jspdf('p', 'pt', 'a4', true); // A4 size page of PDF
var positionX = 0;
var positionY = 0;
pdf.addImage(contentDataURL, 'PNG', positionY, positionY, undefined, undefined)
pdf.save('thisMotion.pdf'); // Generated PDF
});
});
})
This will get you a PDF just like the HTML rendered on screen.这将为您提供一个 PDF,就像在屏幕上呈现的 HTML 一样。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.