之前上一篇随笔说了Canvas截图网页为图片,下来个新需求,把网页截图后保存为PDF文件供用户下载。
使用canvas保存网页为pdf文件支持跨域
正文需求:用户点击下载,将页面保存为PDF文件并下载。
思路:继续使用Canvas截图后将画布内容转换为pdf文件。
首先我们需要引入js文件jspdf.debug.js 下载路径https://github.com/MrRio/jsPDF
引入canvas的js文件,js文件获取地址官网主页:http://html2canvas.hertzen.com/
<script type=text/javascript src=js/html2canvas.js></script><script type=text/javascript src=js/html2canvas.min.js></script><script type=text/javascript src=js/jspdf.debug.js></script>
div按钮代码
<div id=down_pdf>导出为PDF按钮</div> <div class=sta-main>需要获取为PDF的div</div>
jsp代码
<script type=text/javascript>/* var downPdf = document.getElementById(down_pdf); */var downPdf = document.getElementById(down_pdf);$(#down_pdf).on(click, function() { var canvas2 = document.createElement(canvas); let _canvas = document.querySelector('.sta-main'); //获取宽高 var w = parseInt(window.getComputedStyle(_canvas).width); var h = parseInt(window.getComputedStyle(_canvas) .height); //将canvas画布放大2倍,然后盛放在小的容器内,处理模糊 canvas2.width = w * 2; canvas2.height = h * 2; canvas2.style.width = w + px; canvas2.style.height = h + px; var context = canvas2.getContext(2d); //处理偏移 context.scale(1.5, 1.5); //修改背景颜色,默认是黑色 $('.sta-main').css(background, #fff) html2canvas( _canvas, { //处理pdf跨域获取不到跨域信息问题 taintTest : false, useCORS : true, allowTaint : false, canvas : canvas2, dpi: 172,//导出pdf清晰度 onrendered: function (canvas) { var contentWidth = canvas.width; var contentHeight = canvas.height; //一页pdf显示html页面生成的canvas高度; var pageHeight = contentWidth / 592.28 * 841.89; //未生成pdf的html页面高度 var leftHeight = contentHeight; //pdf页面偏移 var position = 0; //html页面生成的canvas在pdf中图片的宽高(a4纸的尺寸[595.28,841.89]) var imgWidth = 595.28; var imgHeight = 592.28 / contentWidth * contentHeight; var pageData = canvas.toDataURL('image/jpeg', 1.0); var pdf = new jsPDF('', 'pt', 'a4'); //有两个高度需要区分,一个是html页面的实际高度,和生成pdf的页面高度(841.89) //当内容未超过pdf一页显示的范围,无需分页 if (leftHeight < pageHeight) { pdf.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight); } else { while (leftHeight > 0) { pdf.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight) leftHeight -= pageHeight; position -= 841.89; //避免添加空白页 if (leftHeight > 0) { pdf.addPage(); } } } pdf.save('PDF的名字.pdf'); } }) $('.sta-main').css(background, )})</script>
此次网页改为PDF,与上次截图网页为PNG,使用同一种技术,都是先使用Canvas截图画布后转格式。
同样也有偏移、模糊、跨域等问题,使用之前的代码来处理。
转换pdf会让背景色变为黑色使用css样式改一下背景色就可以了。
完美转换为pdf。
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持VeVb武林网。