(vue)Vue项目中使用jsPDF和html2canvas生成PDF

(vue)Vue项目中使用jsPDF和html2canvas生成PDF


效果:


安装与使用

1.:安装jsPDF和html2canvas

c 复制代码
npm install jspdf html2canvas

2.在需要生成PDF文档的组件中引入jsPDF和html2canvas

c 复制代码
<template>
	<div>
		<el-button  type="primary" @click="exportPDF">导出画像</el-button> 
		<div id="pdf-container">
			//需要导出pdf的内容
		</div>
	</div>
</template>

<script>
import html2Canvas from "html2canvas";
import JsPDF from "jspdf";
data() {
    return {}
}
methods: {
    // 单页pdf:css高度自适应即可(此处用的一个css,为了实现多页pdf同时不让分页分割图片,css中写死了每页的高度.a4page)
    exportPDF() {
      var title = "单页报告";
      var dom = document.getElementById("pdf-container"); // 生成pdf的html内容
      html2Canvas(dom, {
        allowTaint: true,
        scrollY: 0,
        scrollX: 0,
        useCORS: true, // 开启跨院
        // width: 1000, // 宽度
        height: dom.offsetHeight,
      }).then(function (canvas) {
        var contentWidth = canvas.width;
        var contentHeight = canvas.height;
        var pdfWidth = ((contentWidth + 10) / 2) * 0.75;
        var pdfHeight = ((contentHeight + 200) / 2) * 0.75; // 500为底部留白
        var imgWidth = pdfWidth;
        var imgHeight = (contentHeight / 2) * 0.75; //内容图片这里不需要留白的距离
        var pageData = canvas.toDataURL("image/jpeg", 1.0);
        var pdf = new JsPDF("", "pt", [pdfWidth, pdfHeight]);
        pdf.addImage(pageData, "jpeg", 0, 0, imgWidth, imgHeight);
        pdf.save(title + ".pdf");
      });
    },
}
</script>

解决参考:

1.https://www.jianshu.com/p/31d37bef539b

2.https://www.php.cn/faq/556634.html

3.https://blog.csdn.net/m0_54967474/article/details/123820384

相关推荐
岁月宁静30 分钟前
MasterGo AI 实战教程:10分钟生成网页设计图(附案例演示)
前端·aigc·视觉设计
狗头大军之江苏分军1 小时前
快手12·22事故原因的合理猜测
前端·后端
我命由我123451 小时前
CSS 锚点定位 - 锚点定位引入(anchor-name、position-anchor)
开发语言·前端·javascript·css·学习·html·学习方法
哟哟耶耶1 小时前
js-清除首尾空白字符再进行空白匹配str.trim().match(...)
开发语言·前端·javascript
计算机毕设VX:Fegn08951 小时前
计算机毕业设计|基于springboot + vue医院挂号管理系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·课程设计
浮游本尊2 小时前
React 18.x 学习计划 - 第十天:React综合实践与项目构建
前端·学习·react.js
阿蔹2 小时前
UI测试自动化--Web--Python_Selenium-元素定位
前端·ui·自动化
万少2 小时前
【鸿蒙心迹】-03-自然壁纸实战教程-项目结构介绍
前端
万少2 小时前
【鸿蒙心迹】- 02-自然壁纸实战教程-AGC 新建项目
前端
南望无一2 小时前
Vite拆包后Chunk级别的循环依赖分析及解决方案
前端·vite