(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

相关推荐
默_笙5 分钟前
🔑 让 AI 学会"读"网页:我用 Cheerio 爬了一篇掘金文章,然后切成小块存进了向量库
前端·javascript
颜进强5 分钟前
Ollama 从入门到实践:本地模型运行、API 调用
前端·后端·ai编程
颜进强10 分钟前
Embedding 基础使用:用 Ollama 和 LangChain.js 生成文本向量
前端·后端·ai编程
颜进强14 分钟前
Vector Store 入门:什么是向量数据库,主流产品如何选择
前端·后端·ai编程
方方洛33 分钟前
AI 教程系列-TUI 应用开发教程14-技能系统与可扩展性
前端·javascript·typescript
方方洛38 分钟前
AI 教程系列-TUI 应用开发教程05-大模型对话界面设计
前端·javascript·typescript
方方洛1 小时前
AI 教程系列-TUI 应用开发教程08-流式响应与动画
前端·javascript·typescript
方方洛1 小时前
AI 教程系列-TUI 应用开发教程04-第一个 TUI 应用
前端·javascript·typescript
cooldream20091 小时前
AI 时代,前端工程师的“新学习路线“—— 从“学框架“到“用 AI“
前端·人工智能·学习
明日清晨1 小时前
printf(“%p\n“,&((struct A *)NULL)->m_float)的原理
linux·服务器·前端