相信各位前端工程狮们在一些报表项目,管理系统项目中都会遇到在这样的需求:申请报、表格、简历等等图文信息有导出为PDF文件。下面是记录我在项目中完成该需求的代码dome,发布出来也是希望对大家有些帮助。

1,整体思路

将HTML元素打印或导出为PDF文件,无非就是提取元素页面内容,然后转化为图片,将图片保存为PDF文件。

2,准备工作

将HTML元素转化为图片:html2canvas.js  插件;

<script src="https://cdn.bootcss.com/html2canvas/0.5.0-beta4/html2canvas.js"></script>

导出为PDF文件:jspdf.js插件:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.0.272/jspdf.debug.js"></script>

 3,dome

HTML:

    <button id="btn">导出为PDF文件</button>
    <div id="pdfDom">
        <table>
            <th></th>
        </table>
        <ul id="box"></ul>
    </div>

JavaScript:

<script>
    let obox = document.getElementById("box")
    let opdfdom = $("#pdfDom")
    let obtn = document.getElementById("btn")
    let lihtml = ''
    for(let i = 0; i < 50; i++){
        lihtml += "<li>条目"+i+"</li>"
    }
    obox.innerHTML = lihtml

    obtn.onclick = function(){
        downLoadPdf(opdfdom)
    }

    function downLoadPdf(content){
        content = content ? content : null;
        // 条件判断是否打印
        if(!content){
            alert("打印失败,请重新操作")
            return false
        }
        // 开始打印
        console.log(content)
        var contentWidth = content.width();
        var contentHeight = content.height();
        var canvas = document.createElement("canvas")
        canvas.width = contentWidth
        canvas.height = contentHeight
        var context = canvas.getContext("2d");
        html2canvas(content,{
            allowTaint:true,
            scale:2  // 提升画面质量,但是会增加文件大小
        }).then(function(canvas){
            var pdfWidth = canvas.width;
            var pdfHeight = canvas.height;
            var pageHeight = pdfWidth / 592.28 * 841.89;
            var leftHeight = pdfHeight;
            var position = 0;
            var imgWidth = 595.28;
            var imgHeight = 595.28 / pdfWidth * pdfHeight;
            var pageData = canvas.toDataURL("img/jpeg",1.0);
            var pdf = new jsPDF('', 'pt', 'a4');
            // 判断打印dom高度是否需要分页,如果需要进行分页处理
            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")
        })

    }
</script>

4,结果

 完了,没有了。

我也是拾人牙慧,不过这个还是有记录下来的价值的,以后遇到直接Ctrl+C Ctrl+V,啧啧啧,它不香吗?

香啊~~~

拜了个拜!迪迦。。。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