Html   F
last analyzed

Complexity

Total Complexity 348

Size/Duplication

Total Lines 2083
Duplicated Lines 0 %

Test Coverage

Coverage 99.15%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 348
eloc 935
c 1
b 0
f 0
dl 0
loc 2083
ccs 930
cts 938
cp 0.9915
rs 1.665

70 Methods

Rating   Name   Duplication   Size   Complexity  
A generateMeta() 0 5 3
A getGenerateSheetNavigationBlock() 0 3 1
A writeAllSheets() 0 5 1
A setGenerateSheetNavigationBlock() 0 5 1
A mapHAlign() 0 3 1
A setEditHtmlCallback() 0 3 1
A mapVAlign() 0 3 1
B calculateSpansOmitRows() 0 27 8
A buildCssRowHeights() 0 16 4
B buildCSS() 0 88 7
A setEmbedImages() 0 5 1
A generateTableFooter() 0 3 1
A getSheetIndex() 0 3 1
A createCSSStyle() 0 8 1
B generatePageDeclarations() 0 57 7
A shouldGenerateColumn() 0 10 4
B generateHTMLHeader() 0 61 9
A generateHTMLFooter() 0 8 1
C writeImageInCell() 0 79 14
B writeChartInCell() 0 52 11
A setTableFormats() 0 5 1
A createCSSStyleBorder() 0 6 2
A writeComment() 0 19 6
A generateStyles() 0 29 6
A generateSheetStarts() 0 17 3
A replaceControlChars() 0 6 1
A getEmbedImages() 0 3 1
A shouldGenerateRow() 0 7 3
A generateRowSpans() 0 6 3
C generateRowCellData() 0 58 15
A formatColor() 0 3 1
C generateSheetData() 0 80 15
A setBetterBoolean() 0 5 1
B calculateSpans() 0 61 9
A replaceNonAscii() 0 3 1
A setSheetIndex() 0 5 1
B generateRowCellDataValueRich() 0 38 6
A getOrientation() 0 4 2
A generateHtmlAll() 0 38 5
A formatColorStatic() 0 21 3
A setConditionalFormatting() 0 5 1
A generateRowCellCss() 0 11 3
A getImagesRoot() 0 3 1
C buildCssPerSheet() 0 66 11
A getBetterBoolean() 0 3 1
A createCSSStyleBorders() 0 28 6
A assembleCSS() 0 9 2
A generateSheetTags() 0 11 6
F generateRow() 0 91 19
A generateRowIncludeCharts() 0 3 2
B adjustRendererPositions() 0 30 10
A generateSheetPrep() 0 10 2
C generateRowCellDataValue() 0 39 13
B generateTableTagInline() 0 18 7
A generateTableTag() 0 8 4
A setImagesRoot() 0 5 1
A createCSSStyleFill() 0 20 6
B createCSSStyleAlignment() 0 27 7
A save() 0 9 1
B createCSSStyleFont() 0 25 7
A generateTableHeader() 0 29 6
A __construct() 0 7 1
B generateRowStart() 0 31 7
A getUseInlineCss() 0 3 1
A winFileToUrl() 0 9 3
A generateNavigation() 0 29 4
B extendRowsAndColumns() 0 26 10
F generateRowWriteCell() 0 144 41
A setUseInlineCss() 0 5 1
A mapBorderStyle() 0 3 1

How to fix   Complexity   

Complex Class

Complex classes like Html often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Html, and based on these observations, apply Extract Interface, too.

