浅念`

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

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>

posted on   浅念`  阅读(516)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」
点击右上角即可分享
微信分享提示