针对前端PDF导出中内容丢失、图表被切断、黑底及浏览器卡死等问题,通过临时展开DOM、智能避让分页、配置白底及异步防卡死等策略,封装成TypeScript工具类,保证导出内容完整、分页恰当、背景正常且不阻塞浏览器,实现高效稳定导出。
| 遇到的问题 | 解决思路 |
|---|---|
| 滚动区域内容丢失 | 截图前临时修改 DOM 样式(`overflow: visible`,`height: auto`),强制撑开高度,截图后恢复。 |
| 图表/文字被切断 | 引入“智能避让机制”。截图前收集需要保护的元素(如图表容器、段落)的绝对坐标。切片时,如果发现“切割线”落在这些元素的坐标区间内,则提前换页。 |
| PDF 底部黑块 | 黑块是 Canvas 裁剪后透明背景在转为 JPEG 时被默认填充为黑色导致的。解决办法是在 `html2canvas` 配置中指定白底,并在每次切片绘制前主动填充白色背景。 |
| 浏览器卡死无响应 | 核心原因是大量计算阻塞主线程。解决办法:1. 降低 `scale` 缩放比(从 2 降为 1.5);2. 利用 `setTimeout` 和 `async/await` 在截图前和切片循环中主动让渡主线程,给浏览器 UI 刷新的机会。 |
复制代码import html2Canvas from "html2canvas";
import jsPDF from "jspdf";interface PdfExportOptions {
// 需要避免被分页截断的元素选择器数组,如 ['.a void-break', 'p', 'tr']
noBreakSelectors: string[];
// 导出时需要排除(隐藏)的元素 ID 数组
excludeIds: string[];
// 渲染倍率,默认 1.5(降低倍率可大幅缓解无响应问题)
scale: number;
}// 工具函数:让出主线程,防止浏览器卡死
const delay = (ms: number = 0) => new Promise((resolve) => setTimeout(resolve, ms));const htmlToPdf = {
/**
* 异步导出 PDF
* @param title 文件名
* @param id 要截取的根元素选择器
* @param options 配置项
*/
async getPdf(title: string, id: string, options: PdfExportOptions): Promise<void> {
const {
noBreakSelectors = [".a void-break"],
excludeIds = [],
scale = 1.5
} = options || {};
const pdfContent = document.querySelector(id) as HTMLElement | null;
if (!pdfContent) {
throw new Error(`Element with selector "${id}" not found.`);
} // 1. 临时修改样式,确保滚动区域全部展开被捕获
const originalOverflow = pdfContent.style.overflow;
const originalHeight = pdfContent.style.height;
const containerRect = pdfContent.getBoundingClientRect(); pdfContent.style.overflow = "visible";
pdfContent.style.height = "auto"; // 【关键优化1】:让出主线程,让浏览器有机会渲染 Loading 动画,缓解"无响应"
await delay(50); try {
// 2. Canvas 渲染图像
const canvas = await html2Canvas(pdfContent, {
logging: false,
useCORS: true,
scale: scale, // 降低 scale 减少计算压力
backgroundColor: "#ffffff", // 防止透明变黑
height: pdfContent.scrollHeight,
windowHeight: pdfContent.scrollHeight,
ignoreElements: (element) => {
// 过滤掉需要排除的元素
return excludeIds.includes(element.id);
},
}); // 恢复原有样式
pdfContent.style.overflow = originalOverflow;
pdfContent.style.height = originalHeight; const pdf = new jsPDF("p", "mm", "a4");
const margin = 10;
const a4Width = 190; // A4宽 210 - 边距 20
const a4Height = 277; // A4高 297 - 边距 20 const pxPerMm = canvas.width / a4Width;
const pageHeightPx = a4Height * pxPerMm; // 3. 收集所有需要避免截断的元素坐标
const breakPoints: Array<{ startY: number; endY: number }> = [];
noBreakSelectors.forEach(selector => {
const els = pdfContent.querySelectorAll(selector);
els.forEach((el) => {
const rect = el.getBoundingClientRect();
const startY = (rect.top - containerRect.top) * scale;
const endY = startY + rect.height * scale;
breakPoints.push({ startY, endY });
});
}); let currentY = 0;
let pageIndex = 0; // 4. 智能分页切割 Canvas
while (currentY < canvas.height) {
let targetEndY = currentY + pageHeightPx; // 检查是否切到了需要保护的元素
for (let point of breakPoints) {
if (targetEndY > point.startY && targetEndY < point.endY) {
targetEndY = point.startY; // 提前换页,将元素推到下一页
break;
}
} // 边界保护
if (targetEndY <= currentY) targetEndY = currentY + pageHeightPx;
if (targetEndY > canvas.height) targetEndY = canvas.height; const cropHeight = targetEndY - currentY;
const cropCanvas = document.createElement("canvas");
cropCanvas.width = canvas.width;
cropCanvas.height = cropHeight;
const ctx = cropCanvas.getContext("2d");
if (ctx) {
// 填充白色背景,解决最后留白处变黑的问题
ctx.fillStyle = "#ffffff";
ctx.fillRect(0, 0, cropCanvas.width, cropCanvas.height); ctx.drawImage(
canvas,
0, currentY, canvas.width, cropHeight,
0, 0, canvas.width, cropHeight
); const cropImgData = cropCanvas.toDataURL("image/jpeg", 1.0);
const cropHeightMm = cropHeight / pxPerMm; if (pageIndex > 0) pdf.addPage();
pdf.addImage(cropImgData, "JPEG", margin, margin, a4Width, cropHeightMm);
} currentY = targetEndY;
pageIndex++;
// 【关键优化2】:每切一页让出主线程,防止切片循环导致浏览器假死
await delay(0);
} pdf.save(title + ".pdf");
} catch (err) {
// 发生异常时恢复样式并抛出错误
pdfContent.style.overflow = originalOverflow;
pdfContent.style.height = originalHeight;
console.error("导出PDF失败:", err);
throw err;
}
},
};export default htmlToPdf;
复制代码<div id="report-container">
<h1>季度数据报表h1>
<div class="a void-break">
div>
<p>这是一段重要的说明文字,不希望被分页截断。p>
<button id="export-btn" @click="handleExport">导出 PDFbutton>
div>
复制代码import htmlToPdf from './utils/htmlToPdf';const handleExport = async () => {
// 1. 开启页面 loading 动画
this.loading = true;
try {
// 2. 调用导出方法
await htmlToPdf.getPdf("季度数据报表", "#report-container", {
// 保护 Echarts 图表、段落文字 p 不被切断
noBreakSelectors: [".a void-break", "p", "tr"],
// 导出时排除导出按钮
excludeIds: ["export-btn"],
// 清晰度与性能的平衡点
scale: 1.5,
});
// 3. 导出成功提示
this.$message.success("PDF 导出成功!");
} catch (error) {
this.$message.error("导出失败,请重试");
} finally {
// 4. 关闭 loading 动画
this.loading = false;
}
};
侠游戏发布此文仅为了传递信息,不代表侠游戏网站认同其观点或证实其描述