当前位置: 移动技术网 > IT编程>网页制作>Html5 > 详解使用canvas保存网页为pdf文件支持跨域

详解使用canvas保存网页为pdf文件支持跨域

2019年07月25日  | 移动技术网IT编程  | 我要评论

前言

之前上一篇随笔说了canvas截图网页为图片,下来个新需求,把网页截图后保存为pdf文件供用户下载。

使用canvas保存网页为pdf文件支持跨域

正文

需求:用户点击下载,将页面保存为pdf文件并下载。

思路:继续使用canvas截图后将画布内容转换为pdf文件。

首先我们需要引入js文件jspdf.debug.js 下载路径 https://github.com/mrrio/jspdf

引入canvas的js文件,js文件获取地址官网主页:

<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。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网