react 生成pdf

* 如果是node搭建的底层,引入方式不一样  jspdf需要用script标签全局引用 不然会报window错误

*pdf如果想显示图片,必须为本地图片或者64转码之后的网络地址

// 引用

import jsPDF from 'jspdf';

import html2canvas from 'html2canvas';

// 创建函数

creatPdf = () => {

        html2canvas.(//把此dom节点下的内容生成pdf   this.pdfs,{

            dpi: window.devicePixelRatio,

            useCORS: true,

        }).then(canvas=>{

            let contentWidth = canvas.width;

            let contentHeight = canvas.height;

            let pageHeight = contentWidth / 592.28 * 841.89;

            let leftHeight = contentHeight;

            let position = 100;

            let imgWidth = 560.28;

            let imgHeight = 560.28/contentWidth * contentHeight;

            let pageData = canvas.toDataURL('image/jpeg', 1.0);

            let pdf = new jsPDF('', 'pt', 'a4');

            if (leftHeight < pageHeight) {

                pdf.addImage(pageData, 'JPEG', 26, 100, imgWidth, imgHeight );

            } else {

                while(leftHeight > 0) {

                    pdf.addImage(pageData, 'JPEG', 26, position, imgWidth, imgHeight);

                    // 如果pdf为两页且内容有重合需要更改下面的560.28数值

                    position -= 560;

                    if(leftHeight > 0) {

                        pdf.addPage();

                    }

                }

            }

            pdf.save("creat.pdf");

        })

    }

// dom 节点

this.pdfs=pdf}>

   

生成pdf

   

或者

   

你可能感兴趣的:(react 生成pdf)