(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

相关推荐
一次旅行43 分钟前
多智能体编排实战:拆解Plan-and-Execute范式+三层记忆架构,手写无依赖轻量Agent调度引擎
前端·javascript·架构
小玮看世界2 小时前
[Python]从“脏”数据到优雅实现:一个IoT滑动窗口最大值问题的测试驱动优化实录
linux·前端·python
尤乐娃子2 小时前
进入大厂(厂子大)实习Day11
前端·笔记·实习
xiaoxiangsiyan3 小时前
运维之前端反调试学习
运维·前端·学习·状态模式
小徐_23333 小时前
TRAE WORK 实战,之前写一篇水文要半天,现在用 TRAE Work 摸鱼2分钟交差,真香!
前端·trae
明月_清风3 小时前
🤗 Hugging Face 模型上传完全指南:从本地到 Hub 的 4 种姿势
前端·后端·ai编程
sugar__salt3 小时前
跟着 Demo 学 Pinia:两种仓库写法 + 完整 TodoList 复现
前端·javascript·vue.js·前端框架·vue
To_OC3 小时前
从一个名字编辑组件开始,我把 React + TS 的数据流和副作用彻底搞明白了
前端·react.js·typescript
程序员黑豆4 小时前
Java入门第一步:从零开始编写你的第一个Hello World程序
java·前端·ai编程