From 701f770ab781d92723ca2e7ae1471466d349040d Mon Sep 17 00:00:00 2001 From: lubosdz Date: Fri, 10 Jul 2020 12:43:19 +0200 Subject: [PATCH] Html parser (addHtml) - support width in tables & cells --- src/PhpWord/Shared/Html.php | 19 ++++++++- tests/PhpWord/Shared/HtmlTest.php | 70 +++++++++++++++++++++++++++++++ 2 files changed, 88 insertions(+), 1 deletion(-) diff --git a/src/PhpWord/Shared/Html.php b/src/PhpWord/Shared/Html.php index 54e9509e..cb09af62 100644 --- a/src/PhpWord/Shared/Html.php +++ b/src/PhpWord/Shared/Html.php @@ -106,6 +106,19 @@ class Html case 'lang': $styles['lang'] = $attribute->value; break; + case 'width': + // tables, cells + $val = trim($attribute->value); + if(false !== strpos($val, '%')){ + // e.g. or
+ $styles['width'] = intval($val) * 50; + $styles['unit'] = \PhpOffice\PhpWord\SimpleType\TblWidth::PERCENT; + }else{ + // e.g. addCell(null, $cellStyles); + + // set cell width to control column widths + $width = isset($cellStyles['width']) ? $cellStyles['width'] : null; + unset($cellStyles['width']); // would not apply + $cell = $element->addCell($width, $cellStyles); if (self::shouldAddTextRun($node)) { return $cell->addTextRun(self::parseInlineStyle($node, $styles['paragraph'])); diff --git a/tests/PhpWord/Shared/HtmlTest.php b/tests/PhpWord/Shared/HtmlTest.php index 5bc9e241..5474eb0d 100644 --- a/tests/PhpWord/Shared/HtmlTest.php +++ b/tests/PhpWord/Shared/HtmlTest.php @@ -632,4 +632,74 @@ class HtmlTest extends AbstractWebServerEmbeddedTest $this->assertTrue($doc->elementExists('/w:document/w:body/w:p/w:r/w:rPr/w:spacing')); $this->assertEquals(150 * 15, $doc->getElement('/w:document/w:body/w:p/w:r/w:rPr/w:spacing')->getAttribute('w:val')); } + + /** + * Parse widths in tables and cells, which also allows for controlling column width + */ + public function testParseTableAndCellWidth() + { + $phpWord = new \PhpOffice\PhpWord\PhpWord(); + $section = $phpWord->addSection([ + 'orientation' => \PhpOffice\PhpWord\Style\Section::ORIENTATION_LANDSCAPE, + ]); + + // borders & backgrounds are here just for better visual comparison + $html = << + + + + +
25% + + + + + + + + + + + + + +
400px
T2.R2.C150ptT2.R2.C3
300pxT2.R3.C3
+
+HTML; + + Html::addHtml($section, $html); + $doc = TestHelperDOCX::getDocument($phpWord, 'Word2007'); + + // outer table grid + $xpath = '/w:document/w:body/w:tbl/w:tblGrid/w:gridCol'; + $this->assertTrue($doc->elementExists($xpath)); + $this->assertEquals(25 * 50, $doc->getElement($xpath)->getAttribute('w:w')); + $this->assertEquals('dxa', $doc->getElement($xpath)->getAttribute('w:type')); + + //
assertTrue($doc->elementExists($xpath)); + $this->assertEquals(6000, $doc->getElement($xpath)->getAttribute('w:w')); + $this->assertEquals('dxa', $doc->getElement($xpath)->getAttribute('w:type')); + + // assertTrue($doc->elementExists($xpath)); + $this->assertEquals(4500, $doc->getElement($xpath)->getAttribute('w:w')); + $this->assertEquals('dxa', $doc->getElement($xpath)->getAttribute('w:type')); + } + }