Html   F
last analyzed

Complexity

Total Complexity 383

Size/Duplication

Total Lines 2198
Duplicated Lines 0 %

Test Coverage

Coverage 98.7%

Importance

Changes 3
Bugs 0 Features 0
Metric Value
wmc 383
eloc 996
c 3
b 0
f 0
dl 0
loc 2198
ccs 985
cts 998
cp 0.987
rs 1.604

76 Methods

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