安装:
npm install jspdf html2canvas --legacy-peer-deps
导入:
import jsPDF from 'jspdf';
import html2canvas from 'html2canvas';
加入PDF函数:
const [loading, setLoading] = useState(false); // 新增loading状态,控制按钮状态(导出报告)
// 导出PDF的函数
const exportPDF = () => {
const input = document.getElementById('test-report') as HTMLElement;
if (!input) return; // 如果没有找到元素则直接返回
setLoading(true); // 开始导出时设置loading状态
html2canvas(input, { scale: 2 }).then((canvas) => {
const imgData = canvas.toDataURL('image/png');
const pdf = new jsPDF();
// 设置页面大小为A4
const imgWidth = 210; // A4 页面宽度(mm)
const imgHeight = (canvas.height * imgWidth) / canvas.width; // 根据比例调整高度
pdf.addImage(imgData, 'PNG', 0, 0, imgWidth, imgHeight);
// 保存PDF
pdf.save('测试报告.pdf');
setLoading(false); // 导出完毕,取消loading状态
}).catch(() => {
setLoading(false); // 捕获错误并取消loading状态
alert("导出失败,请稍后重试!");
});
};
最后在想要导出pdf的元素上 添加 id为test-report即可实现;
2848




被折叠的 条评论
为什么被折叠?



