Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

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