1
<?php
2
3
namespace PhpOffice\PhpSpreadsheet\Writer;
4
5
use Composer\Pcre\Preg;
6
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
7
use PhpOffice\PhpSpreadsheet\Calculation\Exception as CalculationException;
8
use PhpOffice\PhpSpreadsheet\Cell\Cell;
9
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
10
use PhpOffice\PhpSpreadsheet\Cell\DataType;
11
use PhpOffice\PhpSpreadsheet\Chart\Chart;
12
use PhpOffice\PhpSpreadsheet\Comment;
13
use PhpOffice\PhpSpreadsheet\Document\Properties;
14
use PhpOffice\PhpSpreadsheet\RichText\RichText;
15
use PhpOffice\PhpSpreadsheet\RichText\Run;
16
use PhpOffice\PhpSpreadsheet\Settings;
17
use PhpOffice\PhpSpreadsheet\Shared\Date;
18
use PhpOffice\PhpSpreadsheet\Shared\Drawing as SharedDrawing;
19
use PhpOffice\PhpSpreadsheet\Shared\File;
20
use PhpOffice\PhpSpreadsheet\Shared\Font as SharedFont;
21
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
22
use PhpOffice\PhpSpreadsheet\Spreadsheet;
23
use PhpOffice\PhpSpreadsheet\Style\Alignment;
24
use PhpOffice\PhpSpreadsheet\Style\Border;
25
use PhpOffice\PhpSpreadsheet\Style\Borders;
26
use PhpOffice\PhpSpreadsheet\Style\Conditional;
27
use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\CellStyleAssessor;
28
use PhpOffice\PhpSpreadsheet\Style\ConditionalFormatting\StyleMerger;
29
use PhpOffice\PhpSpreadsheet\Style\Fill;
30
use PhpOffice\PhpSpreadsheet\Style\Font;
31
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
32
use PhpOffice\PhpSpreadsheet\Style\Style;
33
use PhpOffice\PhpSpreadsheet\Worksheet\BaseDrawing;
34
use PhpOffice\PhpSpreadsheet\Worksheet\Drawing;
35
use PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing;
36
use PhpOffice\PhpSpreadsheet\Worksheet\PageSetup;
37
use PhpOffice\PhpSpreadsheet\Worksheet\Table;
38
use PhpOffice\PhpSpreadsheet\Worksheet\Table\TableDxfsStyle;
39
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
40
41
class Html extends BaseWriter
42
{
43
    private const DEFAULT_CELL_WIDTH_POINTS = 42;
44
45
    private const DEFAULT_CELL_WIDTH_PIXELS = 56;
46
47
    /**
48
     * Migration aid to tell if html tags will be treated as plaintext in comments.
49
     *     if (
50
     *         defined(
51
     *             \PhpOffice\PhpSpreadsheet\Writer\Html::class
52
     *             . '::COMMENT_HTML_TAGS_PLAINTEXT'
53
     *         )
54
     *     ) {
55
     *         new logic with styling in TextRun elements
56
     *     } else {
57
     *         old logic with styling via Html tags
58
     *     }.
59
     */
60
    public const COMMENT_HTML_TAGS_PLAINTEXT = true;
61
62
    /**
63
     * Spreadsheet object.
64
     */
65
    protected Spreadsheet $spreadsheet;
66
67
    /**
68
     * Sheet index to write.
69
     */
70
    private ?int $sheetIndex = 0;
71
72
    /**
73
     * Images root.
74
     */
75
    private string $imagesRoot = '';
76
77
    /**
78
     * embed images, or link to images.
79
     */
80
    protected bool $embedImages = false;
81
82
    /**
83
     * Use inline CSS?
84
     */
85
    private bool $useInlineCss = false;
86
87
    /**
88
     * Array of CSS styles.
89
     *
90
     * @var string[][]
91
     */
92
    private ?array $cssStyles = null;
93
94
    /**
95
     * Array of column widths in points.
96
     *
97
     * @var array<array<float|int>>
98
     */
99
    private array $columnWidths;
100
101
    /**
102
     * Default font.
103
     */
104
    private Font $defaultFont;
105
106
    /**
107
     * Flag whether spans have been calculated.
108
     */
109
    private bool $spansAreCalculated = false;
110
111
    /**
112
     * Excel cells that should not be written as HTML cells.
113
     *
114
     * @var mixed[][][][]
115
     */
116
    private array $isSpannedCell = [];
117
118
    /**
119
     * Excel cells that are upper-left corner in a cell merge.
120
     *
121
     * @var int[][][][]
122
     */
123
    private array $isBaseCell = [];
124
125
    /**
126
     * Excel rows that should not be written as HTML rows.
127
     *
128
     * @var mixed[][]
129
     */
130
    private array $isSpannedRow = [];
131
132
    /**
133
     * Is the current writer creating PDF?
134
     */
135
    protected bool $isPdf = false;
136
137
    /**
138
     * Generate the Navigation block.
139
     */
140
    private bool $generateSheetNavigationBlock = true;
141
142
    /**
143
     * Callback for editing generated html.
144
     *
145
     * @var null|callable(string): string
146
     */
147
    private $editHtmlCallback;
148
149
    /** @var BaseDrawing[] */
150
    private $sheetDrawings;
151
152
    /** @var Chart[] */
153
    private $sheetCharts;
154
155
    private bool $betterBoolean = true;
156
157
    private string $getTrue = 'TRUE';
158
159
    private string $getFalse = 'FALSE';
160
161
    /**
162
     * Create a new HTML.
163
     */
164 554
    public function __construct(Spreadsheet $spreadsheet)
165
    {
166 554
        $this->spreadsheet = $spreadsheet;
167 554
        $this->defaultFont = $this->spreadsheet->getDefaultStyle()->getFont();
168 554
        $calc = Calculation::getInstance($this->spreadsheet);
169 554
        $this->getTrue = $calc->getTRUE();
170 554
        $this->getFalse = $calc->getFALSE();
171
    }
172
173
    /**
174
     * Save Spreadsheet to file.
175
     *
176
     * @param resource|string $filename
177
     */
178 463
    public function save($filename, int $flags = 0): void
179
    {
180 463
        $this->processFlags($flags);
181
        // Open file
182 463
        $this->openFileHandle($filename);
183
        // Write html
184 462
        fwrite($this->fileHandle, $this->generateHTMLAll());
185
        // Close file
186 462
        $this->maybeCloseFileHandle();
187
    }
188
189
    /**
190
     * Save Spreadsheet as html to variable.
191
     */
192 541
    public function generateHtmlAll(): string
193
    {
194 541
        $sheets = $this->generateSheetPrep();
195 541
        foreach ($sheets as $sheet) {
196 541
            $sheet->calculateArrays($this->preCalculateFormulas);
197
        }
198
        // garbage collect
199 541
        $this->spreadsheet->garbageCollect();
200
201 541
        $saveDebugLog = Calculation::getInstance($this->spreadsheet)->getDebugLog()->getWriteDebugLog();
202 541
        Calculation::getInstance($this->spreadsheet)->getDebugLog()->setWriteDebugLog(false);
203
204
        // Build CSS
205 541
        $this->buildCSS(!$this->useInlineCss);
206
207 541
        $html = '';
208
209
        // Write headers
210 541
        $html .= $this->generateHTMLHeader(!$this->useInlineCss);
211
212
        // Write navigation (tabs)
213 541
        if ((!$this->isPdf) && ($this->generateSheetNavigationBlock)) {
214 510
            $html .= $this->generateNavigation();
215
        }
216
217
        // Write data
218 541
        $html .= $this->generateSheetData();
219
220
        // Write footer
221 541
        $html .= $this->generateHTMLFooter();
222 541
        $callback = $this->editHtmlCallback;
223 541
        if ($callback) {
224 6
            $html = $callback($html);
225
        }
226
227 541
        Calculation::getInstance($this->spreadsheet)->getDebugLog()->setWriteDebugLog($saveDebugLog);
228
229 541
        return $html;
230
    }
231
232
    /**
233
     * Set a callback to edit the entire HTML.
234
     *
235
     * The callback must accept the HTML as string as first parameter,
236
     * and it must return the edited HTML as string.
237
     */
238 6
    public function setEditHtmlCallback(?callable $callback): void
239
    {
240 6
        $this->editHtmlCallback = $callback;
241
    }
242
243
    /**
244
     * Map VAlign.
245
     *
246
     * @param string $vAlign Vertical alignment
247
     */
248 543
    private function mapVAlign(string $vAlign): string
249
    {
250 543
        return Alignment::VERTICAL_ALIGNMENT_FOR_HTML[$vAlign] ?? '';
251
    }
252
253
    /**
254
     * Map HAlign.
255
     *
256
     * @param string $hAlign Horizontal alignment
257
     */
258 543
    private function mapHAlign(string $hAlign): string
259
    {
260 543
        return Alignment::HORIZONTAL_ALIGNMENT_FOR_HTML[$hAlign] ?? '';
261
    }
262
263
    const BORDER_NONE = 'none';
264
    const BORDER_ARR = [
265
        Border::BORDER_NONE => self::BORDER_NONE,
266
        Border::BORDER_DASHDOT => '1px dashed',
267
        Border::BORDER_DASHDOTDOT => '1px dotted',
268
        Border::BORDER_DASHED => '1px dashed',
269
        Border::BORDER_DOTTED => '1px dotted',
270
        Border::BORDER_DOUBLE => '3px double',
271
        Border::BORDER_HAIR => '1px solid',
272
        Border::BORDER_MEDIUM => '2px solid',
273
        Border::BORDER_MEDIUMDASHDOT => '2px dashed',
274
        Border::BORDER_MEDIUMDASHDOTDOT => '2px dotted',
275
        Border::BORDER_SLANTDASHDOT => '2px dashed',
276
        Border::BORDER_THICK => '3px solid',
277
    ];
278
279
    /**
280
     * Map border style.
281
     *
282
     * @param int|string $borderStyle Sheet index
283
     */
284 531
    private function mapBorderStyle($borderStyle): string
285
    {
286 531
        return self::BORDER_ARR[$borderStyle] ?? '1px solid';
287
    }
288
289
    /**
290
     * Get sheet index.
291
     */
292 18
    public function getSheetIndex(): ?int
293
    {
294 18
        return $this->sheetIndex;
295
    }
296
297
    /**
298
     * Set sheet index.
299
     *
300
     * @param int $sheetIndex Sheet index
301
     *
302
     * @return $this
303
     */
304 1
    public function setSheetIndex(int $sheetIndex): static
305
    {
306 1
        $this->sheetIndex = $sheetIndex;
307
308 1
        return $this;
309
    }
310
311
    /**
312
     * Get sheet index.
313
     */
314 1
    public function getGenerateSheetNavigationBlock(): bool
315
    {
316 1
        return $this->generateSheetNavigationBlock;
317
    }
318
319
    /**
320
     * Set sheet index.
321
     *
322
     * @param bool $generateSheetNavigationBlock Flag indicating whether the sheet navigation block should be generated or not
323
     *
324
     * @return $this
325
     */
326 1
    public function setGenerateSheetNavigationBlock(bool $generateSheetNavigationBlock): static
327
    {
328 1
        $this->generateSheetNavigationBlock = (bool) $generateSheetNavigationBlock;
329
330 1
        return $this;
331
    }
332
333
    /**
334
     * Write all sheets (resets sheetIndex to NULL).
335
     *
336
     * @return $this
337
     */
338 15
    public function writeAllSheets(): static
339
    {
340 15
        $this->sheetIndex = null;
341
342 15
        return $this;
343
    }
344
345 543
    private static function generateMeta(?string $val, string $desc): string
346
    {
347 543
        return ($val || $val === '0')
348 543
            ? ('      <meta name="' . $desc . '" content="' . htmlspecialchars($val, Settings::htmlEntityFlags()) . '" />' . PHP_EOL)
349 543
            : '';
350
    }
351
352
    public const BODY_LINE = '  <body>' . PHP_EOL;
353
354
    private const CUSTOM_TO_META = [
355
        Properties::PROPERTY_TYPE_BOOLEAN => 'bool',
356
        Properties::PROPERTY_TYPE_DATE => 'date',
357
        Properties::PROPERTY_TYPE_FLOAT => 'float',
358
        Properties::PROPERTY_TYPE_INTEGER => 'int',
359
        Properties::PROPERTY_TYPE_STRING => 'string',
360
    ];
361
362
    /**
363
     * Generate HTML header.
364
     *
365
     * @param bool $includeStyles Include styles?
366
     */
367 543
    public function generateHTMLHeader(bool $includeStyles = false): string
368
    {
369
        // Construct HTML
370 543
        $properties = $this->spreadsheet->getProperties();
371 543
        $html = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">' . PHP_EOL;
372 543
        $html .= '<html xmlns="http://www.w3.org/1999/xhtml">' . PHP_EOL;
373 543
        $html .= '  <head>' . PHP_EOL;
374 543
        $html .= '      <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />' . PHP_EOL;
375 543
        $html .= '      <meta name="generator" content="PhpSpreadsheet, https://github.com/PHPOffice/PhpSpreadsheet" />' . PHP_EOL;
376 543
        $title = $properties->getTitle();
377 543
        if ($title === '') {
378 19
            $title = $this->spreadsheet->getActiveSheet()->getTitle();
379
        }
380 543
        $html .= '      <title>' . htmlspecialchars($title, Settings::htmlEntityFlags()) . '</title>' . PHP_EOL;
381 543
        $html .= self::generateMeta($properties->getCreator(), 'author');
382 543
        $html .= self::generateMeta($properties->getTitle(), 'title');
383 543
        $html .= self::generateMeta($properties->getDescription(), 'description');
384 543
        $html .= self::generateMeta($properties->getSubject(), 'subject');
385 543
        $html .= self::generateMeta($properties->getKeywords(), 'keywords');
386 543
        $html .= self::generateMeta($properties->getCategory(), 'category');
387 543
        $html .= self::generateMeta($properties->getCompany(), 'company');
388 543
        $html .= self::generateMeta($properties->getManager(), 'manager');
389 543
        $html .= self::generateMeta($properties->getLastModifiedBy(), 'lastModifiedBy');
390 543
        $html .= self::generateMeta($properties->getViewport(), 'viewport');
391 543
        $date = Date::dateTimeFromTimestamp((string) $properties->getCreated());
392 543
        $date->setTimeZone(Date::getDefaultOrLocalTimeZone());
393 543
        $html .= self::generateMeta($date->format(DATE_W3C), 'created');
394 543
        $date = Date::dateTimeFromTimestamp((string) $properties->getModified());
395 543
        $date->setTimeZone(Date::getDefaultOrLocalTimeZone());
396 543
        $html .= self::generateMeta($date->format(DATE_W3C), 'modified');
397
398 543
        $customProperties = $properties->getCustomProperties();
399 543
        foreach ($customProperties as $customProperty) {
400 4
            $propertyValue = $properties->getCustomPropertyValue($customProperty);
401 4
            $propertyType = $properties->getCustomPropertyType($customProperty);
402 4
            $propertyQualifier = self::CUSTOM_TO_META[$propertyType] ?? null;
403 4
            if ($propertyQualifier !== null) {
404 4
                if ($propertyType === Properties::PROPERTY_TYPE_BOOLEAN) {
405 1
                    $propertyValue = $propertyValue ? '1' : '0';
406 4
                } elseif ($propertyType === Properties::PROPERTY_TYPE_DATE) {
407 1
                    $date = Date::dateTimeFromTimestamp((string) $propertyValue);
408 1
                    $date->setTimeZone(Date::getDefaultOrLocalTimeZone());
409 1
                    $propertyValue = $date->format(DATE_W3C);
410
                } else {
411 4
                    $propertyValue = (string) $propertyValue;
412
                }
413 4
                $html .= self::generateMeta($propertyValue, htmlspecialchars("custom.$propertyQualifier.$customProperty"));
414
            }
415
        }
416
417 543
        if (!empty($properties->getHyperlinkBase())) {
418 2
            $html .= '      <base href="' . htmlspecialchars($properties->getHyperlinkBase()) . '" />' . PHP_EOL;
419
        }
420
421 543
        $html .= $includeStyles ? $this->generateStyles(true) : $this->generatePageDeclarations(true);
422
423 543
        $html .= '  </head>' . PHP_EOL;
424 543
        $html .= '' . PHP_EOL;
425 543
        $html .= self::BODY_LINE;
426
427 543
        return $html;
428
    }
429
430
    /** @return Worksheet[] */
431 541
    private function generateSheetPrep(): array
432
    {
433
        // Fetch sheets
434 541
        if ($this->sheetIndex === null) {
435 14
            $sheets = $this->spreadsheet->getAllSheets();
436
        } else {
437 534
            $sheets = [$this->spreadsheet->getSheet($this->sheetIndex)];
438
        }
439
440 541
        return $sheets;
441
    }
442
443
    /** @return array{int, int, int} */
444 541
    private function generateSheetStarts(Worksheet $sheet, int $rowMin): array
445
    {
446
        // calculate start of <tbody>, <thead>
447 541
        $tbodyStart = $rowMin;
448 541
        $theadStart = $theadEnd = 0; // default: no <thead>    no </thead>
449 541
        if ($sheet->getPageSetup()->isRowsToRepeatAtTopSet()) {
450 2
            $rowsToRepeatAtTop = $sheet->getPageSetup()->getRowsToRepeatAtTop();
451
452
            // we can only support repeating rows that start at top row
453 2
            if ($rowsToRepeatAtTop[0] == 1) {
454 2
                $theadStart = $rowsToRepeatAtTop[0];
455 2
                $theadEnd = $rowsToRepeatAtTop[1];
456 2
                $tbodyStart = $rowsToRepeatAtTop[1] + 1;
457
            }
458
        }
459
460 541
        return [$theadStart, $theadEnd, $tbodyStart];
461
    }
462
463
    /** @return array{string, string, string} */
464 541
    private function generateSheetTags(int $row, int $theadStart, int $theadEnd, int $tbodyStart): array
465
    {
466
        // <thead> ?
467 541
        $startTag = ($row == $theadStart) ? ('        <thead>' . PHP_EOL) : '';
468 541
        if (!$startTag) {
469 541
            $startTag = ($row == $tbodyStart) ? ('        <tbody>' . PHP_EOL) : '';
470
        }
471 541
        $endTag = ($row == $theadEnd) ? ('        </thead>' . PHP_EOL) : '';
472 541
        $cellType = ($row >= $tbodyStart) ? 'td' : 'th';
473
474 541
        return [$cellType, $startTag, $endTag];
475
    }
476
477
    /**
478
     * Generate sheet data.
479
     */
480 541
    public function generateSheetData(): string
481
    {
482
        // Ensure that Spans have been calculated?
483 541
        $this->calculateSpans();
484 541
        $sheets = $this->generateSheetPrep();
485
486
        // Construct HTML
487 541
        $html = '';
488
489
        // Loop all sheets
490 541
        $sheetId = 0;
491
492 541
        $activeSheet = $this->spreadsheet->getActiveSheetIndex();
493
494 541
        foreach ($sheets as $sheet) {
495
            // save active cells
496 541
            $selectedCells = $sheet->getSelectedCells();
497
            // Write table header
498 541
            $html .= $this->generateTableHeader($sheet);
499 541
            $this->sheetCharts = [];
500 541
            $this->sheetDrawings = [];
501 541
            $condStylesCollection = $sheet->getConditionalStylesCollection();
502 541
            foreach ($condStylesCollection as $condStyles) {
503 11
                foreach ($condStyles as $key => $cs) {
504 11
                    if ($cs->getConditionType() === Conditional::CONDITION_COLORSCALE) {
505 2
                        $cs->getColorScale()?->setScaleArray();
506
                    }
507
                }
508
            }
509
            // Get worksheet dimension
510 541
            [$min, $max] = explode(':', $sheet->calculateWorksheetDataDimension());
511 541
            [$minCol, $minRow, $minColString] = Coordinate::indexesFromString($min);
512 541
            [$maxCol, $maxRow] = Coordinate::indexesFromString($max);
513 541
            $this->extendRowsAndColumns($sheet, $maxCol, $maxRow);
514
515 541
            [$theadStart, $theadEnd, $tbodyStart] = $this->generateSheetStarts($sheet, $minRow);
516
            // Loop through cells
517 541
            $row = $minRow - 1;
518 541
            while ($row++ < $maxRow) {
519 541
                [$cellType, $startTag, $endTag] = $this->generateSheetTags($row, $theadStart, $theadEnd, $tbodyStart);
520 541
                $html .= StringHelper::convertToString($startTag);
521
522
                // Write row if there are HTML table cells in it
523 541
                if ($this->shouldGenerateRow($sheet, $row) && !isset($this->isSpannedRow[$sheet->getParentOrThrow()->getIndex($sheet)][$row])) {
524
                    // Start a new rowData
525 541
                    $rowData = [];
526
                    // Loop through columns
527 541
                    $column = $minCol;
528 541
                    $colStr = $minColString;
529 541
                    while ($column <= $maxCol) {
530
                        // Cell exists?
531 541
                        $cellAddress = Coordinate::stringFromColumnIndex($column) . $row;
532 541
                        if ($this->shouldGenerateColumn($sheet, $colStr)) {
533 541
                            $rowData[$column] = ($sheet->getCellCollection()->has($cellAddress)) ? $cellAddress : '';
534
                        }
535 541
                        ++$column;
536
                        /** @var string $colStr */
537 541
                        ++$colStr;
538
                    }
539 541
                    $html .= $this->generateRow($sheet, $rowData, $row - 1, $cellType);
540
                }
541
542 541
                $html .= StringHelper::convertToString($endTag);
543
            }
544
            // Write table footer
545 541
            $html .= $this->generateTableFooter();
546
            // Writing PDF?
547 541
            if ($this->isPdf && $this->useInlineCss) {
548 7
                if ($this->sheetIndex === null && $sheetId + 1 < $this->spreadsheet->getSheetCount()) {
549 1
                    $html .= '<div style="page-break-before:always" ></div>';
550
                }
551
            }
552
553
            // Next sheet
554 541
            ++$sheetId;
555 541
            $sheet->setSelectedCells($selectedCells);
556
        }
557 541
        $this->spreadsheet->setActiveSheetIndex($activeSheet);
558
559 541
        return $html;
560
    }
561
562
    /**
563
     * Generate sheet tabs.
564
     */
565 510
    public function generateNavigation(): string
566
    {
567
        // Fetch sheets
568 510
        $sheets = [];
569 510
        if ($this->sheetIndex === null) {
570 8
            $sheets = $this->spreadsheet->getAllSheets();
571
        } else {
572 508
            $sheets[] = $this->spreadsheet->getSheet($this->sheetIndex);
573
        }
574
575
        // Construct HTML
576 510
        $html = '';
577
578
        // Only if there are more than 1 sheets
579 510
        if (count($sheets) > 1) {
580
            // Loop all sheets
581 8
            $sheetId = 0;
582
583 8
            $html .= '<ul class="navigation">' . PHP_EOL;
584
585 8
            foreach ($sheets as $sheet) {
586 8
                $html .= '  <li class="sheet' . $sheetId . '"><a href="#sheet' . $sheetId . '">' . htmlspecialchars($sheet->getTitle()) . '</a></li>' . PHP_EOL;
587 8
                ++$sheetId;
588
            }
589
590 8
            $html .= '</ul>' . PHP_EOL;
591
        }
592
593 510
        return $html;
594
    }
595
596 541
    private function extendRowsAndColumns(Worksheet $worksheet, int &$colMax, int &$rowMax): void
597
    {
598 541
        if ($this->includeCharts) {
599 4
            foreach ($worksheet->getChartCollection() as $chart) {
600 4
                $chartCoordinates = $chart->getTopLeftPosition();
601 4
                $this->sheetCharts[$chartCoordinates['cell']] = $chart;
602 4
                $chartTL = Coordinate::indexesFromString($chartCoordinates['cell']);
603 4
                if ($chartTL[1] > $rowMax) {
604 1
                    $rowMax = $chartTL[1];
605
                }
606 4
                if ($chartTL[0] > $colMax) {
607 2
                    $colMax = $chartTL[0];
608
                }
609
            }
610
        }
611 541
        foreach ($worksheet->getDrawingCollection() as $drawing) {
612 27
            if ($drawing instanceof Drawing && $drawing->getPath() === '') {
613 2
                continue;
614
            }
615 26
            $imageTL = Coordinate::indexesFromString($drawing->getCoordinates());
616 26
            $this->sheetDrawings[$drawing->getCoordinates()] = $drawing;
617 26
            if ($imageTL[1] > $rowMax) {
618
                $rowMax = $imageTL[1];
619
            }
620 26
            if ($imageTL[0] > $colMax) {
621
                $colMax = $imageTL[0];
622
            }
623
        }
624
    }
625
626
    /**
627
     * Convert Windows file name to file protocol URL.
628
     *
629
     * @param string $filename file name on local system
630
     */
631 20
    public static function winFileToUrl(string $filename, bool $mpdf = false): string
632
    {
633
        // Windows filename
634 20
        if (substr($filename, 1, 2) === ':\\') {
635 1
            $protocol = $mpdf ? '' : 'file:///';
636 1
            $filename = $protocol . str_replace('\\', '/', $filename);
637
        }
638
639 20
        return $filename;
640
    }
641
642
    /**
643
     * Generate image tag in cell.
644
     *
645
     * @param string $coordinates Cell coordinates
646
     */
647 541
    private function writeImageInCell(string $coordinates): string
648
    {
649
        // Construct HTML
650 541
        $html = '';
651
652
        // Write images
653 541
        $drawing = $this->sheetDrawings[$coordinates] ?? null;
654 541
        if ($drawing !== null) {
655 26
            $opacity = '';
656 26
            $opacityValue = $drawing->getOpacity();
657 26
            if ($opacityValue !== null) {
658 3
                $opacityValue = $opacityValue / 100000;
659 3
                if ($opacityValue >= 0.0 && $opacityValue <= 1.0) {
660 3
                    $opacity = "opacity:$opacityValue; ";
661
                }
662
            }
663 26
            $filedesc = $drawing->getDescription();
664 26
            $filedesc = $filedesc ? htmlspecialchars($filedesc, ENT_QUOTES) : 'Embedded image';
665 26
            if ($drawing instanceof Drawing && $drawing->getPath() !== '') {
666 19
                $filename = $drawing->getPath();
667
668
                // Strip off eventual '.'
669 19
                $filename = Preg::replace('/^[.]/', '', $filename);
670
671
                // Prepend images root
672 19
                $filename = $this->getImagesRoot() . $filename;
673
674
                // Strip off eventual '.' if followed by non-/
675 19
                $filename = Preg::replace('@^[.]([^/])@', '$1', $filename);
676
677
                // Convert UTF8 data to PCDATA
678 19
                $filename = htmlspecialchars($filename, Settings::htmlEntityFlags());
679
680 19
                $html .= PHP_EOL;
681 19
                $imageData = self::winFileToUrl($filename, $this instanceof Pdf\Mpdf);
682
683 19
                if ($this->embedImages || str_starts_with($imageData, 'zip://')) {
684 11
                    $imageData = 'data:,';
685 11
                    $picture = @file_get_contents($filename);
686 11
                    if ($picture !== false) {
687 11
                        $mimeContentType = (string) @mime_content_type($filename);
688 11
                        if (str_starts_with($mimeContentType, 'image/')) {
689
                            // base64 encode the binary data
690 11
                            $base64 = base64_encode($picture);
691 11
                            $imageData = 'data:' . $mimeContentType . ';base64,' . $base64;
692
                        }
693
                    }
694
                }
695
696 19
                $html .= '<img style="' . $opacity . 'position: absolute; z-index: 1; left: '
697 19
                    . $drawing->getOffsetX() . 'px; top: ' . $drawing->getOffsetY() . 'px; width: '
698 19
                    . $drawing->getWidth() . 'px; height: ' . $drawing->getHeight() . 'px;" src="'
699 19
                    . $imageData . '" alt="' . $filedesc . '" />';
700 7
            } elseif ($drawing instanceof MemoryDrawing) {
701 7
                $imageResource = $drawing->getImageResource();
702 7
                if ($imageResource) {
703 7
                    ob_start(); //  Let's start output buffering.
704 7
                    imagepng($imageResource); //  This will normally output the image, but because of ob_start(), it won't.
705 7
                    $contents = (string) ob_get_contents(); //  Instead, output above is saved to $contents
706 7
                    ob_end_clean(); //  End the output buffer.
707
708 7
                    $dataUri = 'data:image/png;base64,' . base64_encode($contents);
709
710
                    //  Because of the nature of tables, width is more important than height.
711
                    //  max-width: 100% ensures that image doesnt overflow containing cell
712
                    //    However, PR #3535 broke test
713
                    //    25_In_memory_image, apparently because
714
                    //    of the use of max-with. In addition,
715
                    //    non-memory-drawings don't use max-width.
716
                    //    Its use here is suspect and is being eliminated.
717
                    //  width: X sets width of supplied image.
718
                    //  As a result, images bigger than cell will be contained and images smaller will not get stretched
719 7
                    $html .= '<img alt="' . $filedesc . '" src="' . $dataUri . '" style="' . $opacity . 'width:' . $drawing->getWidth() . 'px;left: '
720 7
                        . $drawing->getOffsetX() . 'px; top: ' . $drawing->getOffsetY() . 'px;position: absolute; z-index: 1;" />';
721
                }
722
            }
723
        }
724
725 541
        return $html;
726
    }
727
728
    /**
729
     * Generate chart tag in cell.
730
     * This code should be exercised by sample:
731
     * Chart/32_Chart_read_write_PDF.php.
732
     */
733 4
    private function writeChartInCell(Worksheet $worksheet, string $coordinates): string
734
    {
735
        // Construct HTML
736 4
        $html = '';
737
738
        // Write charts
739 4
        $chart = $this->sheetCharts[$coordinates] ?? null;
740 4
        if ($chart !== null) {
741 4
            $chartCoordinates = $chart->getTopLeftPosition();
742 4
            $chartFileName = File::sysGetTempDir() . '/' . uniqid('', true) . '.png';
743 4
            $renderedWidth = $chart->getRenderedWidth();
744 4
            $renderedHeight = $chart->getRenderedHeight();
745 4
            if ($renderedWidth === null || $renderedHeight === null) {
746 4
                $this->adjustRendererPositions($chart, $worksheet);
747
            }
748 4
            $title = $chart->getTitle();
749 4
            $caption = null;
750 4
            $filedesc = '';
751 4
            if ($title !== null) {
752 4
                $calculatedTitle = $title->getCalculatedTitle($worksheet->getParent());
753 4
                if ($calculatedTitle !== null) {
754 2
                    $caption = $title->getCaption();
755 2
                    $title->setCaption($calculatedTitle);
756
                }
757 4
                $filedesc = $title->getCaptionText($worksheet->getParent());
758
            }
759 4
            $renderSuccessful = $chart->render($chartFileName);
760 4
            $chart->setRenderedWidth($renderedWidth);
761 4
            $chart->setRenderedHeight($renderedHeight);
762 4
            if (isset($title, $caption)) {
763 2
                $title->setCaption($caption);
764
            }
765 4
            if (!$renderSuccessful) {
766
                return '';
767
            }
768
769 4
            $html .= PHP_EOL;
770 4
            $imageDetails = getimagesize($chartFileName) ?: ['', '', 'mime' => ''];
771
772 4
            $filedesc = $filedesc ? htmlspecialchars($filedesc, ENT_QUOTES) : 'Embedded chart';
773 4
            $picture = file_get_contents($chartFileName);
774 4
            unlink($chartFileName);
775 4
            if ($picture !== false) {
776 4
                $base64 = base64_encode($picture);
777 4
                $imageData = 'data:' . $imageDetails['mime'] . ';base64,' . $base64;
778
779 4
                $html .= '<img style="position: absolute; z-index: 1; left: ' . $chartCoordinates['xOffset'] . 'px; top: ' . $chartCoordinates['yOffset'] . 'px; width: ' . $imageDetails[0] . 'px; height: ' . $imageDetails[1] . 'px;" src="' . $imageData . '" alt="' . $filedesc . '" />' . PHP_EOL;
780
            }
781
        }
782
783
        // Return
784 4
        return $html;
785
    }
786
787 4
    private function adjustRendererPositions(Chart $chart, Worksheet $sheet): void
788
    {
789 4
        $topLeft = $chart->getTopLeftPosition();
790 4
        $bottomRight = $chart->getBottomRightPosition();
791 4
        $tlCell = $topLeft['cell'];
792
        /** @var string */
793 4
        $brCell = $bottomRight['cell'];
794 4
        if ($tlCell !== '' && $brCell !== '') {
795 4
            $tlCoordinate = Coordinate::indexesFromString($tlCell);
796 4
            $brCoordinate = Coordinate::indexesFromString($brCell);
797 4
            $totalHeight = 0.0;
798 4
            $totalWidth = 0.0;
799 4
            $defaultRowHeight = $sheet->getDefaultRowDimension()->getRowHeight();
800 4
            $defaultRowHeight = SharedDrawing::pointsToPixels(($defaultRowHeight >= 0) ? $defaultRowHeight : SharedFont::getDefaultRowHeightByFont($this->defaultFont));
801 4
            if ($tlCoordinate[1] <= $brCoordinate[1] && $tlCoordinate[0] <= $brCoordinate[0]) {
802 4
                for ($row = $tlCoordinate[1]; $row <= $brCoordinate[1]; ++$row) {
803 4
                    $height = $sheet->getRowDimension($row)->getRowHeight('pt');
804 4
                    $totalHeight += ($height >= 0) ? $height : $defaultRowHeight;
805
                }
806 4
                $rightEdge = $brCoordinate[2];
807 4
                ++$rightEdge;
808 4
                for ($column = $tlCoordinate[2]; $column !== $rightEdge;) {
809 4
                    $width = $sheet->getColumnDimension($column)->getWidth();
810 4
                    $width = ($width < 0) ? self::DEFAULT_CELL_WIDTH_PIXELS : SharedDrawing::cellDimensionToPixels($sheet->getColumnDimension($column)->getWidth(), $this->defaultFont);
811 4
                    $totalWidth += $width;
812
                    /** @var string $column */
813 4
                    ++$column;
814
                }
815 4
                $chart->setRenderedWidth($totalWidth);
816 4
                $chart->setRenderedHeight($totalHeight);
817
            }
818
        }
819
    }
820
821
    /**
822
     * Generate CSS styles.
823
     *
824
     * @param bool $generateSurroundingHTML Generate surrounding HTML tags? (&lt;style&gt; and &lt;/style&gt;)
825
     */
826 535
    public function generateStyles(bool $generateSurroundingHTML = true): string
827
    {
828
        // Build CSS
829 535
        $css = $this->buildCSS($generateSurroundingHTML);
830
831
        // Construct HTML
832 535
        $html = '';
833
834
        // Start styles
835 535
        if ($generateSurroundingHTML) {
836 535
            $html .= '    <style type="text/css">' . PHP_EOL;
837 535
            $html .= (array_key_exists('html', $css)) ? ('      html { ' . $this->assembleCSS($css['html']) . ' }' . PHP_EOL) : '';
838
        }
839
840
        // Write all other styles
841 535
        foreach ($css as $styleName => $styleDefinition) {
842 535
            if ($styleName != 'html') {
843 535
                $html .= '      ' . $styleName . ' { ' . $this->assembleCSS($styleDefinition) . ' }' . PHP_EOL;
844
            }
845
        }
846 535
        $html .= $this->generatePageDeclarations(false);
847
848
        // End styles
849 535
        if ($generateSurroundingHTML) {
850 535
            $html .= '    </style>' . PHP_EOL;
851
        }
852
853
        // Return
854 535
        return $html;
855
    }
856
857
    /** @param string[][] $css */
858 543
    private function buildCssRowHeights(Worksheet $sheet, array &$css, int $sheetIndex): void
859
    {
860
        // Calculate row heights
861 543
        foreach ($sheet->getRowDimensions() as $rowDimension) {
862 32
            $row = $rowDimension->getRowIndex() - 1;
863
864
            // table.sheetN tr.rowYYYYYY { }
865 32
            $css['table.sheet' . $sheetIndex . ' tr.row' . $row] = [];
866
867 32
            if ($rowDimension->getRowHeight() != -1) {
868 22
                $pt_height = $rowDimension->getRowHeight();
869 22
                $css['table.sheet' . $sheetIndex . ' tr.row' . $row]['height'] = $pt_height . 'pt';
870
            }
871 32
            if ($rowDimension->getVisible() === false) {
872 8
                $css['table.sheet' . $sheetIndex . ' tr.row' . $row]['display'] = 'none';
873 8
                $css['table.sheet' . $sheetIndex . ' tr.row' . $row]['visibility'] = 'hidden';
874
            }
875
        }
876
    }
877
878
    /** @param string[][] $css */
879 543
    private function buildCssPerSheet(Worksheet $sheet, array &$css): void
880
    {
881
        // Calculate hash code
882 543
        $sheetIndex = $sheet->getParentOrThrow()->getIndex($sheet);
883 543
        $setup = $sheet->getPageSetup();
884 543
        if ($setup->getFitToPage() && $setup->getFitToHeight() === 1) {
885 11
            $css["table.sheet$sheetIndex"]['page-break-inside'] = 'avoid';
886 11
            $css["table.sheet$sheetIndex"]['break-inside'] = 'avoid';
887
        }
888 543
        $picture = $sheet->getBackgroundImage();
889 543
        if ($picture !== '') {
890 1
            $base64 = base64_encode($picture);
891 1
            $css["table.sheet$sheetIndex"]['background-image'] = 'url(data:' . $sheet->getBackgroundMime() . ';base64,' . $base64 . ')';
892
        }
893
894
        // Build styles
895
        // Calculate column widths
896 543
        $sheet->calculateColumnWidths();
897
898
        // col elements, initialize
899 543
        $highestColumnIndex = Coordinate::columnIndexFromString($sheet->getHighestColumn()) - 1;
900 543
        $column = -1;
901 543
        $colStr = 'A';
902 543
        while ($column++ < $highestColumnIndex) {
903 543
            $this->columnWidths[$sheetIndex][$column] = self::DEFAULT_CELL_WIDTH_POINTS; // approximation
904 543
            if ($this->shouldGenerateColumn($sheet, $colStr)) {
905 543
                $css['table.sheet' . $sheetIndex . ' col.col' . $column]['width'] = self::DEFAULT_CELL_WIDTH_POINTS . 'pt';
906
            }
907 543
            ++$colStr;
908
        }
909
910
        // col elements, loop through columnDimensions and set width
911 543
        foreach ($sheet->getColumnDimensions() as $columnDimension) {
912 39
            $column = Coordinate::columnIndexFromString($columnDimension->getColumnIndex()) - 1;
913 39
            $width = SharedDrawing::cellDimensionToPixels($columnDimension->getWidth(), $this->defaultFont);
914 39
            $width = SharedDrawing::pixelsToPoints($width);
915 39
            if ($columnDimension->getVisible() === false) {
916 10
                $css['table.sheet' . $sheetIndex . ' .column' . $column]['display'] = 'none';
917
                // This would be better but Firefox has an 11-year-old bug.
918
                // https://bugzilla.mozilla.org/show_bug.cgi?id=819045
919
                //$css['table.sheet' . $sheetIndex . ' col.col' . $column]['visibility'] = 'collapse';
920
            }
921 39
            if ($width >= 0) {
922 28
                $this->columnWidths[$sheetIndex][$column] = $width;
923 28
                $css['table.sheet' . $sheetIndex . ' col.col' . $column]['width'] = $width . 'pt';
924
            }
925
        }
926
927
        // Default row height
928 543
        $rowDimension = $sheet->getDefaultRowDimension();
929
930
        // table.sheetN tr { }
931 543
        $css['table.sheet' . $sheetIndex . ' tr'] = [];
932
933 543
        if ($rowDimension->getRowHeight() == -1) {
934 525
            $pt_height = SharedFont::getDefaultRowHeightByFont($this->spreadsheet->getDefaultStyle()->getFont());
935
        } else {
936 18
            $pt_height = $rowDimension->getRowHeight();
937
        }
938 543
        $css['table.sheet' . $sheetIndex . ' tr']['height'] = $pt_height . 'pt';
939 543
        if ($rowDimension->getVisible() === false) {
940 1
            $css['table.sheet' . $sheetIndex . ' tr']['display'] = 'none';
941 1
            $css['table.sheet' . $sheetIndex . ' tr']['visibility'] = 'hidden';
942
        }
943
944 543
        $this->buildCssRowHeights($sheet, $css, $sheetIndex);
945
    }
946
947
    /**
948
     * Build CSS styles.
949
     *
950
     * @param bool $generateSurroundingHTML Generate surrounding HTML style? (html { })
951
     *
952
     * @return string[][]
953
     */
954 543
    public function buildCSS(bool $generateSurroundingHTML = true): array
955
    {
956
        // Cached?
957 543
        if ($this->cssStyles !== null) {
958 533
            return $this->cssStyles;
959
        }
960
961
        // Ensure that spans have been calculated
962 543
        $this->calculateSpans();
963
964
        // Construct CSS
965
        /** @var string[][] */
966 543
        $css = [];
967
968
        // Start styles
969 543
        if ($generateSurroundingHTML) {
970
            // html { }
971 534
            $css['html']['font-family'] = 'Calibri, Arial, Helvetica, sans-serif';
972 534
            $css['html']['font-size'] = '11pt';
973 534
            $css['html']['background-color'] = 'white';
974
        }
975
976
        // CSS for comments as found in LibreOffice
977 543
        $css['a.comment-indicator:hover + div.comment'] = [
978 543
            'background' => '#ffd',
979 543
            'position' => 'absolute',
980 543
            'display' => 'block',
981 543
            'border' => '1px solid black',
982 543
            'padding' => '0.5em',
983 543
        ];
984
985 543
        $css['a.comment-indicator'] = [
986 543
            'background' => 'red',
987 543
            'display' => 'inline-block',
988 543
            'border' => '1px solid black',
989 543
            'width' => '0.5em',
990 543
            'height' => '0.5em',
991 543
        ];
992
993 543
        $css['div.comment']['display'] = 'none';
994
995
        // table { }
996 543
        $css['table']['border-collapse'] = 'collapse';
997
998
        // .b {}
999 543
        $css['.b']['text-align'] = 'center'; // BOOL
1000
1001
        // .e {}
1002 543
        $css['.e']['text-align'] = 'center'; // ERROR
1003
1004
        // .f {}
1005 543
        $css['.f']['text-align'] = 'right'; // FORMULA
1006
1007
        // .inlineStr {}
1008 543
        $css['.inlineStr']['text-align'] = 'left'; // INLINE
1009
1010
        // .n {}
1011 543
        $css['.n']['text-align'] = 'right'; // NUMERIC
1012
1013
        // .s {}
1014 543
        $css['.s']['text-align'] = 'left'; // STRING
1015
1016
        // Calculate cell style hashes
1017 543
        foreach ($this->spreadsheet->getCellXfCollection() as $index => $style) {
1018 543
            $css['td.style' . $index . ', th.style' . $index] = $this->createCSSStyle($style);
1019
            //$css['th.style' . $index] = $this->createCSSStyle($style);
1020
        }
1021
1022
        // Fetch sheets
1023 543
        $sheets = [];
1024 543
        if ($this->sheetIndex === null) {
1025 15
            $sheets = $this->spreadsheet->getAllSheets();
1026
        } else {
1027 535
            $sheets[] = $this->spreadsheet->getSheet($this->sheetIndex);
1028
        }
1029
1030
        // Build styles per sheet
1031 543
        foreach ($sheets as $sheet) {
1032 543
            $this->buildCssPerSheet($sheet, $css);
1033
        }
1034
1035
        // Cache
1036 543
        if ($this->cssStyles === null) {
1037 543
            $this->cssStyles = $css;
1038
        }
1039
1040
        // Return
1041 543
        return $css;
1042
    }
1043
1044
    /**
1045
     * Create CSS style.
1046
     *
1047
     * @return string[]
1048
     */
1049 543
    private function createCSSStyle(Style $style): array
1050
    {
1051
        // Create CSS
1052 543
        return array_merge(
1053 543
            $this->createCSSStyleAlignment($style->getAlignment()),
1054 543
            $this->createCSSStyleBorders($style->getBorders()),
1055 543
            $this->createCSSStyleFont($style->getFont()),
1056 543
            $this->createCSSStyleFill($style->getFill())
1057 543
        );
1058
    }
1059
1060
    /**
1061
     * Create CSS style.
1062
     *
1063
     * @return string[]
1064
     */
1065 543
    private function createCSSStyleAlignment(Alignment $alignment): array
1066
    {
1067
        // Construct CSS
1068 543
        $css = [];
1069
1070
        // Create CSS
1071 543
        $verticalAlign = $this->mapVAlign($alignment->getVertical() ?? '');
1072 543
        if ($verticalAlign) {
1073 543
            $css['vertical-align'] = $verticalAlign;
1074
        }
1075 543
        $textAlign = $this->mapHAlign($alignment->getHorizontal() ?? '');
1076 543
        if ($textAlign) {
1077 18
            $css['text-align'] = $textAlign;
1078 18
            if (in_array($textAlign, ['left', 'right'])) {
1079 11
                $css['padding-' . $textAlign] = (string) ((int) $alignment->getIndent() * 9) . 'px';
1080
            }
1081
        }
1082 543
        $rotation = $alignment->getTextRotation();
1083 543
        if ($rotation !== 0 && $rotation !== Alignment::TEXTROTATION_STACK_PHPSPREADSHEET) {
1084 5
            if ($this instanceof Pdf\Mpdf) {
1085 1
                $css['text-rotate'] = "$rotation";
1086
            } else {
1087 4
                $css['transform'] = "rotate({$rotation}deg)";
1088
            }
1089
        }
1090
1091 543
        return $css;
1092
    }
1093
1094
    /**
1095
     * Create CSS style.
1096
     *
1097
     * @return string[]
1098
     */
1099 543
    private function createCSSStyleFont(Font $font): array
1100
    {
1101
        // Construct CSS
1102 543
        $css = [];
1103
1104
        // Create CSS
1105 543
        if ($font->getBold()) {
1106 20
            $css['font-weight'] = 'bold';
1107
        }
1108 543
        if ($font->getUnderline() != Font::UNDERLINE_NONE && $font->getStrikethrough()) {
1109 1
            $css['text-decoration'] = 'underline line-through';
1110 543
        } elseif ($font->getUnderline() != Font::UNDERLINE_NONE) {
1111 12
            $css['text-decoration'] = 'underline';
1112 543
        } elseif ($font->getStrikethrough()) {
1113 1
            $css['text-decoration'] = 'line-through';
1114
        }
1115 543
        if ($font->getItalic()) {
1116 10
            $css['font-style'] = 'italic';
1117
        }
1118
1119 543
        $css['color'] = '#' . $font->getColor()->getRGB();
1120 543
        $css['font-family'] = '\'' . htmlspecialchars((string) $font->getName(), ENT_QUOTES) . '\'';
1121 543
        $css['font-size'] = $font->getSize() . 'pt';
1122
1123 543
        return $css;
1124
    }
1125
1126
    /**
1127
     * Create CSS style.
1128
     *
1129
     * @param Borders $borders Borders
1130
     *
1131
     * @return string[]
1132
     */
1133 543
    private function createCSSStyleBorders(Borders $borders): array
1134
    {
1135
        // Construct CSS
1136 543
        $css = [];
1137
1138
        // Create CSS
1139 543
        if (!($this instanceof Pdf\Mpdf)) {
1140 526
            $css['border-bottom'] = $this->createCSSStyleBorder($borders->getBottom());
1141 526
            $css['border-top'] = $this->createCSSStyleBorder($borders->getTop());
1142 526
            $css['border-left'] = $this->createCSSStyleBorder($borders->getLeft());
1143 526
            $css['border-right'] = $this->createCSSStyleBorder($borders->getRight());
1144
        } else {
1145
            // Mpdf doesn't process !important, so omit unimportant border none
1146 23
            if ($borders->getBottom()->getBorderStyle() !== Border::BORDER_NONE) {
1147 6
                $css['border-bottom'] = $this->createCSSStyleBorder($borders->getBottom());
1148
            }
1149 23
            if ($borders->getTop()->getBorderStyle() !== Border::BORDER_NONE) {
1150 6
                $css['border-top'] = $this->createCSSStyleBorder($borders->getTop());
1151
            }
1152 23
            if ($borders->getLeft()->getBorderStyle() !== Border::BORDER_NONE) {
1153 6
                $css['border-left'] = $this->createCSSStyleBorder($borders->getLeft());
1154
            }
1155 23
            if ($borders->getRight()->getBorderStyle() !== Border::BORDER_NONE) {
1156 6
                $css['border-right'] = $this->createCSSStyleBorder($borders->getRight());
1157
            }
1158
        }
1159
1160 543
        return $css;
1161
    }
1162
1163
    /**
1164
     * Create CSS style.
1165
     *
1166
     * @param Border $border Border
1167
     */
1168 531
    private function createCSSStyleBorder(Border $border): string
1169
    {
1170
        //    Create CSS - add !important to non-none border styles for merged cells
1171 531
        $borderStyle = $this->mapBorderStyle($border->getBorderStyle());
1172
1173 531
        return $borderStyle . ' #' . $border->getColor()->getRGB() . (($borderStyle === self::BORDER_NONE) ? '' : ' !important');
1174
    }
1175
1176
    /**
1177
     * Create CSS style (Fill).
1178
     *
1179
     * @param Fill $fill Fill
1180
     *
1181
     * @return string[]
1182
     */
1183 543
    private function createCSSStyleFill(Fill $fill): array
1184
    {
1185
        // Construct HTML
1186 543
        $css = [];
1187
1188
        // Create CSS
1189 543
        if ($fill->getFillType() !== Fill::FILL_NONE) {
1190
            if (
1191 22
                (in_array($fill->getFillType(), ['', Fill::FILL_SOLID], true) || !$fill->getEndColor()->getRGB())
1192 22
                && $fill->getStartColor()->getRGB()
1193
            ) {
1194 22
                $value = '#' . $fill->getStartColor()->getRGB();
1195 22
                $css['background-color'] = $value;
1196 9
            } elseif ($fill->getEndColor()->getRGB()) {
1197 9
                $value = '#' . $fill->getEndColor()->getRGB();
1198 9
                $css['background-color'] = $value;
1199
            }
1200
        }
1201
1202 543
        return $css;
1203
    }
1204
1205
    /**
1206
     * Generate HTML footer.
1207
     */
1208 541
    public function generateHTMLFooter(): string
1209
    {
1210
        // Construct HTML
1211 541
        $html = '';
1212 541
        $html .= '  </body>' . PHP_EOL;
1213 541
        $html .= '</html>' . PHP_EOL;
1214
1215 541
        return $html;
1216
    }
1217
1218 14
    private function generateTableTagInline(Worksheet $worksheet, string $id): string
1219
    {
1220 14
        $style = isset($this->cssStyles['table'])
1221 14
            ? $this->assembleCSS($this->cssStyles['table']) : '';
1222
1223 14
        $prntgrid = $worksheet->getPrintGridlines();
1224 14
        $viewgrid = $this->isPdf ? $prntgrid : $worksheet->getShowGridlines();
1225 14
        if ($viewgrid && $prntgrid) {
1226 1
            $html = "    <table border='1' cellpadding='1' $id cellspacing='1' style='$style' class='gridlines gridlinesp'>" . PHP_EOL;
1227 14
        } elseif ($viewgrid) {
1228 7
            $html = "    <table border='0' cellpadding='0' $id cellspacing='0' style='$style' class='gridlines'>" . PHP_EOL;
1229 8
        } elseif ($prntgrid) {
1230 1
            $html = "    <table border='0' cellpadding='0' $id cellspacing='0' style='$style' class='gridlinesp'>" . PHP_EOL;
1231
        } else {
1232 8
            $html = "    <table border='0' cellpadding='1' $id cellspacing='0' style='$style'>" . PHP_EOL;
1233
        }
1234
1235 14
        return $html;
1236
    }
1237
1238 541
    private function generateTableTag(Worksheet $worksheet, string $id, string &$html, int $sheetIndex): void
1239
    {
1240 541
        if (!$this->useInlineCss) {
1241 533
            $gridlines = $worksheet->getShowGridlines() ? ' gridlines' : '';
1242 533
            $gridlinesp = $worksheet->getPrintGridlines() ? ' gridlinesp' : '';
1243 533
            $html .= "    <table border='0' cellpadding='0' cellspacing='0' $id class='sheet$sheetIndex$gridlines$gridlinesp'>" . PHP_EOL;
1244
        } else {
1245 14
            $html .= $this->generateTableTagInline($worksheet, $id);
1246
        }
1247
    }
1248
1249
    /**
1250
     * Generate table header.
1251
     *
1252
     * @param Worksheet $worksheet The worksheet for the table we are writing
1253
     * @param bool $showid whether or not to add id to table tag
1254
     */
1255 541
    private function generateTableHeader(Worksheet $worksheet, bool $showid = true): string
1256
    {
1257 541
        $sheetIndex = $worksheet->getParentOrThrow()->getIndex($worksheet);
1258
1259
        // Construct HTML
1260 541
        $html = '';
1261 541
        $id = $showid ? "id='sheet$sheetIndex'" : '';
1262 541
        if ($showid) {
1263 541
            $html .= "<div style='page: page$sheetIndex'>" . PHP_EOL;
1264
        } else {
1265 2
            $html .= "<div style='page: page$sheetIndex' class='scrpgbrk'>" . PHP_EOL;
1266
        }
1267
1268 541
        $this->generateTableTag($worksheet, $id, $html, $sheetIndex);
1269
1270
        // Write <col> elements
1271 541
        $highestColumnIndex = Coordinate::columnIndexFromString($worksheet->getHighestColumn()) - 1;
1272 541
        $i = -1;
1273 541
        while ($i++ < $highestColumnIndex) {
1274 541
            if (!$this->useInlineCss) {
1275 533
                $html .= '        <col class="col' . $i . '" />' . PHP_EOL;
1276
            } else {
1277 14
                $style = isset($this->cssStyles['table.sheet' . $sheetIndex . ' col.col' . $i])
1278 14
                    ? $this->assembleCSS($this->cssStyles['table.sheet' . $sheetIndex . ' col.col' . $i]) : '';
1279 14
                $html .= '        <col style="' . $style . '" />' . PHP_EOL;
1280
            }
1281
        }
1282
1283 541
        return $html;
1284
    }
1285
1286
    /**
1287
     * Generate table footer.
1288
     */
1289 541
    private function generateTableFooter(): string
1290
    {
1291 541
        return '    </tbody></table>' . PHP_EOL . '</div>' . PHP_EOL;
1292
    }
1293
1294
    /**
1295
     * Generate row start.
1296
     *
1297
     * @param int $sheetIndex Sheet index (0-based)
1298
     * @param int $row row number
1299
     */
1300 541
    private function generateRowStart(Worksheet $worksheet, int $sheetIndex, int $row): string
1301
    {
1302 541
        $html = '';
1303 541
        if (count($worksheet->getBreaks()) > 0) {
1304 2
            $breaks = $worksheet->getRowBreaks();
1305
1306
            // check if a break is needed before this row
1307 2
            if (isset($breaks['A' . $row])) {
1308
                // close table: </table>
1309 2
                $html .= $this->generateTableFooter();
1310 2
                if ($this->isPdf && $this->useInlineCss) {
1311 1
                    $html .= '<div style="page-break-before:always" />';
1312
                }
1313
1314
                // open table again: <table> + <col> etc.
1315 2
                $html .= $this->generateTableHeader($worksheet, false);
1316 2
                $html .= '<tbody>' . PHP_EOL;
1317
            }
1318
        }
1319
1320
        // Write row start
1321 541
        if (!$this->useInlineCss) {
1322 533
            $html .= '          <tr class="row' . $row . '">' . PHP_EOL;
1323
        } else {
1324 14
            $style = isset($this->cssStyles['table.sheet' . $sheetIndex . ' tr.row' . $row])
1325 14
                ? $this->assembleCSS($this->cssStyles['table.sheet' . $sheetIndex . ' tr.row' . $row]) : '';
1326
1327 14
            $html .= '          <tr style="' . $style . '">' . PHP_EOL;
1328
        }
1329
1330 541
        return $html;
1331
    }
1332
1333
    /** @return array{null|''|Cell, array{}|string, non-empty-string} */
1334 541
    private function generateRowCellCss(Worksheet $worksheet, string $cellAddress, int $row, int $columnNumber): array
1335
    {
1336 541
        $cell = ($cellAddress > '') ? $worksheet->getCellCollection()->get($cellAddress) : '';
1337 541
        $coordinate = Coordinate::stringFromColumnIndex($columnNumber + 1) . ($row + 1);
1338 541
        if (!$this->useInlineCss) {
1339 533
            $cssClass = 'column' . $columnNumber;
1340
        } else {
1341 14
            $cssClass = [];
1342
        }
1343
1344 541
        return [$cell, $cssClass, $coordinate];
1345
    }
1346
1347 31
    private function generateRowCellDataValueRich(RichText $richText): string
1348
    {
1349 31
        $cellData = '';
1350
        // Loop through rich text elements
1351 31
        $elements = $richText->getRichTextElements();
1352 31
        foreach ($elements as $element) {
1353
            // Rich text start?
1354 31
            if ($element instanceof Run) {
1355 15
                $cellEnd = '';
1356 15
                if ($element->getFont() !== null) {
1357 15
                    $cellData .= '<span style="' . $this->assembleCSS($this->createCSSStyleFont($element->getFont())) . '">';
1358
1359 15
                    if ($element->getFont()->getSuperscript()) {
1360 1
                        $cellData .= '<sup>';
1361 1
                        $cellEnd = '</sup>';
1362 15
                    } elseif ($element->getFont()->getSubscript()) {
1363 1
                        $cellData .= '<sub>';
1364 1
                        $cellEnd = '</sub>';
1365
                    }
1366
                } else {
1367
                    $cellData .= '<span>';
1368
                }
1369
1370
                // Convert UTF8 data to PCDATA
1371 15
                $cellText = $element->getText();
1372 15
                $cellData .= htmlspecialchars($cellText, Settings::htmlEntityFlags());
1373
1374 15
                $cellData .= $cellEnd;
1375
1376 15
                $cellData .= '</span>';
1377
            } else {
1378
                // Convert UTF8 data to PCDATA
1379 27
                $cellText = $element->getText();
1380 27
                $cellData .= htmlspecialchars($cellText, Settings::htmlEntityFlags());
1381
            }
1382
        }
1383
1384 31
        return nl2br($cellData);
1385
    }
1386
1387 539
    private function generateRowCellDataValue(Worksheet $worksheet, Cell $cell, string &$cellData): void
1388
    {
1389 539
        if ($cell->getValue() instanceof RichText) {
1390 11
            $cellData .= $this->generateRowCellDataValueRich($cell->getValue());
1391
        } else {
1392 539
            if ($this->preCalculateFormulas) {
1393
                try {
1394 538
                    $origData = $cell->getCalculatedValue();
1395
                } catch (CalculationException $exception) {
1396
                    $origData = '#ERROR'; // mark as error, rather than crash everything
1397
                }
1398 538
                if ($this->betterBoolean && is_bool($origData)) {
1399 4
                    $origData2 = $origData ? $this->getTrue : $this->getFalse;
1400
                } else {
1401 538
                    $origData2 = $cell->getCalculatedValueString();
1402
                }
1403
            } else {
1404 1
                $origData = $cell->getValue();
1405 1
                if ($this->betterBoolean && is_bool($origData)) {
1406
                    $origData2 = $origData ? $this->getTrue : $this->getFalse;
1407
                } else {
1408 1
                    $origData2 = $cell->getValueString();
1409
                }
1410
            }
1411 539
            $formatCode = $worksheet->getParentOrThrow()->getCellXfByIndex($cell->getXfIndex())->getNumberFormat()->getFormatCode();
1412
1413 539
            $cellData = NumberFormat::toFormattedString(
1414 539
                $origData2,
1415 539
                $formatCode ?? NumberFormat::FORMAT_GENERAL,
1416 539
                [$this, 'formatColor']
1417 539
            );
1418
1419 539
            if ($cellData === $origData) {
1420 114
                $cellData = htmlspecialchars($cellData, Settings::htmlEntityFlags());
1421
            }
1422 539
            if ($worksheet->getParentOrThrow()->getCellXfByIndex($cell->getXfIndex())->getFont()->getSuperscript()) {
1423 1
                $cellData = '<sup>' . $cellData . '</sup>';
1424 539
            } elseif ($worksheet->getParentOrThrow()->getCellXfByIndex($cell->getXfIndex())->getFont()->getSubscript()) {
1425 1
                $cellData = '<sub>' . $cellData . '</sub>';
1426
            }
1427
        }
1428
    }
1429
1430
    /** @param string|string[] $cssClass */
1431 541
    private function generateRowCellData(Worksheet $worksheet, null|Cell|string $cell, array|string &$cssClass): string
1432
    {
1433 541
        $cellData = '&nbsp;';
1434 541
        if ($cell instanceof Cell) {
1435 539
            $cellData = '';
1436
            // Don't know what this does, and no test cases.
1437
            //if ($cell->getParent() === null) {
1438
            //    $cell->attach($worksheet);
1439
            //}
1440
            // Value
1441 539
            $this->generateRowCellDataValue($worksheet, $cell, $cellData);
1442
1443
            // Converts the cell content so that spaces occuring at beginning of each new line are replaced by &nbsp;
1444
            // Example: "  Hello\n to the world" is converted to "&nbsp;&nbsp;Hello\n&nbsp;to the world"
1445 539
            $cellData = Preg::replace('/(?m)(?:^|\G) /', '&nbsp;', $cellData);
1446
1447
            // convert newline "\n" to '<br>'
1448 539
            $cellData = nl2br($cellData);
1449
1450
            // Extend CSS class?
1451 539
            $dataType = $cell->getDataType();
1452 539
            if ($this->betterBoolean && $this->preCalculateFormulas && $dataType === DataType::TYPE_FORMULA) {
1453 27
                $calculatedValue = $cell->getCalculatedValue();
1454 27
                if (is_bool($calculatedValue)) {
1455 4
                    $dataType = DataType::TYPE_BOOL;
1456 27
                } elseif (is_numeric($calculatedValue)) {
1457 20
                    $dataType = DataType::TYPE_NUMERIC;
1458 19
                } elseif (is_string($calculatedValue)) {
1459 18
                    $dataType = DataType::TYPE_STRING;
1460
                }
1461
            }
1462 539
            if (!$this->useInlineCss && is_string($cssClass)) {
1463 532
                $cssClass .= ' style' . $cell->getXfIndex();
1464 532
                $cssClass .= ' ' . $dataType;
1465 13
            } elseif (is_array($cssClass)) {
1466 13
                $index = $cell->getXfIndex();
1467 13
                $styleIndex = 'td.style' . $index . ', th.style' . $index;
1468 13
                if (isset($this->cssStyles[$styleIndex])) {
1469 13
                    $cssClass = array_merge($cssClass, $this->cssStyles[$styleIndex]);
1470
                }
1471
1472
                // General horizontal alignment: Actual horizontal alignment depends on dataType
1473 13
                $sharedStyle = $worksheet->getParentOrThrow()->getCellXfByIndex($cell->getXfIndex());
1474
                if (
1475 13
                    $sharedStyle->getAlignment()->getHorizontal() == Alignment::HORIZONTAL_GENERAL
1476 13
                    && isset($this->cssStyles['.' . $cell->getDataType()]['text-align'])
1477
                ) {
1478 13
                    $cssClass['text-align'] = $this->cssStyles['.' . $dataType]['text-align'];
1479
                }
1480
            }
1481
        } else {
1482
            // Use default borders for empty cell
1483 56
            if (is_string($cssClass)) {
1484 51
                $cssClass .= ' style0';
1485
            }
1486
        }
1487
1488 541
        return $cellData;
1489
    }
1490
1491 541
    private function generateRowIncludeCharts(Worksheet $worksheet, string $coordinate): string
1492
    {
1493 541
        return $this->includeCharts ? $this->writeChartInCell($worksheet, $coordinate) : '';
1494
    }
1495
1496 541
    private function generateRowSpans(string $html, int $rowSpan, int $colSpan): string
1497
    {
1498 541
        $html .= ($colSpan > 1) ? (' colspan="' . $colSpan . '"') : '';
1499 541
        $html .= ($rowSpan > 1) ? (' rowspan="' . $rowSpan . '"') : '';
1500
1501 541
        return $html;
1502
    }
1503
1504
    /**
1505
     * @param string|string[] $cssClass
1506
     * @param Conditional[] $condStyles
1507
     */
1508 541
    private function generateRowWriteCell(
1509
        string &$html,
1510
        Worksheet $worksheet,
1511
        string $coordinate,
1512
        string $cellType,
1513
        string $cellData,
1514
        int $colSpan,
1515
        int $rowSpan,
1516
        array|string $cssClass,
1517
        int $colNum,
1518
        int $sheetIndex,
1519
        int $row,
1520
        array $condStyles = []
1521
    ): void {
1522
        // Image?
1523 541
        $htmlx = $this->writeImageInCell($coordinate);
1524
        // Chart?
1525 541
        $htmlx .= $this->generateRowIncludeCharts($worksheet, $coordinate);
1526
        // Column start
1527 541
        $html .= '            <' . $cellType;
1528 541
        if ($this->betterBoolean) {
1529 540
            $dataType = $worksheet->getCell($coordinate)->getDataType();
1530 540
            if ($dataType === DataType::TYPE_BOOL) {
1531 3
                $html .= ' data-type="' . DataType::TYPE_BOOL . '"';
1532 540
            } elseif ($dataType === DataType::TYPE_FORMULA && $this->preCalculateFormulas && is_bool($worksheet->getCell($coordinate)->getCalculatedValue())) {
1533 4
                $html .= ' data-type="' . DataType::TYPE_BOOL . '"';
1534 540
            } elseif (is_numeric($cellData) && $worksheet->getCell($coordinate)->getDataType() === DataType::TYPE_STRING) {
1535 3
                $html .= ' data-type="' . DataType::TYPE_STRING . '"';
1536
            }
1537
        }
1538 541
        if (!$this->useInlineCss && !$this->isPdf && is_string($cssClass)) {
1539 508
            $html .= ' class="' . $cssClass . '"';
1540 508
            if ($htmlx) {
1541 23
                $html .= " style='position: relative;'";
1542
            }
1543
        } else {
1544
            //** Necessary redundant code for the sake of \PhpOffice\PhpSpreadsheet\Writer\Pdf **
1545
            // We must explicitly write the width of the <td> element because TCPDF
1546
            // does not recognize e.g. <col style="width:42pt">
1547 43
            if ($this->useInlineCss) {
1548 14
                $xcssClass = is_array($cssClass) ? $cssClass : [];
1549
            } else {
1550 30
                if (is_string($cssClass)) {
1551 30
                    $html .= ' class="' . $cssClass . '"';
1552
                }
1553 30
                $xcssClass = [];
1554
            }
1555 43
            $width = 0;
1556 43
            $i = $colNum - 1;
1557 43
            $e = $colNum + $colSpan - 1;
1558 43
            while ($i++ < $e) {
1559 43
                if (isset($this->columnWidths[$sheetIndex][$i])) {
1560 43
                    $width += $this->columnWidths[$sheetIndex][$i];
1561
                }
1562
            }
1563 43
            $xcssClass['width'] = (string) $width . 'pt';
1564
            // We must also explicitly write the height of the <td> element because TCPDF
1565
            // does not recognize e.g. <tr style="height:50pt">
1566 43
            if (isset($this->cssStyles['table.sheet' . $sheetIndex . ' tr.row' . $row]['height'])) {
1567 8
                $height = $this->cssStyles['table.sheet' . $sheetIndex . ' tr.row' . $row]['height'];
1568 8
                $xcssClass['height'] = $height;
1569
            }
1570
            //** end of redundant code **
1571 43
            if ($this->useInlineCss) {
1572 14
                foreach (['border-top', 'border-bottom', 'border-right', 'border-left'] as $borderType) {
1573 14
                    if (($xcssClass[$borderType] ?? '') === 'none #000000') {
1574 13
                        unset($xcssClass[$borderType]);
1575
                    }
1576
                }
1577
            }
1578
1579 43
            if ($htmlx) {
1580 11
                $xcssClass['position'] = 'relative';
1581
            }
1582
            /** @var string[] $xcssClass */
1583 43
            $html .= ' style="' . $this->assembleCSS($xcssClass) . '"';
1584 43
            if ($this->useInlineCss) {
1585 14
                $html .= ' class="gridlines gridlinesp"';
1586
            }
1587
        }
1588
1589 541
        $html = $this->generateRowSpans($html, $rowSpan, $colSpan);
1590
1591 541
        $tables = $worksheet->getTablesWithStylesForCell($worksheet->getCell($coordinate));
1592 541
        if (count($tables) > 0 || count($condStyles) > 0) {
1593 11
            $matched = false; // TODO the style gotten from the merger overrides everything
1594 11
            $styleMerger = new StyleMerger($worksheet->getCell($coordinate)->getStyle());
1595 11
            if ($this->tableFormats) {
1596 4
                if (count($tables) > 0) {
1597 4
                    foreach ($tables as $ts) {
1598
                        /** @var Table $ts */
1599 4
                        $dxfsTableStyle = $ts->getStyle()->getTableDxfsStyle();
1600 4
                        if ($dxfsTableStyle !== null) {
1601
                            /** @var int */
1602 4
                            $tableRow = $ts->getRowNumber($coordinate);
1603
                            /** @var TableDxfsStyle $dxfsTableStyle */
1604 4
                            if ($tableRow === 0 && $dxfsTableStyle->getHeaderRowStyle() !== null) {
1605 4
                                $styleMerger->mergeStyle($dxfsTableStyle->getHeaderRowStyle());
1606 4
                                $matched = true;
1607 4
                            } elseif ($tableRow % 2 === 1 && $dxfsTableStyle->getFirstRowStripeStyle() !== null) {
1608 4
                                $styleMerger->mergeStyle($dxfsTableStyle->getFirstRowStripeStyle());
1609 4
                                $matched = true;
1610 4
                            } elseif ($tableRow % 2 === 0 && $dxfsTableStyle->getSecondRowStripeStyle() !== null) {
1611 4
                                $styleMerger->mergeStyle($dxfsTableStyle->getSecondRowStripeStyle());
1612 4
                                $matched = true;
1613
                            }
1614
                        }
1615
                    }
1616
                }
1617
            }
1618 11
            if (count($condStyles) > 0 && $this->conditionalFormatting) {
1619 8
                if ($worksheet->getConditionalRange($coordinate) !== null) {
1620 8
                    $assessor = new CellStyleAssessor($worksheet->getCell($coordinate), $worksheet->getConditionalRange($coordinate));
1621
                } else {
1622
                    $assessor = new CellStyleAssessor($worksheet->getCell($coordinate), $coordinate);
1623
                }
1624 8
                $matchedStyle = $assessor->matchConditionsReturnNullIfNoneMatched($condStyles, $cellData, true);
1625
1626 8
                if ($matchedStyle !== null) {
1627 8
                    $matched = true;
1628
                    // this is really slow
1629 8
                    $styleMerger->mergeStyle($matchedStyle);
1630
                }
1631
            }
1632 11
            if ($matched) {
1633 10
                $styles = $this->createCSSStyle($styleMerger->getStyle());
1634 10
                $html .= ' style="';
1635 10
                foreach ($styles as $key => $value) {
1636 10
                    $html .= $key . ':' . $value . ';';
1637
                }
1638 10
                $html .= '"';
1639
            }
1640
        }
1641
1642 541
        $html .= '>';
1643 541
        $html .= $htmlx;
1644
1645 541
        $html .= $this->writeComment($worksheet, $coordinate);
1646
1647
        // Cell data
1648 541
        $html .= $cellData;
1649
1650
        // Column end
1651 541
        $html .= '</' . $cellType . '>' . PHP_EOL;
1652
    }
1653
1654
    /**
1655
     * Generate row.
1656
     *
1657
     * @param array<int, string> $values Array containing cells in a row
1658
     * @param int $row Row number (0-based)
1659
     * @param string $cellType eg: 'td'
1660
     */
1661 541
    private function generateRow(Worksheet $worksheet, array $values, int $row, string $cellType): string
1662
    {
1663
        // Sheet index
1664 541
        $sheetIndex = $worksheet->getParentOrThrow()->getIndex($worksheet);
1665 541
        $html = $this->generateRowStart($worksheet, $sheetIndex, $row);
1666
1667
        // Write cells
1668 541
        $colNum = 0;
1669 541
        $tcpdfInited = false;
1670 541
        foreach ($values as $key => $cellAddress) {
1671 541
            if ($this instanceof Pdf\Mpdf) {
1672 23
                $colNum = $key - 1;
1673 524
            } elseif ($this instanceof Pdf\Tcpdf) {
1674
                // It appears that Tcpdf requires first cell in tr.
1675 7
                $colNum = $key - 1;
1676 7
                if (!$tcpdfInited && $key !== 1) {
1677 1
                    $tempspan = ($colNum > 1) ? " colspan='$colNum'" : '';
1678 1
                    $html .= "<td$tempspan></td>\n";
1679
                }
1680 7
                $tcpdfInited = true;
1681
            }
1682 541
            [$cell, $cssClass, $coordinate] = $this->generateRowCellCss($worksheet, $cellAddress, $row, $colNum);
1683
1684
            // Cell Data
1685 541
            $cellData = $this->generateRowCellData($worksheet, $cell, $cssClass);
1686
1687
            // Get an array of all styles
1688 541
            $condStyles = $worksheet->getStyle($coordinate)->getConditionalStyles();
1689
1690
            // Hyperlink?
1691 541
            if ($worksheet->hyperlinkExists($coordinate) && !$worksheet->getHyperlink($coordinate)->isInternal()) {
1692 13
                $url = $worksheet->getHyperlink($coordinate)->getUrl();
1693 13
                $urlDecode1 = html_entity_decode($url, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
1694 13
                $urlTrim = Preg::replace('/^\s+/u', '', $urlDecode1);
1695 13
                $parseScheme = Preg::isMatch('/^([\w\s\x00-\x1f]+):/u', strtolower($urlTrim), $matches);
1696 13
                if ($parseScheme && !in_array($matches[1], ['http', 'https', 'file', 'ftp', 'mailto', 's3'], true)) {
1697 3
                    $cellData = htmlspecialchars($url, Settings::htmlEntityFlags());
1698 3
                    $cellData = self::replaceControlChars($cellData);
1699
                } else {
1700 11
                    $tooltip = $worksheet->getHyperlink($coordinate)->getTooltip();
1701 11
                    $tooltipOut = empty($tooltip) ? '' : (' title="' . htmlspecialchars($tooltip) . '"');
1702 11
                    $cellData = '<a href="'
1703 11
                        . htmlspecialchars($url) . '"'
1704 11
                        . $tooltipOut
1705 11
                        . '>' . $cellData . '</a>';
1706
                }
1707
            }
1708
1709
            // Should the cell be written or is it swallowed by a rowspan or colspan?
1710 541
            $writeCell = !(isset($this->isSpannedCell[$worksheet->getParentOrThrow()->getIndex($worksheet)][$row + 1][$colNum])
1711 541
                && $this->isSpannedCell[$worksheet->getParentOrThrow()->getIndex($worksheet)][$row + 1][$colNum]);
1712
1713
            // Colspan and Rowspan
1714 541
            $colSpan = 1;
1715 541
            $rowSpan = 1;
1716 541
            if (isset($this->isBaseCell[$worksheet->getParentOrThrow()->getIndex($worksheet)][$row + 1][$colNum])) {
1717
                /** @var array<string, int> */
1718 21
                $spans = $this->isBaseCell[$worksheet->getParentOrThrow()->getIndex($worksheet)][$row + 1][$colNum];
1719 21
                $rowSpan = $spans['rowspan'];
1720 21
                $colSpan = $spans['colspan'];
1721
1722
                //    Also apply style from last cell in merge to fix borders -
1723
                //        relies on !important for non-none border declarations in createCSSStyleBorder
1724 21
                $endCellCoord = Coordinate::stringFromColumnIndex($colNum + $colSpan) . ($row + $rowSpan);
1725 21
                if (!$this->useInlineCss && is_string($cssClass)) {
1726 18
                    $cssClass .= ' style' . $worksheet->getCell($endCellCoord)->getXfIndex();
1727
                } else {
1728 4
                    $endBorders = $this->spreadsheet->getCellXfByIndex($worksheet->getCell($endCellCoord)->getXfIndex())->getBorders();
1729 4
                    $altBorders = $this->createCSSStyleBorders($endBorders);
1730 4
                    foreach ($altBorders as $altKey => $altValue) {
1731 4
                        if (str_contains($altValue, '!important')) {
1732 2
                            $cssClass[$altKey] = $altValue;
1733
                        }
1734
                    }
1735
                }
1736
            }
1737
1738
            // Write
1739 541
            if ($writeCell) {
1740 541
                $this->generateRowWriteCell($html, $worksheet, $coordinate, $cellType, $cellData, $colSpan, $rowSpan, $cssClass, $colNum, $sheetIndex, $row, $condStyles);
1741
            }
1742
1743
            // Next column
1744 541
            ++$colNum;
1745
        }
1746
1747
        // Write row end
1748 541
        $html .= '          </tr>' . PHP_EOL;
1749
1750
        // Return
1751 541
        return $html;
1752
    }
1753
1754
    /** @param string[] $matches */
1755 2
    private static function replaceNonAscii(array $matches): string
1756
    {
1757 2
        return '&#' . mb_ord($matches[0], 'UTF-8') . ';';
1758
    }
1759
1760 3
    private static function replaceControlChars(string $convert): string
1761
    {
1762 3
        return (string) preg_replace_callback(
1763 3
            '/[\x00-\x1f]/',
1764 3
            [self::class, 'replaceNonAscii'],
1765 3
            $convert
1766 3
        );
1767
    }
1768
1769
    /**
1770
     * Takes array where of CSS properties / values and converts to CSS string.
1771
     *
1772
     * @param string[] $values
1773
     */
1774 543
    private function assembleCSS(array $values = []): string
1775
    {
1776 543
        $pairs = [];
1777 543
        foreach ($values as $property => $value) {
1778 543
            $pairs[] = $property . ':' . $value;
1779
        }
1780 543
        $string = implode('; ', $pairs);
1781
1782 543
        return $string;
1783
    }
1784
1785
    /**
1786
     * Get images root.
1787
     */
1788 19
    public function getImagesRoot(): string
1789
    {
1790 19
        return $this->imagesRoot;
1791
    }
1792
1793
    /**
1794
     * Set images root.
1795
     *
1796
     * @return $this
1797
     */
1798 1
    public function setImagesRoot(string $imagesRoot): static
1799
    {
1800 1
        $this->imagesRoot = $imagesRoot;
1801
1802 1
        return $this;
1803
    }
1804
1805
    /**
1806
     * Get embed images.
1807
     */
1808 5
    public function getEmbedImages(): bool
1809
    {
1810 5
        return $this->embedImages;
1811
    }
1812
1813
    /**
1814
     * Set embed images.
1815
     *
1816
     * @return $this
1817
     */
1818 4
    public function setEmbedImages(bool $embedImages): static
1819
    {
1820 4
        $this->embedImages = $embedImages;
1821
1822 4
        return $this;
1823
    }
1824
1825
    /**
1826
     * Get use inline CSS?
1827
     */
1828 1
    public function getUseInlineCss(): bool
1829
    {
1830 1
        return $this->useInlineCss;
1831
    }
1832
1833
    /**
1834
     * Set use inline CSS?
1835
     *
1836
     * @return $this
1837
     */
1838 15
    public function setUseInlineCss(bool $useInlineCss): static
1839
    {
1840 15
        $this->useInlineCss = $useInlineCss;
1841
1842 15
        return $this;
1843
    }
1844
1845 4
    public function setTableFormats(bool $tableFormats): self
1846
    {
1847 4
        $this->tableFormats = $tableFormats;
1848
1849 4
        return $this;
1850
    }
1851
1852 8
    public function setConditionalFormatting(bool $conditionalFormatting): self
1853
    {
1854 8
        $this->conditionalFormatting = $conditionalFormatting;
1855
1856 8
        return $this;
1857
    }
1858
1859
    /**
1860
     * Add color to formatted string as inline style.
1861
     *
1862
     * @param string $value Plain formatted value without color
1863
     * @param string $format Format code
1864
     */
1865 395
    public function formatColor(string $value, string $format): string
1866
    {
1867 395
        return self::formatColorStatic($value, $format);
1868
    }
1869
1870
    /**
1871
     * Add color to formatted string as inline style.
1872
     *
1873
     * @param string $value Plain formatted value without color
1874
     * @param string $format Format code
1875
     */
1876 395
    public static function formatColorStatic(string $value, string $format): string
1877
    {
1878
        // Color information, e.g. [Red] is always at the beginning
1879 395
        $color = null; // initialize
1880 395
        $matches = [];
1881
1882 395
        $color_regex = '/^\[[a-zA-Z]+\]/';
1883 395
        if (Preg::isMatch($color_regex, $format, $matches)) {
1884 17
            $color = str_replace(['[', ']'], '', $matches[0]);
1885 17
            $color = strtolower($color);
1886
        }
1887
1888
        // convert to PCDATA
1889 395
        $result = htmlspecialchars($value, Settings::htmlEntityFlags());
1890
1891
        // color span tag
1892 395
        if ($color !== null) {
1893 17
            $result = '<span style="color:' . $color . '">' . $result . '</span>';
1894
        }
1895
1896 395
        return $result;
1897
    }
1898
1899
    /**
1900
     * Calculate information about HTML colspan and rowspan which is not always the same as Excel's.
1901
     */
1902 543
    private function calculateSpans(): void
1903
    {
1904 543
        if ($this->spansAreCalculated) {
1905 543
            return;
1906
        }
1907
        // Identify all cells that should be omitted in HTML due to cell merge.
1908
        // In HTML only the upper-left cell should be written and it should have
1909
        //   appropriate rowspan / colspan attribute
1910 543
        $sheetIndexes = $this->sheetIndex !== null
1911 543
            ? [$this->sheetIndex] : range(0, $this->spreadsheet->getSheetCount() - 1);
1912
1913 543
        foreach ($sheetIndexes as $sheetIndex) {
1914 543
            $sheet = $this->spreadsheet->getSheet($sheetIndex);
1915
1916 543
            $candidateSpannedRow = [];
1917
1918
            // loop through all Excel merged cells
1919 543
            foreach ($sheet->getMergeCells() as $cells) {
1920 21
                [$cells] = Coordinate::splitRange($cells);
1921 21
                $first = $cells[0];
1922 21
                $last = $cells[1];
1923
1924 21
                [$fc, $fr] = Coordinate::indexesFromString($first);
1925 21
                $fc = $fc - 1;
1926
1927 21
                [$lc, $lr] = Coordinate::indexesFromString($last);
1928 21
                $lc = $lc - 1;
1929
1930
                // loop through the individual cells in the individual merge
1931 21
                $r = $fr - 1;
1932 21
                while ($r++ < $lr) {
1933
                    // also, flag this row as a HTML row that is candidate to be omitted
1934 21
                    $candidateSpannedRow[$r] = $r;
1935
1936 21
                    $c = $fc - 1;
1937 21
                    while ($c++ < $lc) {
1938 21
                        if (!($c == $fc && $r == $fr)) {
1939
                            // not the upper-left cell (should not be written in HTML)
1940 21
                            $this->isSpannedCell[$sheetIndex][$r][$c] = [
1941 21
                                'baseCell' => [$fr, $fc],
1942 21
                            ];
1943
                        } else {
1944
                            // upper-left is the base cell that should hold the colspan/rowspan attribute
1945 21
                            $this->isBaseCell[$sheetIndex][$r][$c] = [
1946 21
                                'xlrowspan' => $lr - $fr + 1, // Excel rowspan
1947 21
                                'rowspan' => $lr - $fr + 1, // HTML rowspan, value may change
1948 21
                                'xlcolspan' => $lc - $fc + 1, // Excel colspan
1949 21
                                'colspan' => $lc - $fc + 1, // HTML colspan, value may change
1950 21
                            ];
1951
                        }
1952
                    }
1953
                }
1954
            }
1955
1956 543
            $this->calculateSpansOmitRows($sheet, $sheetIndex, $candidateSpannedRow);
1957
1958
            // TODO: Same for columns
1959
        }
1960
1961
        // We have calculated the spans
1962 543
        $this->spansAreCalculated = true;
1963
    }
1964
1965
    /** @param int[] $candidateSpannedRow */
1966 543
    private function calculateSpansOmitRows(Worksheet $sheet, int $sheetIndex, array $candidateSpannedRow): void
1967
    {
1968
        // Identify which rows should be omitted in HTML. These are the rows where all the cells
1969
        //   participate in a merge and the where base cells are somewhere above.
1970 543
        $countColumns = Coordinate::columnIndexFromString($sheet->getHighestColumn());
1971 543
        foreach ($candidateSpannedRow as $rowIndex) {
1972 21
            if (isset($this->isSpannedCell[$sheetIndex][$rowIndex])) {
1973 21
                if (count($this->isSpannedCell[$sheetIndex][$rowIndex]) == $countColumns) {
1974 9
                    $this->isSpannedRow[$sheetIndex][$rowIndex] = $rowIndex;
1975
                }
1976
            }
1977
        }
1978
1979
        // For each of the omitted rows we found above, the affected rowspans should be subtracted by 1
1980 543
        if (isset($this->isSpannedRow[$sheetIndex])) {
1981 9
            foreach ($this->isSpannedRow[$sheetIndex] as $rowIndex) {
1982 9
                $adjustedBaseCells = [];
1983 9
                $c = -1;
1984 9
                $e = $countColumns - 1;
1985 9
                while ($c++ < $e) {
1986 9
                    $baseCell = $this->isSpannedCell[$sheetIndex][$rowIndex][$c]['baseCell'];
1987
1988 9
                    if (!in_array($baseCell, $adjustedBaseCells, true)) {
1989
                        // subtract rowspan by 1
1990
                        /** @var array<int|string> $baseCell */
1991 9
                        --$this->isBaseCell[$sheetIndex][$baseCell[0]][$baseCell[1]]['rowspan'];
1992 9
                        $adjustedBaseCells[] = $baseCell;
1993
                    }
1994
                }
1995
            }
1996
        }
1997
    }
1998
1999
    /**
2000
     * Write a comment in the same format as LibreOffice.
2001
     *
2002
     * @see https://github.com/LibreOffice/core/blob/9fc9bf3240f8c62ad7859947ab8a033ac1fe93fa/sc/source/filter/html/htmlexp.cxx#L1073-L1092
2003
     */
2004 541
    private function writeComment(Worksheet $worksheet, string $coordinate): string
2005
    {
2006 541
        $result = '';
2007 541
        if (!$this->isPdf && isset($worksheet->getComments()[$coordinate])) {
2008 24
            $sanitizedString = $this->generateRowCellDataValueRich($worksheet->getComment($coordinate)->getText());
2009 24
            $dir = ($worksheet->getComment($coordinate)->getTextboxDirection() === Comment::TEXTBOX_DIRECTION_RTL) ? ' dir="rtl"' : '';
2010 24
            $align = strtolower($worksheet->getComment($coordinate)->getAlignment());
2011 24
            $alignment = Alignment::HORIZONTAL_ALIGNMENT_FOR_HTML[$align] ?? '';
2012 24
            if ($alignment !== '') {
2013 2
                $alignment = " style=\"text-align:$alignment\"";
2014
            }
2015 24
            if ($sanitizedString !== '') {
2016 24
                $result .= '<a class="comment-indicator"></a>';
2017 24
                $result .= "<div class=\"comment\"$dir$alignment>" . $sanitizedString . '</div>';
2018 24
                $result .= PHP_EOL;
2019
            }
2020
        }
2021
2022 541
        return $result;
2023
    }
2024
2025 512
    public function getOrientation(): ?string
2026
    {
2027
        // Expect Pdf classes to override this method.
2028 512
        return $this->isPdf ? PageSetup::ORIENTATION_PORTRAIT : null;
2029
    }
2030
2031
    /**
2032
     * Generate @page declarations.
2033
     */
2034 543
    private function generatePageDeclarations(bool $generateSurroundingHTML): string
2035
    {
2036
        // Ensure that Spans have been calculated?
2037 543
        $this->calculateSpans();
2038
2039
        // Fetch sheets
2040 543
        $sheets = [];
2041 543
        if ($this->sheetIndex === null) {
2042 15
            $sheets = $this->spreadsheet->getAllSheets();
2043
        } else {
2044 535
            $sheets[] = $this->spreadsheet->getSheet($this->sheetIndex);
2045
        }
2046
2047
        // Construct HTML
2048 543
        $htmlPage = $generateSurroundingHTML ? ('<style type="text/css">' . PHP_EOL) : '';
2049
2050
        // Loop all sheets
2051 543
        $sheetId = 0;
2052 543
        foreach ($sheets as $worksheet) {
2053 543
            $htmlPage .= "@page page$sheetId { ";
2054 543
            $left = StringHelper::formatNumber($worksheet->getPageMargins()->getLeft()) . 'in; ';
2055 543
            $htmlPage .= 'margin-left: ' . $left;
2056 543
            $right = StringHelper::FormatNumber($worksheet->getPageMargins()->getRight()) . 'in; ';
2057 543
            $htmlPage .= 'margin-right: ' . $right;
2058 543
            $top = StringHelper::FormatNumber($worksheet->getPageMargins()->getTop()) . 'in; ';
2059 543
            $htmlPage .= 'margin-top: ' . $top;
2060 543
            $bottom = StringHelper::FormatNumber($worksheet->getPageMargins()->getBottom()) . 'in; ';
2061 543
            $htmlPage .= 'margin-bottom: ' . $bottom;
2062 543
            $orientation = $this->getOrientation() ?? $worksheet->getPageSetup()->getOrientation();
2063 543
            if ($orientation === PageSetup::ORIENTATION_LANDSCAPE) {
2064 17
                $htmlPage .= 'size: landscape; ';
2065 527
            } elseif ($orientation === PageSetup::ORIENTATION_PORTRAIT) {
2066 13
                $htmlPage .= 'size: portrait; ';
2067
            }
2068 543
            $htmlPage .= '}' . PHP_EOL;
2069 543
            ++$sheetId;
2070
        }
2071 543
        $htmlPage .= implode(PHP_EOL, [
2072 543
            '.navigation {page-break-after: always;}',
2073 543
            '.scrpgbrk, div + div {page-break-before: always;}',
2074 543
            '@media screen {',
2075 543
            '  .gridlines td {border: 1px solid black;}',
2076 543
            '  .gridlines th {border: 1px solid black;}',
2077 543
            '  body>div {margin-top: 5px;}',
2078 543
            '  body>div:first-child {margin-top: 0;}',
2079 543
            '  .scrpgbrk {margin-top: 1px;}',
2080 543
            '}',
2081 543
            '@media print {',
2082 543
            '  .gridlinesp td {border: 1px solid black;}',
2083 543
            '  .gridlinesp th {border: 1px solid black;}',
2084 543
            '  .navigation {display: none;}',
2085 543
            '}',
2086 543
            '',
2087 543
        ]);
2088 543
        $htmlPage .= $generateSurroundingHTML ? ('</style>' . PHP_EOL) : '';
2089
2090 543
        return $htmlPage;
2091
    }
2092
2093 541
    private function shouldGenerateRow(Worksheet $sheet, int $row): bool
2094
    {
2095 541
        if (!($this instanceof Pdf\Mpdf || $this instanceof Pdf\Tcpdf)) {
2096 518
            return true;
2097
        }
2098
2099 29
        return $sheet->isRowVisible($row);
2100
    }
2101
2102 543
    private function shouldGenerateColumn(Worksheet $sheet, string $colStr): bool
2103
    {
2104 543
        if (!($this instanceof Pdf\Mpdf || $this instanceof Pdf\Tcpdf)) {
2105 520
            return true;
2106
        }
2107 29
        if (!$sheet->columnDimensionExists($colStr)) {
2108 28
            return true;
2109
        }
2110
2111 11
        return $sheet->getColumnDimension($colStr)->getVisible();
2112
    }
2113
2114 1
    public function getBetterBoolean(): bool
2115
    {
2116 1
        return $this->betterBoolean;
2117
    }
2118
2119 3
    public function setBetterBoolean(bool $betterBoolean): self
2120
    {
2121 3
        $this->betterBoolean = $betterBoolean;
2122
2123 3
        return $this;
2124
    }
2125
}
2126