通过html2canvas+jspdf将html页面生成PDF下载

通过html2canvas+jspdf将html页面生成PDF下载

月光魔力鸭

2019-03-03 08:53 阅读 2714 喜欢 0 html转pdf html转图片 canvas

这里讲一种实现起来比较简单的html转pdf下载的实现。

依赖插件

html2canvas jspdf

思路

通过html2canvas,我们可以将指定的一个dom元素,渲染到canvas中,然后从canva中获得该图片,并将图片通过jspdf来生成。

代码

function createPdf (selector,pagesize,direction,title){
    var key = pagesize +''+direction;
    var settings = {
        '00' : {
            pdf : {orientation : 'portrait',format : 'a4',unit : 'px'},
            width : 448,
            height : 632.5
        },
        '01' : {
            pdf : {orientation : 'landscape',format : 'a4',unit : 'px'},
            width : 632.5,
            height : 448
        },
        '10' : {
            pdf : {orientation : 'portrait',format : 'a3',unit : 'px'},
            width : 632.5,
            height : 894.2
        },
        '11' : {
            pdf : {orientation : 'landscape',format : 'a3',unit : 'px'},
            width : 894.2,
            height : 632.5
        }
    };
    var set = settings[key];
    var doc = new jsPDF(set.pdf);
    var arr = [];//根据顺序保存
    var $arr = $(selector);
    function tempCreate(){
        if($arr.length == 0){//没有啦
            //执行生成
            tempPdf();
        }else{
            var $dom = $arr.splice(0,1);
            html2canvas($dom[0]).then(canvas => {
                var dataurl = canvas.toDataURL('image/png');
                arr.push(dataurl);
                tempCreate();
            });
        }
    }
    function tempPdf(){
        arr.forEach((item,i)=>{
            if(i !== 0){
                doc.addPage();
            }
            doc.addImage(item,'png',-1,-1,set.width,set.height);//根据不同的宽高写入
        })
        //根据当前的作业名称
        doc.save(title+'.pdf');
    }
    tempCreate();
}

需要指定容器(依赖jquery),然后指定纸张A4或 A3,以及横纵向。

//调用
createPdf('.single-page',0,0,'test')

当然,如果是数据量很大的话,就不建议在前台生成了,最好还是放在后端去做。个人测试过,做A4的图片生成PDF,当数量大约在100左右的时候,浏览器就崩溃了,如果只是几页的数据的话,这个方式还是很方便的。

Ps:浏览器要是现代浏览器哈。

参考资料

html2canvas : http://html2canvas.hertzen.com/ jspdf :https://github.com/MrRio/jsPDF

转载请注明出处: https://chrunlee.cn/article/html-to-pdf-download.html


感谢支持!

赞赏支持
提交评论
评论信息 (请文明评论)
暂无评论,快来快来写想法...
推荐
web网站上总会有在文本域中提交代码的操作,那么如何处理呢?
如何通过js调用本地摄像头呢?获取后如何对视频进行截图呢?在这里跟大家做一个简易的Demo来实现以上几个功能。
先记录下,不定哪天就查了..防止找不到或不全
在页面中不同的frame之间进行相互调用的话,我们可以通过frame获取对应的window然后进行调用,但是如果是浏览器不同的tab之间呢?
项目中需要使用treegrid,找了下easyui 和 ext都有,但是项目用的框架是 byyui,如果为了treegrid 就把这些都加载的话,感觉不太合算。找了大家常用的基于jquery的treegrid.
nvm install 16.15.0 : The process cannot access the file because it is being used by another process
codewars上的一个题目,这里记录下解决方法。
在我们web开发过程中经常会碰到针对table的一些dom操作,这里整理一下关于这方面的知识点。当然我们可以通过jquery这样的插件来处理,或许会更简单一些,不过现在简单说下原生JS是如何操作的