js 生成pdf

  • 最简洁的代码
<script src="js/html2canvas.min.js" type="text/javascript" charset="utf-8"></script>
<script src="js/jspdf.debug.js" type="text/javascript" charset="utf-8"></script>
document.getElementById("savePdf").onclick = function() {
    html2canvas(document.getElementById("tabContainer"), {
        onrendered: function(canvas) {
            //通过html2canvas将html渲染成canvas,然后获取图片数据
            var pageData = canvas.toDataURL('image/jpeg', 1.0);
            var pdfWidth = 210;
            const pdf = new jspdf('p', 'mm', 'a4');
            pdf.addImage(pageData, 'JPEG', 25, 25, pdfWidth - 50, ((pdfWidth - 50) / canvas.width) * canvas.height);
            // 保存
            pdf.save(`fileName.pdf`);
        }
    });
}

posted @ 2022-01-28 11:27  奔跑的前端猿  阅读(1463)  评论(0编辑  收藏  举报