(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

相关推荐
duanshu_5 分钟前
官网表单与下载异常怎么排查?五个环节定位故障
前端·自动化·flyweight
Zhou14113625 分钟前
SpringBoot_03_Web开发
前端·spring boot·python
辻弋20126 分钟前
【无标题】
大数据·服务器·前端·搜索引擎·开源软件
FluxArt1 小时前
GPT Image 2.5 中文提示词教程:Flux Art 可复用模板
前端·gpt·算法
搬砖的小码农_Sky2 小时前
AI Agent:Windows上Node.js安装后 npm -v报错
前端·npm·node.js·人机交互
FYKJ_20102 小时前
SSM校园失物招领系统41452-计算机课程设计、毕业设计
java·vue.js·spring boot·python·mysql·typescript·spark
计算机魔术师2 小时前
半年翻倍!OpenAI再融300亿,估值冲到1.4万亿
前端
研☆香3 小时前
jQuery + Swiper.js 实现动态渲染轮播图
前端·javascript·jquery
子兮曰3 小时前
Node.js 50个优势场景盘点:一个人单干,为啥我多数时候只用它
前端·后端
IT_陈寒3 小时前
我花3小时debug,就因为JavaScript这个隐式转换坑
前端·人工智能·后端