(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

相关推荐
胡志辉的博客12 分钟前
深入浅出理解浏览器事件循环:从一道输出题讲到 Chrome 源码
前端·javascript·chrome·chromium·event loop
代码不加糖20 分钟前
js中不会冒泡的事件有哪些?
前端·javascript·vue.js
懂懂tty36 分钟前
Vue2与Vue3之间API差异
前端·javascript·vue.js
AI焦点1 小时前
跨越协议鸿沟:Tool Use状态机从Anthropic到OpenAI兼容体系的适配要点
前端·人工智能
Dxy12393102161 小时前
Python线程锁:为什么多线程会“打架“,以及怎么解决
开发语言·前端·python
老毛肚1 小时前
软件测试期末考试
vue.js
海兰1 小时前
【web应用】Excel 项目数据自动化分析系统(AI 驱动分析)详细设计与部署指南(附源代码)
前端·人工智能·自动化·excel
2501_940041741 小时前
技术分享:高质量全栈开发提示词设计实践 —— 覆盖简单到复杂
前端·prompt
IT_陈寒2 小时前
Python的os.path.join居然能这么坑?
前端·人工智能·后端
艳阳天_.2 小时前
星瀚弹框页面实现
java·前端·python