(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

相关推荐
Chengbei1135 分钟前
云安全漏洞挖掘SKILL、一站式云漏洞挖掘工具,支持S3爆破、IMDS探测、K8s检测与AK/SK权限利用
前端·人工智能·网络安全·云原生·容器·kubernetes·系统安全
海带紫菜菠萝汤1 小时前
企业批量PDF翻译方案:从选型到部署的完整指南
人工智能·算法·pdf
不简说1 小时前
JS 代码技巧 vol.9 — 20 个设计模式在真实项目里的应用
前端·javascript·github
CoderLiu1 小时前
Agent 工程的下一层:为什么「把流程写成图」还不够,还需要 Graph Engineering
前端·人工智能·后端
勇往直前plus1 小时前
Vue3(篇三) Element Plus
前端·javascript·typescript·vue
AI_paid_community1 小时前
机械研发人员如何使用 Claude?
java·vue.js
爱勇宝1 小时前
《道德经》第 8 章:真正高级的能力,像水一样成事
前端·后端·程序员
Revolution611 小时前
数组本身没有 map,为什么还能直接调用:原型链怎样查找属性
前端·javascript·面试
bonechips1 小时前
RAG实战(一):EPUB 加载、文本切割与向量入库
前端·数据库
swipe1 小时前
10|(前端转全栈)库存扣减为什么最容易出事故?SKU、并发与原子更新
前端·后端·全栈