• html2canvas+jspdf导出html代码为pdf文件


    由于项目需求需要导出页面内容为pdf文件,最开始的思路是调用后端接口,但是由于接口跨域问题导致调用失败经过多方面沟通后决定前端完成导出。
    思路:使用html2canvas先将指定代码片段转为canvas图片,然后再将canvas使用jspdf转为pdf文件下载(上代码)。

    1.引入html2canvas和jspdf的包
    2.新建pdf.js用于定义html2canvas 和 jspdf的配置

    import html2Canvas from 'html2canvas';
    import JsPDF from 'jspdf';
    export default {
        install(Vue) {
            Vue.prototype.getPdf = function(dom, title) {
                let that = this;
                let width = document.querySelector(dom).clientWidth; //获取dom 宽度
                let height = document.querySelector(dom).clientHeight; //获取dom 高度
                document.querySelector(dom).style.color = '#000';//默认导出时页面的字体更改为黑色,防止页面字体为白色时导出的pdf看不到字体
                console.log(document.querySelector(dom));
                console.log(width);
                console.log(height);
                let canvas = document.createElement('canvas'); //创建一个canvas节点
                let scale = 1; //定义任意放大倍数 支持小数
                canvas.width = width * scale; //定义canvas 宽度 * 缩放
                canvas.height = height * scale; //定义canvas高度 *缩放
                canvas.getContext('2d').scale(scale,scale); //获取context,设置scale
                let opts = {
                    tainttest: true, //检测每张图片都已经加载完成
                    scale, // 添加的scale 参数
                    useCORS: true,
                    canvas, //自定义 canvas
                    logging: true, //日志开关
                    width, //dom 原始宽度
                    height, //dom 原始高度
                };
    
                html2Canvas(document.querySelector(dom), {
                    allowTaint: true,
                    ...opts,
                }).then(function(canvas) {
                    console.log(canvas);
                    let contentWidth = canvas.width;
                    let contentHeight = canvas.height;
                    console.log(canvas.height);
                    let pageHeight = contentWidth / 592.28 * 841.89;
                    let leftHeight = contentHeight;
                    let position = 0;
                    let imgWidth = 595.28;
                    let imgHeight = 592.28 / contentWidth * contentHeight;
                    let pageData = canvas.toDataURL('image/jpeg');
                    let PDF = new JsPDF('', 'pt', 'a4');
                    // return
                    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(title + '.pdf');
                    that.isPrint = true;
                });
            };
        },
    };
    
    //vue文件使用
    <template>
      <div>
        <div class="export" @click="download()">导出</div>
      </div>
      div  id="pdfDoms"  ref="pdfDom"  v-html="rich"></div>
    </template>
    <script>
      import html2canvas from 'html2canvas';
      import JSPDF from 'jspdf';
      export default{
        data(){
          return{
            
          };
        },
        methods(){
           download() {
              this.getPdf('#pdfDoms','xxx');//第一个参数为导出的内容id,第二个参数为导出的文件名xxx.pdf
              setTimeout(() => { 
                 this.$refs.pdfDom.style.color = '#fff';//这里的字体颜色设置为页面的字体颜色,导出后将页面字体颜色更改为原来的字体颜色
              }, 500);
           },
          renderHtmlToImage(c) {
               html2canvas(c, {
                  allowTaint: true,
                  //scale: 4, // 提升导出文件的分辨率
               }).then(canvas => {
                // var doc = new jsPDF('l', 'pt', [canvas.width / 2, imgheight])
                   let pdf = new JSPDF();
                   //addImage后两个参数控制添加图片的尺寸,此处将页面高度按照a4纸宽高比列进行压缩
                   pdf.addImage(
                       canvas.toDataURL('image/jpeg', 4.0),
                       'JPEG',
                        0,
                        0,
                        595.28,
                        (592.28 / canvas.width) * canvas.height,
                    );
    
                    pdf.save('stone.pdf');
               });
            },
        },
      }
    </script>
    
    
  • 相关阅读:
    mysql基础(三)存储引擎和锁
    为给定字符串生成MD5指纹
    区块链基本原理,Part-2:工作量证明和权益证明
    区块链基本原理,Part-1:拜占庭容错
    区块链挖矿 2.0
    以太坊 2.0 中的验证者经济模型,Part-2
    以太坊 2.0 中的验证者经济模型,Part-1
    Java归并排序之递归
    Python爬虫入门教程 64-100 反爬教科书级别的网站-汽车之家,字体反爬之二
    Java棋盘覆盖问题
  • 原文地址:https://www.cnblogs.com/lishaoxiong/p/15840190.html
Copyright © 2020-2023  润新知