1.
1.安装
//先把页面转为图片
npm install --save html2canvas
//然后图片转pdf
npm install jspdf --save
创建pdf.js
import html2canvas from "html2canvas";
import jsPDF from "jspdf";
export const downloadPDF = page => {
html2canvas(page).then(function (canvas) {
canvas2PDF(canvas);
});
};
const canvas2PDF = canvas => {
let contentWidth = canvas.width;
let contentHeight = canvas.height;
//a4纸的尺寸[595.28,841.89],html页面生成的canvas在pdf中图片的宽高
let imgWidth = 595.28;
let imgHeight = 592.28 / contentWidth * contentHeight;
//let imgHeight = 700/contentWidth * contentHeight;
//一页pdf显示html页面生成的canvas高度;
var pageHeight = contentWidth / 592.28 * 841.89;
let totalHeight = contentHeight;
// 第一个参数: l:横向 p:纵向
// 第二个参数:测量单位("pt","mm", "cm", "m", "in" or "px")
let pdf = new jsPDF("p", "pt");
let position = 0;
// pdf.addImage(
// canvas.toDataURL("image/jpeg", 1.0),
// "JPEG",
// 0,
// 0,
// imgWidth,
// imgHeight
// );
if (totalHeight < pageHeight) {
pdf.addImage( canvas.toDataURL("image/jpeg", 1.0), 'JPEG', 0, 0, imgWidth, imgHeight);
} else {
while (totalHeight > 0) {
pdf.addImage( canvas.toDataURL("image/jpeg", 1.0), 'JPEG', 0, position, imgWidth, imgHeight)
totalHeight -= pageHeight;
position -= 841.89;
//避免添加空白页
if (totalHeight > 0) {
pdf.addPage();
}
}
}
// pdf.addImage(
// canvas.toDataURL("image/jpeg", 1.0),
// "JPEG",
// 0,
// position,
// imgWidth,
// imgHeight
// );
pdf.save("导出.pdf");
};
然后再要导出的页面使用
先引入
import { downloadPDF } from "@/utils/pdf.js";
然后写个按钮时间调用handleExport方法
<el-button @click="handleExport">导出</el-button>
<div class="index-home" ref="pdf"></div>
handleExport() {
downloadPDF(this.$refs.pdf);
},
pdf就是要打印的元素中 ref的定义
然后浏览器会让下载个文件就完成了
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek “源神”启动!「GitHub 热点速览」
· 微软正式发布.NET 10 Preview 1:开启下一代开发框架新篇章
· 我与微信审核的“相爱相杀”看个人小程序副业
· C# 集成 DeepSeek 模型实现 AI 私有化(本地部署与 API 调用教程)
· DeepSeek R1 简明指南:架构、训练、本地部署及硬件要求