JS-Dom转为图片,并放入pdf中进行下载

1、将dom转换为图片

  • 这里我们使用html2canvas工具插件
  • 先将dom转为canvas元素
  • 然后canvas拥有一个方法可以将绘制出来的图形转为url
  • 然后下载即可
  • 注意:如果元素使用了渐变背景并透明的话,生成的图片可能会有点问题。我下面这个案例使用了渐变背景实现元素对角线,就有问题。

1.1、下载插件并导入

npm install --save html2canvas

import html2canvas from 'html2canvas';

1.2、编写代码

<template>
  <div class="home">
    <div class="content">
      
    </div>

    <button @click="creatUrl">下载图片</button>
  </div>
</template>

<script>
import html2canvas from 'html2canvas';

export default {
  name: 'HomeView',
  components: {
  },
  methods: {
    // 生成图片
    creatUrl() {
      const setup = {
        useCORS: true, // 使用跨域
      };
      const dom = document.querySelector(".content")
      html2canvas(dom, setup).then((canvas) => {
        // 将canvas 转换成图片地址
        const link = canvas.toDataURL("image/jpg");
        this.downloadPicture(link, "test.jpg");
      });
    },
  
    // 导出图片
    downloadPicture(link, name = "未命名文件") {
      const file = document.createElement("a");
      file.style.display = "none";
      file.href = link;
      file.download = decodeURI(name);
      document.body.appendChild(file);
      file.click();
      document.body.removeChild(file);
    }
  }
}
</script>

<style lang="scss" scoped>
.home {
  .content {
    width: 100px;
    height: 100px;
    border: 1px solid #000;
    /* 元素添加对角线 */
    background: linear-gradient(
      to bottom left,
      white 50%,
      #000,
      white 51%
    );
  }
}
</style>

1.3、效果

在这里插入图片描述

2、将dom转为图片并放到pdf文件里进行下载

  • 这里使用jspdf插件,创建一个pdf文件,并把上面生成的图片放入pdf中即可完成。
  • 上面将dom元素转为图片并生成url就不再讲解

2.1、下载插件并导入

// 下载
npm install jspdf --save
npm install --save html2canvas

// 导入
import jsPDF from 'jspdf'
import html2canvas from 'html2canvas';

2.2、js代码

// 生成pdf
creatPdf() {
    const setup = {
        useCORS: true, // 使用跨域
    };
    const dom = document.querySelector(".content")
    html2canvas(dom, setup).then((canvas) => {
        // 将canvas 转换成图片地址
        const link = canvas.toDataURL("image/jpg");
        // 创建pdf文件
        const pdf = new jsPDF();
        /*
        * 1. 图片地址
        * 2. 格式化图片格式
        * 3. 图片在pdf中的x坐标
        * 4. 图片在pdf中的y坐标
        * 5. 图片在pdf中的宽度
        * 6. 图片在pdf中的高度
        */
        pdf.addImage(link, 'JPEG', 0, 0, 210, 297); 
        // 参数为下载的pdf的文件名
        pdf.save("test.pdf");
    });
},

2.3、注意

  • 我这里斜线是用背景渐变实现的,有兴趣可以查看第三章CSS的第18篇文章
  • 注意:如果有背景图的话,生成出来的图片可能会有问题。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值