vue3 实现将页面生成 pdf 导出(html2Canvas + jspdf)

效果图:

需求:(报表页面等)导出为pdf

1、安装依赖

javascript 复制代码
npm i html2canvas
npm i jspdf

2、在utils文件夹下新建html2pdf.ts文件

TypeScript 复制代码
import html2canvas from 'html2canvas';
import jsPDF from 'jspdf'
 
export const htmlToPDF = async (htmlId: string, title: string = "标题", bgColor = "#fff") => {
  let pdfDom: HTMLElement | null = document.getElementById(htmlId) as HTMLElement
  pdfDom.style.padding = '0 10px !important'
  const A4Width = 595.28;
  const A4Height = 841.89;
  let canvas = await html2canvas(pdfDom, {
    scale: 2,
    useCORS: true,
    backgroundColor: bgColor,
  });
  let pageHeight = (canvas.width / A4Width) * A4Height;
  let leftHeight = canvas.height;
  let position = 0;
  let imgWidth = A4Width;
  let imgHeight = (A4Width / canvas.width) * canvas.height;
  /*
     根据自身业务需求  是否在此处键入下方水印代码
    */
  let pageData = canvas.toDataURL("image/jpeg", 1.0);
  let PDF = new jsPDF("p", 'pt', 'a4');
  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 -= A4Height;
      if (leftHeight > 0) PDF.addPage();
    }
  }
  PDF.save(title + ".pdf");
}

如果你想给pdf加上水印,则添加下面这段代码:

TypeScript 复制代码
const ctx: any = canvas.getContext('2d');
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.rotate((20 * Math.PI) / 180);
ctx.font = '20px Microsoft Yahei';
ctx.fillStyle = 'rgba(184, 184, 184, 0.8)';
for (let i = canvas.width * -1; i < canvas.width; i += 240) {
  for (let j = canvas.height * -1; j < canvas.height; j += 200) {
    // 填充文字,x 间距, y 间距
    ctx.fillText('水印名', i, j);
  }
}

3、在目标页面引入方法即可

html 复制代码
<template>
  <div id="test-id">
    <TestPinia></TestPinia>
  </div>
  <button @click="() => htmlToPDF('test-id', 'test pdf')">导出</button>
</template>

<script lang="ts">
import { defineComponent } from "vue";

import TestPinia from "@/views/BarChart03/index.vue";
import { htmlToPDF } from "@/utils/pdf/html2pdf";

export default defineComponent({
  name: "App",
  components: {
    TestPinia,
  },
  setup() {
    return {
      htmlToPDF,
    };
  },
});
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>
相关推荐
东风西巷2 小时前
K-Lite Mega/FULL Codec Pack(视频解码器)
前端·电脑·音视频·软件需求
超级大只老咪3 小时前
何为“类”?(Java基础语法)
java·开发语言·前端
你的人类朋友5 小时前
快速搭建redis环境并使用redis客户端进行连接测试
前端·redis·后端
深蓝电商API6 小时前
实战破解前端渲染:当 Requests 无法获取数据时(Selenium/Playwright 入门)
前端·python·selenium·playwright
bestcxx6 小时前
(二十七)、k8s 部署前端项目
前端·容器·kubernetes
鲸落落丶7 小时前
webpack学习
前端·学习·webpack
excel7 小时前
深入理解 3D 火焰着色器:从 Shadertoy 到 Three.js 的完整实现解析
前端
光影少年8 小时前
vue打包优化方案都有哪些?
前端·javascript·vue.js
硅谷工具人8 小时前
vue3边学边做系列(3)-路由缓存接口封装
前端·缓存·前端框架·vue