[英]Export pdf with jsPDF and html2canvas
我可以使用 jsPDF 打印 PDF 但不能使用 div 作為內容。 為此,我現在已經導入了 html2canvas,不幸的是,我無法從文檔中真正弄清楚如何使用它。 我在互聯網上找到了一些說明,但它們對我不起作用。 整件事都在 WordPress 中。 我收到各種錯誤消息,要么 undefiend 不是 function,要么它找不到東西,或者其他什么。
第一種方法:
function testPDF() {
console.log("testPDF-function works")
html2canvas(document.getElementById('a4')).then(function(canvas){
document.body.appendChild(canvas)
})
var img = canvas.toDataURL('img/png')
var doc = new jsPDF();
doc.addImage(img, 'JPEG', 20,20)
doc.save('test.pdf');
}
第二種方法: Github (這里有人合並了兩個庫,但這對我也不起作用。)
let page = document.getElementById("a4");
function testPDF() {
html2PDF(page, {
jsPDF: {
format: "a4",
},
imageType: "image/jpeg",
output: "offerte.pdf",
});
}
第三種方法
function testPDF() {
html2canvas(document.getElementById("a4")).then(function cancas(canvas) {
// document.body.appendChild(canvas);
var doc = new jsPDF();
doc.addImage(document.body.appendChild(canvas));
doc.save("offerte.pdf");
});
}
我的 html 看起來像這樣:
<div id='a4' style='height: 297mm; width: 210mm; border: 1px black solid; margin-left:20%;'>
<p>Content</p>
</div>
<button id='pdfExport' onclick='testPDF' >Export PDF</button>"
試試下面的代碼。
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.4.1/jspdf.debug.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.js"></script>
<style type="text/css">
#a4{width: 100%;background: #ffffff;color: #000000;}
</style>
<div id="a4" style="height: 297mm; width: 210mm; border: 1px black solid; margin-left:20%;">
Content
</div>
<button id="pdfExport" onclick="javascript:demoFromHTML();">Export PDF</button>
<script>
function demoFromHTML() {
html2canvas(document.getElementById('a4'), {
onrendered: function (canvasObj) {
var pdf = new jsPDF('P', 'pt', 'a4'),
pdfConf = {
pagesplit: false,
backgroundColor: '#FFF'
};
document.body.appendChild(canvasObj); //appendChild is required for html to add page in pdf
pdf.addHTML(canvasObj, 0, 0, pdfConf, function () {
document.body.removeChild(canvasObj);
//pdf.addPage();
pdf.save('Test.pdf');
});
}
});
}
</script>
上面的代碼小提琴。 jsfiddle
此外,請參閱以下 URL。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.