html2pdf生成PDF时表格跨页拆分,如何设置使其完整显示?
解决Html2Pdf表格跨页拆分及重复表头问题
问题说明
使用最新版Html2Pdf生成PDF时,表格在页面末尾被拆分为两部分,且重复显示表头。需求是让表格作为整体块显示,若当前页面空间不足则自动移至下一页。
解决方案
1. 用CSS阻止表格内部分页
给表格添加page-break-inside: avoid;样式,强制Html2Pdf避免在表格内部拆分页面。修改print.php中的表格代码:
<table class="table-block" width="100%" name="long-table" style="margin-bottom:10px; padding:0; border-spacing: 0; border-collapse: collapse; page-break-inside: avoid;">
2. 禁用表头自动重复
Html2Pdf默认会在分页后重复<thead>内容,可通过两种方式禁用:
方式A:修改Html2Pdf初始化配置
在主脚本中添加默认样式配置:
$html2pdf = new Html2Pdf('P', 'A4', 'fr'); // 禁用表头重复 $html2pdf->setDefaultStyle(['thead' => ['display' => 'table-row-group']]); $html2pdf->writeHTML($content);
方式B:直接给<thead>加样式
修改print.php中的表头标签:
<thead style="display: table-row-group;">
3. 用Html2Pdf分页标签自动判断
如果上述方法仍有问题,可在每个表格前添加<pagebreak auto="true" />标签,让Html2Pdf自动判断当前页剩余空间是否足够容纳表格,不足则自动跳转到下一页:
<pagebreak auto="true" /> <table class="table-block" ...>
综合修改示例
主脚本修改
<?php require ($_SERVER['DOCUMENT_ROOT']."/includes/config.php"); require ($_SERVER['DOCUMENT_ROOT']."/vendor/autoload.php"); use Spipu\Html2Pdf\Html2Pdf; use Spipu\Html2Pdf\Exception\Html2PdfException; use Spipu\Html2Pdf\Exception\ExceptionFormatter; try { ob_start(); include dirname(__FILE__).'/imprimer/imprimer.php'; $content = ob_get_clean(); $html2pdf = new Html2Pdf('P', 'A4', 'fr'); // 禁用表头自动重复 $html2pdf->setDefaultStyle(['thead' => ['display' => 'table-row-group']]); $html2pdf->writeHTML($content); $html2pdf->output('Tableau de suivi - SIVOP CI - '.date("Y-m-d").'.pdf'); } catch (Html2PdfException $e) { $html2pdf->clean(); $formatter = new ExceptionFormatter($e); echo $formatter->getHtmlMessage(); } ?>
print.php修改
<?php $valeur = "Produit"; try{ $query = "SELECT * FROM $TABLE_PROJET WHERE statut = :valeur ORDER BY nature DESC, marque ASC, libelle ASC"; $stats = $pdo->prepare($query); $stats ->execute(['valeur' => $valeur]); while($data = $stats->fetch(PDO::FETCH_ASSOC)){ $hash = $data["hash"]; $code = $data["code"]; if($code != null) {$code = "<b>".$code."</b> | ";} else {$code = null;} $date = "<span class='small'>".strftime("%d-%m-%Y", strtotime($data["date"]))."</span> | "; $marque = "<b>".$data["marque"]."</b> » "; $libelle = "<b>".$data["libelle"]."</b>"; ?> <pagebreak auto="true" /> <table class="table-block" width="100%" name="long-table" style="margin-bottom:10px; padding:0; border-spacing: 0; border-collapse: collapse; page-break-inside: avoid;"> <thead style="display: table-row-group;"><tr style="<?=$tableau_04?>"><td colspan="3"><?=$date.$code.$marque.$libelle?></td></tr></thead> <tbody style="border-color: #212529;"> <?php require("imprimer/tableau.php"); ?> </tbody> </table> <?php }}catch(PDOException $e){echo "<div class='alert alert-danger'>".$e->getMessage()."</div>";} ?>
内容的提问来源于stack exchange,提问作者Jaber
相关产品推荐
相关产品推荐

