You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MPDF生成大数据表格:如何避免自动调整尺寸?

解决mPDF导出大表格自动缩放导致显示异常的问题

我之前也跟你一样踩过mPDF处理超大表格的坑,试了好几种方法才搞定,给你几个针对性的解决方案:

1. 强制禁用表格自动缩放,用CSS固定布局

shrink_tables_to_fit=1是允许mPDF自动收缩表格,你需要把它设为0来强制禁用,同时配合CSS固定表格和列宽,避免表格被挤变形:

  • 修改mPDF设置:
    $mpdf->shrink_tables_to_fit = 0;
    
  • 在你的PDF专用CSS里添加以下样式(或者追加到现有stylesheet中):
    table {
        table-layout: fixed !important; /* 固定表格布局,按设置的列宽渲染 */
        width: 100% !important;
        border-collapse: collapse !important; /* 确保边框正常显示 */
    }
    table th, table td {
        width: 120px !important; /* 根据你的列数和内容调整宽度 */
        word-wrap: break-word; /* 长文本自动换行,防止撑破单元格 */
        white-space: normal !important; /* 禁用 nowrap 强制换行 */
    }
    

2. 排除Bootstrap样式的干扰

Bootstrap的table-responsive类会给表格加横向滚动容器,这在mPDF里会导致表格被压缩,建议直接移除这个类,或者在PDF CSS里覆盖它:

.table-responsive {
    overflow-x: visible !important;
    width: 100% !important;
}

3. 切换页面方向或启用自动横向分页

如果表格列数实在太多,纵向A4页面放不下,可以直接设置横向页面:

$mpdf = new mPDF('pt', 'A4-L'); // A4-L 表示横向A4

或者让mPDF根据内容自动切换横向:

$mpdf->allowLandscape = true;
$mpdf->autoPageBreak = true;

4. 移除表格的autosize属性

你提到给表格设置了autosize=1,这个属性会让mPDF自动调整表格尺寸,反而会干扰我们的固定布局设置,建议直接去掉这个属性。


修改后的完整代码示例

$stylesheet = file_get_contents($_SERVER['DOCUMENT_ROOT'].'/site/css/layout/pdf.css');
// 追加自定义表格控制样式
$customCss = '
table {
    table-layout: fixed !important;
    width: 100% !important;
    border-collapse: collapse !important;
}
table th, table td {
    width: 120px !important;
    word-wrap: break-word;
    white-space: normal !important;
}
.table-responsive {
    overflow-x: visible !important;
    width: 100% !important;
}
';
$stylesheet .= $customCss;

$bootstrap = file_get_contents('https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css');
// 如果需要横向页面,把'a4'改成'A4-L'
$mpdf = new mPDF('pt', 'a4');
$mpdf->shrink_tables_to_fit = 0;
$mpdf->setAutoTopMargin = 'stretch';
$mpdf->setAutoBottomMargin = 'stretch';
$mpdf->allowLandscape = true;
$mpdf->autoPageBreak = true;
$mpdf->SetHTMLHeader('<img src="'.$_SERVER['DOCUMENT_ROOT'].'/site/img/content/pdf/header.jpg">');
$mpdf->SetFooter('{DATE j/m/Y H:i}|{PAGENO}/{nb}');
$mpdf->WriteHTML($bootstrap, 1);
$mpdf->WriteHTML($stylesheet, 1);
$mpdf->WriteHTML($html);
$mpdf->Output($_SERVER['DOCUMENT_ROOT'].'/upload/consultas-pre/'.$nomeArquivo.'.pdf', 'F');

如果还是有问题,可以检查你的HTML表格是否有复杂的colspan/rowspan,这些结构可能会让mPDF的渲染逻辑混乱,尽量简化表格结构,或者给合并后的单元格单独设置宽度。

内容的提问来源于stack exchange,提问作者Maykel Esser

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 04:56:16