html2pdf导出PDF后表格顶部出现多余间距问题求解决方案
html2pdf导出表格顶部多余间距解决方案
方案1:强制重置导出元素的内联样式
html2canvas渲染时会优先拾取全局样式、框架默认打印样式,很多CSS框架(比如你用到的Bootstrap的table类)会给@media print场景下的表格预设顶部边距,直接给导出容器和表格加优先级最高的内联样式覆盖即可:
<!-- 给导出根容器加样式 --> <div id="pm-pdf" style="margin: 0 !important; padding: 0 !important;"> <!-- 给表格加样式 --> <table class="table table-bordered" style="border-collapse: collapse !important; margin: 0 !important; padding: 0 !important;"> <tbody style="margin: 0 !important; padding: 0 !important;"> <tr class="prnt" *ngFor="let component of routineJobData.pmComponents[title]; let i=index" style="margin: 0 !important; padding: 0 !important;"> <td style="margin: 0 !important; padding: 4px !important;">{{component.label}}:</td> <td style="margin: 0 !important; padding: 4px !important;">{{component.value}}</td> </tr> </tbody> </table> </div>
方案2:添加分页配置禁用自动偏移
html2pdf默认的分页逻辑会给跨页元素自动添加顶部偏移,在配置中新增pagebreak参数关闭自适应偏移即可:
html2pdf(document.getElementById('pm-pdf'), { margin: 10, filename: 'PM.pdf', image: { type: 'jpeg', quality: 0.98 }, // 新增pagebreak配置,避免自动分页产生的顶部留白 pagebreak: { mode: ['avoid-all'] }, html2canvas: { scale: 2, logging: true, dpi: 192, letterRendering: true }, jsPDF: { unit: 'mm', format: 'a3', orientation: 'portrait' } });
方案3:导出前裁剪画布空白
如果上述方案都无效,可以手动处理html2canvas生成的画布,裁剪掉顶部多余空白后再生成PDF:
const opt = { margin: 10, filename: 'PM.pdf', image: { type: 'jpeg', quality: 0.98 }, html2canvas: { scale: 2, logging: true, dpi: 192, letterRendering: true }, jsPDF: { unit: 'mm', format: 'a3', orientation: 'portrait' } }; // 手动处理画布 html2canvas(document.getElementById('pm-pdf'), opt.html2canvas).then(canvas => { // 计算实际内容的顶部起始位置 const ctx = canvas.getContext('2d'); const pixels = ctx.getImageData(0, 0, canvas.width, canvas.height).data; let topOffset = 0; // 遍历像素找第一个非空白行 outer: for (let y = 0; y < canvas.height; y++) { for (let x = 0; x < canvas.width; x++) { const index = (y * canvas.width + x) * 4; if (pixels[index + 3] !== 0) { // 像素不透明即为内容起始点 topOffset = y; break outer; } } } // 裁剪空白生成新画布 const trimmedCanvas = document.createElement('canvas'); trimmedCanvas.width = canvas.width; trimmedCanvas.height = canvas.height - topOffset; trimmedCanvas.getContext('2d').drawImage(canvas, 0, topOffset, canvas.width, trimmedCanvas.height, 0, 0, canvas.width, trimmedCanvas.height); // 用裁剪后的画布生成PDF const pdf = new jsPDF(opt.jsPDF); const imgData = trimmedCanvas.toDataURL('image/jpeg', 0.98); const imgWidth = pdf.internal.pageSize.getWidth(); const imgHeight = trimmedCanvas.height * imgWidth / trimmedCanvas.width; pdf.addImage(imgData, 'JPEG', opt.margin, opt.margin, imgWidth - 2*opt.margin, imgHeight - 2*opt.margin); pdf.save(opt.filename); });
内容的提问来源于stack exchange,提问作者Hassan Ali
相关产品推荐
相关产品推荐

