-
安装插件
-
安装html2canvas npm i html2canvas 安装jspdf npm i jspdf
-
封装导出文件函数
/** * 生成pdf * @param name * @param title */ const htmlToPdf = async (name, title) => { // 开启loading效果 reportDialogRef.value.startLoading(); const ele = document.querySelector('#' + name); const childrenBox = ele.children; const pdf = new jsPDF('', 'pt', 'a4'); for (let i = 0; i < childrenBox.length; i++) { const res = await html2canvas(childrenBox[i], { dpi: 400, // 设置 DPI useCORS: true, allowTaint: true, scale: 4 // 设置缩放比例 }); const pageData = res.toDataURL('image/jpeg', 1.0); const contentWidth = res.width; const contentHeight = res.height; // A4 页面尺寸(pt) const a4Width = 595.28; const a4Height = 841.89; // 计算图像在 A4 页面中的宽高比 const imgAspectRatio = contentWidth / contentHeight; let imgWidth, imgHeight; // 根据 A4 尺寸和图像宽高比计算宽高 if (imgAspectRatio > a4Width / a4Height) { imgWidth = a4Width; imgHeight = a4Width / imgAspectRatio; } else { imgHeight = a4Height; imgWidth = a4Height * imgAspectRatio; } pdf.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight); if (i < childrenBox.length - 1) { pdf.addPage(); // 添加新页面 } } // 将 PDF 转换为 Blob // const pdfBlob = pdf.output('blob'); // const formData = new FormData(); // formData.append('sample_id', reportForm.value.sample_id); // formData.append('report_version', reportForm.value.report_version); // formData.append('pdf_file', pdfBlob, `${title}.pdf`); // 添加 Blob 和文件名 // formData.append('report_info', JSON.stringify(reportForm.value.reportInfo)); // // 提交表单数据 // fetchGeneratePdf(formData).then(res => { // Notification({ // message: res.msg // }); // reportDialogRef.value.endLoading(); // }).catch(err => { // console.error('生成 PDF 失败:', err); // reportDialogRef.value.endLoading(); // }).finally(()=>{ // requestTableData() // }) };
04-12
1万+
09-30
738