纯前端html导出pdf(jsPDF.js)-分页-不分页

欢迎点击: 个人官网博客

基础效果图:
demo源码
在这里插入图片描述

使用html2canvas自动分页效果图:
demo源码
在这里插入图片描述

一、基础:

1.先引入几个文件

<script src="http://www.jq22.com/jquery/1.8.3/jquery.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/html2canvas/0.5.0-beta4/html2canvas.min.js"></script>
    <script type="text/javascript" src="https://cdn.bootcdn.net/ajax/libs/jspdf/1.5.2/jspdf.min.js"></script>

2.平常我们都是后端传链接打开新窗口预览pdf,那么在纯前端html中可以使用iframe标签预览pdf,jspdf或者配合html2canvas创建pdf

<iframe id="pdf" width="500" height="400" seamless scrolling="yes" src="" frameborder="0"></iframe>

//看不懂这一句,请往下看
 const doc = new jsPDF('p', 'pt', 'a4')//a4纸大小
$('#pdf').attr('src', doc.output('datauristring')) //预览放在iframe标签
 

直接下载pdf:doc.save(“a4.pdf”);
导出pdf文件数据:doc.output(‘datauristring’)
添加一页: doc.addPage();

3.文字,图片,多边形,的运用

<script>
        const doc = new jsPDF('p', 'pt', 'a4')//a4纸大小


        //文字
        // // 打印所有可用的字体
        // console.log(doc.getFontList());
        // // 设置字体(内置的几种字体都是不支持中文,中文字体需要自己添加)
        // doc.setFont(doc.getFontList()[3]);
        doc.setFontSize(10)

        doc.text(20, 20, 'This is the default font.');

        doc.setFont("courier");
        doc.setFontType("normal");
        doc.text(20, 30, 'This is courier normal.');

        doc.setFont("times");
        doc.setFontType("italic");
        doc.text(20, 40, 'This is times italic.');

        doc.setFont("helvetica");
        doc.setFontType("bold");
        doc.text(20, 50, 'This is helvetica bold.');

        doc.setTextColor(255, 0, 0);
        doc.setFont("courier");
        doc.setFontType("bolditalic");
        doc.text(20, 60, 'This is courier bbolditalic');



        //多边形
        doc.setLineWidth(1);
        doc.setDrawColor(255, 0, 0);
        doc.setFillColor(0, 0, 255);
        doc.triangle(100, 100, 110, 100, 120, 130, 'FD'); //分别三点x,y坐标



        //图片
        var myImage = new Image();
        myImage.src = './s1.png';
        myImage.onload = function () {
    
    
            //x,y,w,h
            doc.addImage(myImage, 'png', 50, 100, myImage.width, myImage.height);
            console.log(doc.output('datauristring')) //所生成的pdf文件
            doc.addPage(); //如果后面还有内容,添加一个空页
            doc.addImage(myImage, 'png', 50, 100, myImage.width, myImage.height); //相对于新添加一个空页
            $('#pdf').attr('src', doc.output('datauristring')) //预览放在iframe标签
              // doc.save("a4.pdf");//保存为pdf
        };




      
    </script>

使用htmlcanvas

如果不了解htmlcanvas,点击这里

function create() {
    
    
            var dom = $('.poster-container')//为需要生成pdf最外层的div盒子
            html2canvas(dom[0], {
    
    
                useCORS: true, //跨域
                allowTaint: false,
                logging: false,
                letterRendering: true,
                taintTest: true, //在渲染前测试图片
                dpi: window.devicePixelRatio, // window.devicePixelRatio是设备像素比
                background: "#fff"
            }).then(function (canvas) {
    
    
                var imgUrl = canvas.toDataURL('image/png');
                doc.addImage(imgUrl, 'png', 0, 100, $('.poster-container').width(), $('.poster-container')
                    .height());
                $('#pdf').attr('src', doc.output('datauristring')) //预览放在iframe标签
            }

二、自动分页pdf

巧妙的运用了html2canvas的截图效果,然后把图片转化为pdf文件

 html2canvas(document.querySelector('#boardPdf'), {
    
    
                scale: 2,
                dpi: window.devicePixelRatio * 2,
                useCORS: true, // 如果截图的内容里有图片,可能会有跨域的情况,加上这个参数,解决文件跨域问题
                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
                    // a4纸的尺寸[595.28,841.89],html页面生成的canvas在pdf中图片的宽高
                    var imgWidth = 595.28
                    var imgHeight = 592.28 / contentWidth * contentHeight
                    var pageData = canvas.toDataURL('image/jpeg', 1.0)
                    // eslint-disable-next-line
                    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('demo.pdf')
                    $('#pdf').attr('src', pdf.output('datauristring'))
                },
                background: '#fff'//背景色
            })

猜你喜欢

转载自blog.csdn.net/qq_41560520/article/details/114932119