【JS】- 前端生成PDF(html2canvas + jspdf)
1、安装环境依赖
npm install --save html2canvas // 将页面html转换成图片 npm install jspdf --save // 将图片生成pdf
2、自定义PDF转换的函数
// 引入依赖 import Vue from "vue"; import html2canvas from "html2canvas"; import JsPDF from "jspdf"; const PDF = {}; // eslint-disable-next-line no-unused-vars PDF.install = function(Vue, options) { Vue.prototype.$pdf = function(dom, user) { html2canvas(dom).then(canvas => { var contentWidth = canvas.width; var contentHeight = canvas.height; // 一页pdf显示html页面生成的canvas高度; var pageHeight = (contentWidth / 595.28) * 841.89; // 未生成pdf的html页面高度 var htmlHeight = contentHeight; // pdf页面偏移 var position = 0; // a4纸的尺寸[595.28,841.89],html页面生成的canvas在pdf中图片的宽高 var imgWidth = 595.28; var imgHeight = (595.28 / contentWidth) * contentHeight; var pageData = canvas.toDataURL("image/jpeg", 1.0);var pdf = new JsPDF("", "pt", "a4"); // 有两个高度需要区分,一个是html页面的实际高度,和生成pdf的页面高度(841.89) // 当内容未超过pdf一页显示的范围,无需分页 if (htmlHeight < pageHeight) { pdf.addImage(pageData, "JPEG", 0, 0, imgWidth, imgHeight); } else { while (htmlHeight > 0) { pdf.addImage(pageData, "JPEG", 0, position, imgWidth, imgHeight); htmlHeight -= pageHeight; position -= 841.89; // 避免添加空白页 if (htmlHeight > 0) { pdf.addPage(); } } } pdf.save(user + ".pdf"); // doc.save(user); }); }; }; Vue.use(PDF); export default PDF;
3、在main文件中全局定义
import "./utils/pdf";
4、在html中使用
this.$pdf(document.querySelector("#pdfContainer"), "PDF名称")
转载于:https://blog.csdn.net/xiaoge_586/article/details/114001911