Skip to content

writeHTML(): whitespace around table cell content breaks text-align (7.x regression) #875

Description

@naumso

Environment: tecnickcom/tcpdf 7.0.6, tc-lib-pdf 8.70.3, PHP 8.5

In TCPDF 7, whitespace-only text nodes at <td>/<th> boundaries (and after
<br>) disable the cell's text-align. The same markup written on a single
line renders correctly. Per HTML whitespace-collapsing rules, inter-tag
newlines/indentation should not affect layout — and TCPDF 6 rendered both
variants identically. This hits any HTML produced by a template engine (Twig,
Blade, …), since generated markup is normally indented.

Reproduce:

$pdf = new TCPDF('P');
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);
$pdf->setMargins(0, 0, 0, true);
$pdf->setAutoPageBreak(false, 0);
$pdf->setFont('freesans', '', 14);
$pdf->AddPage();

$css = '<style>.tbl { width: 205mm; text-align: center; }</style>';

// Variant A: single line -> centered (correct)
$a = $css . '<table class="tbl"><tr><td colspan="2">Centered text<br>second line</td></tr></table>';

// Variant B: same markup, indented -> renders LEFT-aligned (wrong)
$b = $css . '<table class="tbl">
    <tr>
      <td colspan="2">
        Centered text<br>
        second line
      </td>
    </tr>
  </table>';

$pdf->writeHTML($a, true);
$pdf->writeHTML($b, true);
$pdf->Output('repro.pdf', 'I');

Expected: both variants centered (TCPDF 6 behaviour).
Actual: variant B is left-aligned. Even a single space around the text node
(e.g. after collapsing all whitespace runs to one space) is enough to trigger it;
the alignment only survives when the whitespace touching the cell content is
stripped completely.

Workaround we use: pre-process the HTML with
preg_replace('#(<td[^>]*>)\s+#', '$1', …) / preg_replace('#\s+(</td>)#', '$1', …) /
preg_replace('#(<br\s*/?>)\s+#i', '$1', …) before writeHTML().

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions