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

1、将dom转换为图片

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

1.1、下载插件并导入

bash 复制代码
npm install --save html2canvas

import html2canvas from 'html2canvas';

1.2、编写代码

html 复制代码
<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、下载插件并导入

js 复制代码
// 下载
npm install jspdf --save
npm install --save html2canvas

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

2.2、js代码

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篇文章
  • 注意:如果有背景图的话,生成出来的图片可能会有问题。
相关推荐
酷爱码28 分钟前
如何通过python连接hive,并对里面的表进行增删改查操作
开发语言·hive·python
画个大饼30 分钟前
Go语言实战:快速搭建完整的用户认证系统
开发语言·后端·golang
喵先生!2 小时前
C++中的vector和list的区别与适用场景
开发语言·c++
Thomas_YXQ2 小时前
Unity3D Lua集成技术指南
java·开发语言·驱动开发·junit·全文检索·lua·unity3d
xMathematics3 小时前
计算机图形学实践:结合Qt和OpenGL实现绘制彩色三角形
开发语言·c++·qt·计算机图形学·cmake·opengl
Freedom风间4 小时前
前端优秀编码技巧
前端·javascript·代码规范
萌萌哒草头将军4 小时前
🚀🚀🚀 Openapi:全栈开发神器,0代码写后端!
前端·javascript·next.js
萌萌哒草头将军4 小时前
🚀🚀🚀 Prisma 爱之初体验:一款非常棒的 ORM 工具库
前端·javascript·orm
拉不动的猪4 小时前
SDK与API简单对比
前端·javascript·面试
yuanManGan5 小时前
C++入门小馆: 深入了解STLlist
开发语言·c++