1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > 使用html2canvas+jspdf导出iframe内容到pdf文件

使用html2canvas+jspdf导出iframe内容到pdf文件

时间:2022-06-05 06:54:01

相关推荐

使用html2canvas+jspdf导出iframe内容到pdf文件

使用html2canvas+jspdf导出iframe内容到pdf文件

工具如下:

html2canvas.js

html2canvas.min.js

jspdf.debug.js

代码如下:

<script>// 生成canvas并导出pdf文件function exportPdf() {var dom = document.getElementById('iframeId').contentWindow.document.documentElement;html2canvas(dom, {background: "#FFFFFF",// 如果指定的div没有设置背景色会默认成黑色,这里是个坑// useCORS: true,onrendered:function(canvas) {// 未生成pdf的html页面高度var leftHeight = canvas.height;var a4Width = 595.28-56.69var a4Height = 841.89-56.69// 一页pdf显示html页面生成的canvas高度;var a4HeightRef = Math.floor(canvas.width / a4Width * a4Height);// pdf页面偏移var position = 0;var pageData = canvas.toDataURL('image/jpeg', 1.0);var pdf = new jsPDF('x', 'pt', 'a4');var index = 1,canvas1 = document.createElement('canvas'),height;pdf.setDisplayMode('fullwidth', 'continuous', 'FullScreen');var pdfName='文件名称';var num = 0;function createImpl(canvas) {if (leftHeight > 0) {index++;var checkCount = 0;if (leftHeight > a4HeightRef) {var i = position + a4HeightRef;for (i = position + a4HeightRef; i >= position; i--) {var isWrite = truefor (var j = 0; j < canvas.width; j++) {var c = canvas.getContext('2d').getImageData(j, i, 1, 1).dataif (c[0] != 0xff || c[1] != 0xff || c[2] != 0xff) {isWrite = falsebreak}}if (isWrite) {checkCount++if (checkCount >= 10) {break}} else {checkCount = 0}}height = Math.round(i - position) || Math.min(leftHeight, a4HeightRef);if(height<=0){height = a4HeightRef;}} else {height = leftHeight;}canvas1.width = canvas.width;canvas1.height = height;// console.log(index, 'height:', height, 'pos', position);var ctx = canvas1.getContext('2d');ctx.drawImage(canvas, 0, position, canvas.width, height, 0, 0, canvas.width, height);var pageHeight = Math.round(a4Width / canvas.width * height);// pdf.setPageSize(null, pageHeight)if(position != 0){pdf.addPage();}pdf.addImage(canvas1.toDataURL('image/jpeg', 1.0), 'JPEG', 28.345, 28.345, a4Width, a4Width / canvas1.width * height);leftHeight -= height;position += height;if (leftHeight > 0) {setTimeout(createImpl, 500, canvas);} else {pdf.save(pdfName + '.pdf');}}}// 当内容未超过pdf一页显示的范围,无需分页if (leftHeight < a4HeightRef) {pdf.addImage(pageData, 'JPEG', 28.345, 28.345, a4Width, a4Width / canvas.width * leftHeight);pdf.save(pdfName + '.pdf');} else {try {pdf.deletePage(0);setTimeout(createImpl, 500, canvas);} catch (err) {console.log(err);}}}})}</script>

注意:生成canvas的dom元素应为iframe中的页面元素,即:

var dom = document.getElementById('iframeId').contentWindow.document.documentElement;

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。