zhzf/client/src/utils/ExportPdf.js

60 lines
2.0 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import html2canvas from 'html2canvas';
import jsPDF from 'jspdf';
import caseApi from "@/api/lawenforcement/Case.js";
import {ElMessage} from "element-plus";
/**
* 用Vue组件设计HTML模板
* 将HTML转换为Canvas
* 将Canvas插入PDF并下载
* @param pdfTemplate 导出区域div ref
* @param fileName 导出的pdf文件名
* @returns {Promise<void>}
*/
const exportPDF = async (pdfTemplate,fileName) => {
try {
const element = pdfTemplate.value;
const canvas = await html2canvas(element, { scale: 2, onclone: (clonedDoc) => {
clonedDoc.querySelectorAll('*').forEach(el => {
el.style.transform = 'translateZ(0)'; // 强制 GPU 渲染
});
} }); // 提高分辨率
const imgData = canvas.toDataURL('image/jpeg', 0.8);
const pdf = new jsPDF('p', 'mm', 'a4');
const pageWidth = pdf.internal.pageSize.getWidth();
const pageHeight = pdf.internal.pageSize.getHeight();
const imgRatio = canvas.width / canvas.height;
const imgHeight = pageWidth / imgRatio;
// 添加图片到PDF自动分页
let heightLeft = imgHeight;
let position = 0;
pdf.addImage(imgData, 'JPEG', 0, position, pageWidth, imgHeight);
heightLeft -= pageHeight;
while (heightLeft >= 0) {
position = heightLeft - imgHeight;
pdf.addPage();
pdf.addImage(imgData, 'JPEG', 0, position, pageWidth, imgHeight);
heightLeft -= pageHeight;
}
// 返回 Promise 包装的导出结果
return new Promise((resolve, reject) => {
try {
pdf.save(fileName);
// 假设浏览器在 500ms 内触发下载(根据实际情况调整时间)
setTimeout(() => {
resolve({ success: true, message: 'PDF导出成功' });
}, 500);
} catch (error) {
reject({ success: false, message: '导出失败:' + error.message });
}
});
} catch (error) {
return Promise.reject({ success: false, message: '生成PDF出错' + error.message });
}
}
export { exportPDF }