Failed Conditions
Push — master ( 27d83b...a2771e )
by Adrien
35:04
created

Html::generateStyles()   B

Complexity

Conditions 6
Paths 13

Size

Total Lines 33
Code Lines 13

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 13
CRAP Score 6.0131

Importance

Changes 0
Metric Value
cc 6
eloc 13
nc 13
nop 1
dl 0
loc 33
ccs 13
cts 14
cp 0.9286
crap 6.0131
rs 8.439
c 0
b 0
f 0
1
<?php
2
3
namespace PhpOffice\PhpSpreadsheet\Writer;
4
5
use PhpOffice\PhpSpreadsheet\Calculation\Calculation;
6
use PhpOffice\PhpSpreadsheet\Cell\Cell;
7
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
8
use PhpOffice\PhpSpreadsheet\Chart\Chart;
9
use PhpOffice\PhpSpreadsheet\RichText\RichText;
10
use PhpOffice\PhpSpreadsheet\RichText\Run;
11
use PhpOffice\PhpSpreadsheet\Shared\Drawing as SharedDrawing;
12
use PhpOffice\PhpSpreadsheet\Shared\File;
13
use PhpOffice\PhpSpreadsheet\Shared\Font as SharedFont;
14
use PhpOffice\PhpSpreadsheet\Shared\StringHelper;
15
use PhpOffice\PhpSpreadsheet\Spreadsheet;
16
use PhpOffice\PhpSpreadsheet\Style\Alignment;
17
use PhpOffice\PhpSpreadsheet\Style\Border;
18
use PhpOffice\PhpSpreadsheet\Style\Borders;
19
use PhpOffice\PhpSpreadsheet\Style\Fill;
20
use PhpOffice\PhpSpreadsheet\Style\Font;
21
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
22
use PhpOffice\PhpSpreadsheet\Style\Style;
23
use PhpOffice\PhpSpreadsheet\Worksheet\Drawing;
24
use PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing;
25
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
26
use PhpOffice\PhpSpreadsheet\Writer\Exception as WriterException;
27
28
class Html extends BaseWriter
29
{
30
    /**
31
     * Spreadsheet object.
32
     *
33
     * @var Spreadsheet
34
     */
35
    protected $spreadsheet;
36
37
    /**
38
     * Sheet index to write.
39
     *
40
     * @var int
41
     */
42
    private $sheetIndex = 0;
43
44
    /**
45
     * Images root.
46
     *
47
     * @var string
48
     */
49
    private $imagesRoot = '';
50
51
    /**
52
     * embed images, or link to images.
53
     *
54
     * @var bool
55
     */
56
    private $embedImages = false;
57
58
    /**
59
     * Use inline CSS?
60
     *
61
     * @var bool
62
     */
63
    private $useInlineCss = false;
64
65
    /**
66
     * Array of CSS styles.
67
     *
68
     * @var array
69
     */
70
    private $cssStyles;
71
72
    /**
73
     * Array of column widths in points.
74
     *
75
     * @var array
76
     */
77
    private $columnWidths;
78
79
    /**
80
     * Default font.
81
     *
82
     * @var Font
83
     */
84
    private $defaultFont;
85
86
    /**
87
     * Flag whether spans have been calculated.
88
     *
89
     * @var bool
90
     */
91
    private $spansAreCalculated = false;
92
93
    /**
94
     * Excel cells that should not be written as HTML cells.
95
     *
96
     * @var array
97
     */
98
    private $isSpannedCell = [];
99
100
    /**
101
     * Excel cells that are upper-left corner in a cell merge.
102
     *
103
     * @var array
104
     */
105
    private $isBaseCell = [];
106
107
    /**
108
     * Excel rows that should not be written as HTML rows.
109
     *
110
     * @var array
111
     */
112
    private $isSpannedRow = [];
113
114
    /**
115
     * Is the current writer creating PDF?
116
     *
117
     * @var bool
118
     */
119
    protected $isPdf = false;
120
121
    /**
122
     * Generate the Navigation block.
123
     *
124
     * @var bool
125
     */
126
    private $generateSheetNavigationBlock = true;
127
128
    /**
129
     * Create a new HTML.
130
     *
131
     * @param Spreadsheet $spreadsheet
132
     */
133 18
    public function __construct(Spreadsheet $spreadsheet)
134
    {
135 18
        $this->spreadsheet = $spreadsheet;
136 18
        $this->defaultFont = $this->spreadsheet->getDefaultStyle()->getFont();
137 18
    }
138
139
    /**
140
     * Save Spreadsheet to file.
141
     *
142
     * @param string $pFilename
143
     *
144
     * @throws WriterException
145
     */
146 10
    public function save($pFilename)
147
    {
148
        // garbage collect
149 10
        $this->spreadsheet->garbageCollect();
150
151 10
        $saveDebugLog = Calculation::getInstance($this->spreadsheet)->getDebugLog()->getWriteDebugLog();
152 10
        Calculation::getInstance($this->spreadsheet)->getDebugLog()->setWriteDebugLog(false);
153 10
        $saveArrayReturnType = Calculation::getArrayReturnType();
154 10
        Calculation::setArrayReturnType(Calculation::RETURN_ARRAY_AS_VALUE);
155
156
        // Build CSS
157 10
        $this->buildCSS(!$this->useInlineCss);
158
159
        // Open file
160 10
        $fileHandle = fopen($pFilename, 'wb+');
161 10
        if ($fileHandle === false) {
162
            throw new WriterException("Could not open file $pFilename for writing.");
163
        }
164
165
        // Write headers
166 10
        fwrite($fileHandle, $this->generateHTMLHeader(!$this->useInlineCss));
167
168
        // Write navigation (tabs)
169 10
        if ((!$this->isPdf) && ($this->generateSheetNavigationBlock)) {
170 10
            fwrite($fileHandle, $this->generateNavigation());
171
        }
172
173
        // Write data
174 10
        fwrite($fileHandle, $this->generateSheetData());
175
176
        // Write footer
177 10
        fwrite($fileHandle, $this->generateHTMLFooter());
178
179
        // Close file
180 10
        fclose($fileHandle);
181
182 10
        Calculation::setArrayReturnType($saveArrayReturnType);
183 10
        Calculation::getInstance($this->spreadsheet)->getDebugLog()->setWriteDebugLog($saveDebugLog);
184 10
    }
185
186
    /**
187
     * Map VAlign.
188
     *
189
     * @param string $vAlign Vertical alignment
190
     *
191
     * @return string
192
     */
193 13
    private function mapVAlign($vAlign)
194
    {
195
        switch ($vAlign) {
196 13
            case Alignment::VERTICAL_BOTTOM:
197 13
                return 'bottom';
198 4
            case Alignment::VERTICAL_TOP:
199
                return 'top';
200 4
            case Alignment::VERTICAL_CENTER:
201
            case Alignment::VERTICAL_JUSTIFY:
202 4
                return 'middle';
203
            default:
204
                return 'baseline';
205
        }
206
    }
207
208
    /**
209
     * Map HAlign.
210
     *
211
     * @param string $hAlign Horizontal alignment
212
     *
213
     * @return false|string
214
     */
215 13
    private function mapHAlign($hAlign)
216
    {
217
        switch ($hAlign) {
218 13
            case Alignment::HORIZONTAL_GENERAL:
219 13
                return false;
220 5
            case Alignment::HORIZONTAL_LEFT:
221 4
                return 'left';
222 5
            case Alignment::HORIZONTAL_RIGHT:
223 4
                return 'right';
224 5
            case Alignment::HORIZONTAL_CENTER:
225 4
            case Alignment::HORIZONTAL_CENTER_CONTINUOUS:
226 1
                return 'center';
227 4
            case Alignment::HORIZONTAL_JUSTIFY:
228 4
                return 'justify';
229
            default:
230
                return false;
231
        }
232
    }
233
234
    /**
235
     * Map border style.
236
     *
237
     * @param int $borderStyle Sheet index
238
     *
239
     * @return string
240
     */
241 13
    private function mapBorderStyle($borderStyle)
242
    {
243
        switch ($borderStyle) {
244 13
            case Border::BORDER_NONE:
245 13
                return 'none';
246 4
            case Border::BORDER_DASHDOT:
247
                return '1px dashed';
248 4
            case Border::BORDER_DASHDOTDOT:
249
                return '1px dotted';
250 4
            case Border::BORDER_DASHED:
251
                return '1px dashed';
252 4
            case Border::BORDER_DOTTED:
253
                return '1px dotted';
254 4
            case Border::BORDER_DOUBLE:
255
                return '3px double';
256 4
            case Border::BORDER_HAIR:
257
                return '1px solid';
258 4
            case Border::BORDER_MEDIUM:
259
                return '2px solid';
260 4
            case Border::BORDER_MEDIUMDASHDOT:
261
                return '2px dashed';
262 4
            case Border::BORDER_MEDIUMDASHDOTDOT:
263
                return '2px dotted';
264 4
            case Border::BORDER_MEDIUMDASHED:
265
                return '2px dashed';
266 4
            case Border::BORDER_SLANTDASHDOT:
267
                return '2px dashed';
268 4
            case Border::BORDER_THICK:
269 4
                return '3px solid';
270 4
            case Border::BORDER_THIN:
271 4
                return '1px solid';
272
            default:
273
                // map others to thin
274
                return '1px solid';
275
        }
276
    }
277
278
    /**
279
     * Get sheet index.
280
     *
281
     * @return int
282
     */
283 4
    public function getSheetIndex()
284
    {
285 4
        return $this->sheetIndex;
286
    }
287
288
    /**
289
     * Set sheet index.
290
     *
291
     * @param int $pValue Sheet index
292
     *
293
     * @return HTML
294
     */
295
    public function setSheetIndex($pValue)
296
    {
297
        $this->sheetIndex = $pValue;
298
299
        return $this;
300
    }
301
302
    /**
303
     * Get sheet index.
304
     *
305
     * @return bool
306
     */
307
    public function getGenerateSheetNavigationBlock()
308
    {
309
        return $this->generateSheetNavigationBlock;
310
    }
311
312
    /**
313
     * Set sheet index.
314
     *
315
     * @param bool $pValue Flag indicating whether the sheet navigation block should be generated or not
316
     *
317
     * @return HTML
318
     */
319
    public function setGenerateSheetNavigationBlock($pValue)
320
    {
321
        $this->generateSheetNavigationBlock = (bool) $pValue;
322
323
        return $this;
324
    }
325
326
    /**
327
     * Write all sheets (resets sheetIndex to NULL).
328
     */
329
    public function writeAllSheets()
330
    {
331
        $this->sheetIndex = null;
332
333
        return $this;
334
    }
335
336
    /**
337
     * Generate HTML header.
338
     *
339
     * @param bool $pIncludeStyles Include styles?
340
     *
341
     * @throws WriterException
342
     *
343
     * @return string
344
     */
345 13
    public function generateHTMLHeader($pIncludeStyles = false)
346
    {
347
        // Spreadsheet object known?
348 13
        if ($this->spreadsheet === null) {
349
            throw new WriterException('Internal Spreadsheet object not set to an instance of an object.');
350
        }
351
352
        // Construct HTML
353 13
        $properties = $this->spreadsheet->getProperties();
354 13
        $html = '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">' . PHP_EOL;
355 13
        $html .= '<!-- Generated by Spreadsheet - https://github.com/PHPOffice/Spreadsheet -->' . PHP_EOL;
356 13
        $html .= '<html>' . PHP_EOL;
357 13
        $html .= '  <head>' . PHP_EOL;
358 13
        $html .= '      <meta http-equiv="Content-Type" content="text/html; charset=utf-8">' . PHP_EOL;
359 13
        if ($properties->getTitle() > '') {
360 13
            $html .= '      <title>' . htmlspecialchars($properties->getTitle()) . '</title>' . PHP_EOL;
361
        }
362 13
        if ($properties->getCreator() > '') {
363 13
            $html .= '      <meta name="author" content="' . htmlspecialchars($properties->getCreator()) . '" />' . PHP_EOL;
364
        }
365 13
        if ($properties->getTitle() > '') {
366 13
            $html .= '      <meta name="title" content="' . htmlspecialchars($properties->getTitle()) . '" />' . PHP_EOL;
367
        }
368 13
        if ($properties->getDescription() > '') {
369 5
            $html .= '      <meta name="description" content="' . htmlspecialchars($properties->getDescription()) . '" />' . PHP_EOL;
370
        }
371 13
        if ($properties->getSubject() > '') {
372 6
            $html .= '      <meta name="subject" content="' . htmlspecialchars($properties->getSubject()) . '" />' . PHP_EOL;
373
        }
374 13
        if ($properties->getKeywords() > '') {
375 6
            $html .= '      <meta name="keywords" content="' . htmlspecialchars($properties->getKeywords()) . '" />' . PHP_EOL;
376
        }
377 13
        if ($properties->getCategory() > '') {
378 6
            $html .= '      <meta name="category" content="' . htmlspecialchars($properties->getCategory()) . '" />' . PHP_EOL;
379
        }
380 13
        if ($properties->getCompany() > '') {
381 13
            $html .= '      <meta name="company" content="' . htmlspecialchars($properties->getCompany()) . '" />' . PHP_EOL;
382
        }
383 13
        if ($properties->getManager() > '') {
384
            $html .= '      <meta name="manager" content="' . htmlspecialchars($properties->getManager()) . '" />' . PHP_EOL;
385
        }
386
387 13
        if ($pIncludeStyles) {
388 10
            $html .= $this->generateStyles(true);
389
        }
390
391 13
        $html .= '  </head>' . PHP_EOL;
392 13
        $html .= '' . PHP_EOL;
393 13
        $html .= '  <body>' . PHP_EOL;
394
395 13
        return $html;
396
    }
397
398
    /**
399
     * Generate sheet data.
400
     *
401
     * @throws WriterException
402
     *
403
     * @return string
404
     */
405 13
    public function generateSheetData()
406
    {
407
        // Spreadsheet object known?
408 13
        if ($this->spreadsheet === null) {
409
            throw new WriterException('Internal Spreadsheet object not set to an instance of an object.');
410
        }
411
412
        // Ensure that Spans have been calculated?
413 13
        if ($this->sheetIndex !== null || !$this->spansAreCalculated) {
414 13
            $this->calculateSpans();
415
        }
416
417
        // Fetch sheets
418 13
        $sheets = [];
419 13
        if ($this->sheetIndex === null) {
420
            $sheets = $this->spreadsheet->getAllSheets();
421
        } else {
422 13
            $sheets[] = $this->spreadsheet->getSheet($this->sheetIndex);
423
        }
424
425
        // Construct HTML
426 13
        $html = '';
427
428
        // Loop all sheets
429 13
        $sheetId = 0;
430 13
        foreach ($sheets as $sheet) {
431
            // Write table header
432 13
            $html .= $this->generateTableHeader($sheet);
433
434
            // Get worksheet dimension
435 13
            $dimension = explode(':', $sheet->calculateWorksheetDimension());
436 13
            $dimension[0] = Coordinate::coordinateFromString($dimension[0]);
437 13
            $dimension[0][0] = Coordinate::columnIndexFromString($dimension[0][0]);
438 13
            $dimension[1] = Coordinate::coordinateFromString($dimension[1]);
439 13
            $dimension[1][0] = Coordinate::columnIndexFromString($dimension[1][0]);
440
441
            // row min,max
442 13
            $rowMin = $dimension[0][1];
443 13
            $rowMax = $dimension[1][1];
444
445
            // calculate start of <tbody>, <thead>
446 13
            $tbodyStart = $rowMin;
447 13
            $theadStart = $theadEnd = 0; // default: no <thead>    no </thead>
448 13
            if ($sheet->getPageSetup()->isRowsToRepeatAtTopSet()) {
449
                $rowsToRepeatAtTop = $sheet->getPageSetup()->getRowsToRepeatAtTop();
450
451
                // we can only support repeating rows that start at top row
452
                if ($rowsToRepeatAtTop[0] == 1) {
453
                    $theadStart = $rowsToRepeatAtTop[0];
454
                    $theadEnd = $rowsToRepeatAtTop[1];
455
                    $tbodyStart = $rowsToRepeatAtTop[1] + 1;
456
                }
457
            }
458
459
            // Loop through cells
460 13
            $row = $rowMin - 1;
461 13
            while ($row++ < $rowMax) {
462
                // <thead> ?
463 13
                if ($row == $theadStart) {
464
                    $html .= '        <thead>' . PHP_EOL;
465
                    $cellType = 'th';
466
                }
467
468
                // <tbody> ?
469 13
                if ($row == $tbodyStart) {
470 13
                    $html .= '        <tbody>' . PHP_EOL;
471 13
                    $cellType = 'td';
472
                }
473
474
                // Write row if there are HTML table cells in it
475 13
                if (!isset($this->isSpannedRow[$sheet->getParent()->getIndex($sheet)][$row])) {
476
                    // Start a new rowData
477 13
                    $rowData = [];
478
                    // Loop through columns
479 13
                    $column = $dimension[0][0];
480 13
                    while ($column <= $dimension[1][0]) {
481
                        // Cell exists?
482 13
                        if ($sheet->cellExistsByColumnAndRow($column, $row)) {
483 13
                            $rowData[$column] = Coordinate::stringFromColumnIndex($column) . $row;
484
                        } else {
485 5
                            $rowData[$column] = '';
486
                        }
487 13
                        ++$column;
488
                    }
489 13
                    $html .= $this->generateRow($sheet, $rowData, $row - 1, $cellType);
490
                }
491
492
                // </thead> ?
493 13
                if ($row == $theadEnd) {
494
                    $html .= '        </thead>' . PHP_EOL;
495
                }
496
            }
497 13
            $html .= $this->extendRowsForChartsAndImages($sheet, $row);
498
499
            // Close table body.
500 13
            $html .= '        </tbody>' . PHP_EOL;
501
502
            // Write table footer
503 13
            $html .= $this->generateTableFooter();
504
505
            // Writing PDF?
506 13
            if ($this->isPdf) {
507 4
                if ($this->sheetIndex === null && $sheetId + 1 < $this->spreadsheet->getSheetCount()) {
508
                    $html .= '<div style="page-break-before:always" />';
509
                }
510
            }
511
512
            // Next sheet
513 13
            ++$sheetId;
514
        }
515
516 13
        return $html;
517
    }
518
519
    /**
520
     * Generate sheet tabs.
521
     *
522
     * @throws WriterException
523
     *
524
     * @return string
525
     */
526 10
    public function generateNavigation()
527
    {
528
        // Spreadsheet object known?
529 10
        if ($this->spreadsheet === null) {
530
            throw new WriterException('Internal Spreadsheet object not set to an instance of an object.');
531
        }
532
533
        // Fetch sheets
534 10
        $sheets = [];
535 10
        if ($this->sheetIndex === null) {
536
            $sheets = $this->spreadsheet->getAllSheets();
537
        } else {
538 10
            $sheets[] = $this->spreadsheet->getSheet($this->sheetIndex);
539
        }
540
541
        // Construct HTML
542 10
        $html = '';
543
544
        // Only if there are more than 1 sheets
545 10
        if (count($sheets) > 1) {
546
            // Loop all sheets
547
            $sheetId = 0;
548
549
            $html .= '<ul class="navigation">' . PHP_EOL;
550
551
            foreach ($sheets as $sheet) {
552
                $html .= '  <li class="sheet' . $sheetId . '"><a href="#sheet' . $sheetId . '">' . $sheet->getTitle() . '</a></li>' . PHP_EOL;
553
                ++$sheetId;
554
            }
555
556
            $html .= '</ul>' . PHP_EOL;
557
        }
558
559 10
        return $html;
560
    }
561
562 13
    private function extendRowsForChartsAndImages(Worksheet $pSheet, $row)
563
    {
564 13
        $rowMax = $row;
565 13
        $colMax = 'A';
566 13
        if ($this->includeCharts) {
567
            foreach ($pSheet->getChartCollection() as $chart) {
568
                if ($chart instanceof Chart) {
569
                    $chartCoordinates = $chart->getTopLeftPosition();
570
                    $chartTL = Coordinate::coordinateFromString($chartCoordinates['cell']);
571
                    $chartCol = Coordinate::columnIndexFromString($chartTL[0]);
572
                    if ($chartTL[1] > $rowMax) {
573
                        $rowMax = $chartTL[1];
574
                        if ($chartCol > Coordinate::columnIndexFromString($colMax)) {
575
                            $colMax = $chartTL[0];
576
                        }
577
                    }
578
                }
579
            }
580
        }
581
582 13
        foreach ($pSheet->getDrawingCollection() as $drawing) {
583 5
            if ($drawing instanceof Drawing) {
584 4
                $imageTL = Coordinate::coordinateFromString($drawing->getCoordinates());
585 4
                $imageCol = Coordinate::columnIndexFromString($imageTL[0]);
586 4
                if ($imageTL[1] > $rowMax) {
587
                    $rowMax = $imageTL[1];
588
                    if ($imageCol > Coordinate::columnIndexFromString($colMax)) {
589 5
                        $colMax = $imageTL[0];
590
                    }
591
                }
592
            }
593
        }
594
595
        // Don't extend rows if not needed
596 13
        if ($row === $rowMax) {
597 13
            return '';
598
        }
599
600
        $html = '';
601
        ++$colMax;
602
603
        while ($row <= $rowMax) {
604
            $html .= '<tr>';
605
            for ($col = 'A'; $col != $colMax; ++$col) {
606
                $html .= '<td>';
607
                $html .= $this->writeImageInCell($pSheet, $col . $row);
608
                if ($this->includeCharts) {
609
                    $html .= $this->writeChartInCell($pSheet, $col . $row);
610
                }
611
                $html .= '</td>';
612
            }
613
            ++$row;
614
            $html .= '</tr>';
615
        }
616
617
        return $html;
618
    }
619
620
    /**
621
     * Generate image tag in cell.
622
     *
623
     * @param Worksheet $pSheet \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet
624
     * @param string $coordinates Cell coordinates
625
     *
626
     * @return string
627
     */
628 13
    private function writeImageInCell(Worksheet $pSheet, $coordinates)
629
    {
630
        // Construct HTML
631 13
        $html = '';
632
633
        // Write images
634 13
        foreach ($pSheet->getDrawingCollection() as $drawing) {
635 5
            if ($drawing instanceof Drawing) {
636 4
                if ($drawing->getCoordinates() == $coordinates) {
637 4
                    $filename = $drawing->getPath();
638
639
                    // Strip off eventual '.'
640 4
                    if (substr($filename, 0, 1) == '.') {
641
                        $filename = substr($filename, 1);
642
                    }
643
644
                    // Prepend images root
645 4
                    $filename = $this->getImagesRoot() . $filename;
646
647
                    // Strip off eventual '.'
648 4
                    if (substr($filename, 0, 1) == '.' && substr($filename, 0, 2) != './') {
649
                        $filename = substr($filename, 1);
650
                    }
651
652
                    // Convert UTF8 data to PCDATA
653 4
                    $filename = htmlspecialchars($filename);
654
655 4
                    $html .= PHP_EOL;
656 4
                    if ((!$this->embedImages) || ($this->isPdf)) {
657 4
                        $imageData = $filename;
658
                    } else {
659
                        $imageDetails = getimagesize($filename);
660
                        if ($fp = fopen($filename, 'rb', 0)) {
661
                            $picture = fread($fp, filesize($filename));
662
                            fclose($fp);
663
                            // base64 encode the binary data, then break it
664
                            // into chunks according to RFC 2045 semantics
665
                            $base64 = chunk_split(base64_encode($picture));
666
                            $imageData = 'data:' . $imageDetails['mime'] . ';base64,' . $base64;
667
                        } else {
668
                            $imageData = $filename;
669
                        }
670
                    }
671
672 4
                    $html .= '<div style="position: relative;">';
673
                    $html .= '<img style="position: absolute; z-index: 1; left: ' .
674 4
                        $drawing->getOffsetX() . 'px; top: ' . $drawing->getOffsetY() . 'px; width: ' .
675 4
                        $drawing->getWidth() . 'px; height: ' . $drawing->getHeight() . 'px;" src="' .
676 4
                        $imageData . '" border="0" />';
677 4
                    $html .= '</div>';
678
                }
679 1
            } elseif ($drawing instanceof MemoryDrawing) {
680 1
                if ($drawing->getCoordinates() != $coordinates) {
681
                    continue;
682
                }
683 1
                ob_start(); //  Let's start output buffering.
684 1
                imagepng($drawing->getImageResource()); //  This will normally output the image, but because of ob_start(), it won't.
685 1
                $contents = ob_get_contents(); //  Instead, output above is saved to $contents
686 1
                ob_end_clean(); //  End the output buffer.
687
688 1
                $dataUri = 'data:image/jpeg;base64,' . base64_encode($contents);
689
690
                //  Because of the nature of tables, width is more important than height.
691
                //  max-width: 100% ensures that image doesnt overflow containing cell
692
                //  width: X sets width of supplied image.
693
                //  As a result, images bigger than cell will be contained and images smaller will not get stretched
694 5
                $html .= '<img src="' . $dataUri . '" style="max-width:100%;width:' . $drawing->getWidth() . 'px;" />';
695
            }
696
        }
697
698 13
        return $html;
699
    }
700
701
    /**
702
     * Generate chart tag in cell.
703
     *
704
     * @param Worksheet $pSheet \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet
705
     * @param string $coordinates Cell coordinates
706
     *
707
     * @return string
708
     */
709
    private function writeChartInCell(Worksheet $pSheet, $coordinates)
710
    {
711
        // Construct HTML
712
        $html = '';
713
714
        // Write charts
715
        foreach ($pSheet->getChartCollection() as $chart) {
716
            if ($chart instanceof Chart) {
717
                $chartCoordinates = $chart->getTopLeftPosition();
718
                if ($chartCoordinates['cell'] == $coordinates) {
719
                    $chartFileName = File::sysGetTempDir() . '/' . uniqid('', true) . '.png';
720
                    if (!$chart->render($chartFileName)) {
721
                        return;
722
                    }
723
724
                    $html .= PHP_EOL;
725
                    $imageDetails = getimagesize($chartFileName);
726
                    if ($fp = fopen($chartFileName, 'rb', 0)) {
727
                        $picture = fread($fp, filesize($chartFileName));
728
                        fclose($fp);
729
                        // base64 encode the binary data, then break it
730
                        // into chunks according to RFC 2045 semantics
731
                        $base64 = chunk_split(base64_encode($picture));
732
                        $imageData = 'data:' . $imageDetails['mime'] . ';base64,' . $base64;
733
734
                        $html .= '<div style="position: relative;">';
735
                        $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 . '" border="0" />' . PHP_EOL;
736
                        $html .= '</div>';
737
738
                        unlink($chartFileName);
739
                    }
740
                }
741
            }
742
        }
743
744
        // Return
745
        return $html;
746
    }
747
748
    /**
749
     * Generate CSS styles.
750
     *
751
     * @param bool $generateSurroundingHTML Generate surrounding HTML tags? (&lt;style&gt; and &lt;/style&gt;)
752
     *
753
     * @throws WriterException
754
     *
755
     * @return string
756
     */
757 10
    public function generateStyles($generateSurroundingHTML = true)
758
    {
759
        // Spreadsheet object known?
760 10
        if ($this->spreadsheet === null) {
761
            throw new WriterException('Internal Spreadsheet object not set to an instance of an object.');
762
        }
763
764
        // Build CSS
765 10
        $css = $this->buildCSS($generateSurroundingHTML);
766
767
        // Construct HTML
768 10
        $html = '';
769
770
        // Start styles
771 10
        if ($generateSurroundingHTML) {
772 10
            $html .= '    <style type="text/css">' . PHP_EOL;
773 10
            $html .= '      html { ' . $this->assembleCSS($css['html']) . ' }' . PHP_EOL;
774
        }
775
776
        // Write all other styles
777 10
        foreach ($css as $styleName => $styleDefinition) {
778 10
            if ($styleName != 'html') {
779 10
                $html .= '      ' . $styleName . ' { ' . $this->assembleCSS($styleDefinition) . ' }' . PHP_EOL;
780
            }
781
        }
782
783
        // End styles
784 10
        if ($generateSurroundingHTML) {
785 10
            $html .= '    </style>' . PHP_EOL;
786
        }
787
788
        // Return
789 10
        return $html;
790
    }
791
792
    /**
793
     * Build CSS styles.
794
     *
795
     * @param bool $generateSurroundingHTML Generate surrounding HTML style? (html { })
796
     *
797
     * @throws WriterException
798
     *
799
     * @return array
800
     */
801 13
    public function buildCSS($generateSurroundingHTML = true)
802
    {
803
        // Spreadsheet object known?
804 13
        if ($this->spreadsheet === null) {
805
            throw new WriterException('Internal Spreadsheet object not set to an instance of an object.');
806
        }
807
808
        // Cached?
809 13
        if ($this->cssStyles !== null) {
810 10
            return $this->cssStyles;
811
        }
812
813
        // Ensure that spans have been calculated
814 13
        if (!$this->spansAreCalculated) {
815 13
            $this->calculateSpans();
816
        }
817
818
        // Construct CSS
819 13
        $css = [];
820
821
        // Start styles
822 13
        if ($generateSurroundingHTML) {
823
            // html { }
824 13
            $css['html']['font-family'] = 'Calibri, Arial, Helvetica, sans-serif';
825 13
            $css['html']['font-size'] = '11pt';
826 13
            $css['html']['background-color'] = 'white';
827
        }
828
829
        // CSS for comments as found in LibreOffice
830 13
        $css['a.comment-indicator:hover + div.comment'] = [
831
            'background' => '#ffd',
832
            'position' => 'absolute',
833
            'display' => 'block',
834
            'border' => '1px solid black',
835
            'padding' => '0.5em',
836
        ];
837
838 13
        $css['a.comment-indicator'] = [
839
            'background' => 'red',
840
            'display' => 'inline-block',
841
            'border' => '1px solid black',
842
            'width' => '0.5em',
843
            'height' => '0.5em',
844
        ];
845
846 13
        $css['div.comment']['display'] = 'none';
847
848
        // table { }
849 13
        $css['table']['border-collapse'] = 'collapse';
850 13
        if (!$this->isPdf) {
851 10
            $css['table']['page-break-after'] = 'always';
852
        }
853
854
        // .gridlines td { }
855 13
        $css['.gridlines td']['border'] = '1px dotted black';
856 13
        $css['.gridlines th']['border'] = '1px dotted black';
857
858
        // .b {}
859 13
        $css['.b']['text-align'] = 'center'; // BOOL
860
861
        // .e {}
862 13
        $css['.e']['text-align'] = 'center'; // ERROR
863
864
        // .f {}
865 13
        $css['.f']['text-align'] = 'right'; // FORMULA
866
867
        // .inlineStr {}
868 13
        $css['.inlineStr']['text-align'] = 'left'; // INLINE
869
870
        // .n {}
871 13
        $css['.n']['text-align'] = 'right'; // NUMERIC
872
873
        // .s {}
874 13
        $css['.s']['text-align'] = 'left'; // STRING
875
876
        // Calculate cell style hashes
877 13
        foreach ($this->spreadsheet->getCellXfCollection() as $index => $style) {
878 13
            $css['td.style' . $index] = $this->createCSSStyle($style);
879 13
            $css['th.style' . $index] = $this->createCSSStyle($style);
880
        }
881
882
        // Fetch sheets
883 13
        $sheets = [];
884 13
        if ($this->sheetIndex === null) {
885
            $sheets = $this->spreadsheet->getAllSheets();
886
        } else {
887 13
            $sheets[] = $this->spreadsheet->getSheet($this->sheetIndex);
888
        }
889
890
        // Build styles per sheet
891 13
        foreach ($sheets as $sheet) {
892
            // Calculate hash code
893 13
            $sheetIndex = $sheet->getParent()->getIndex($sheet);
894
895
            // Build styles
896
            // Calculate column widths
897 13
            $sheet->calculateColumnWidths();
898
899
            // col elements, initialize
900 13
            $highestColumnIndex = Coordinate::columnIndexFromString($sheet->getHighestColumn()) - 1;
901 13
            $column = -1;
902 13
            while ($column++ < $highestColumnIndex) {
903 13
                $this->columnWidths[$sheetIndex][$column] = 42; // approximation
904 13
                $css['table.sheet' . $sheetIndex . ' col.col' . $column]['width'] = '42pt';
905
            }
906
907
            // col elements, loop through columnDimensions and set width
908 13
            foreach ($sheet->getColumnDimensions() as $columnDimension) {
909 5
                if (($width = SharedDrawing::cellDimensionToPixels($columnDimension->getWidth(), $this->defaultFont)) >= 0) {
910 5
                    $width = SharedDrawing::pixelsToPoints($width);
911 5
                    $column = Coordinate::columnIndexFromString($columnDimension->getColumnIndex()) - 1;
912 5
                    $this->columnWidths[$sheetIndex][$column] = $width;
913 5
                    $css['table.sheet' . $sheetIndex . ' col.col' . $column]['width'] = $width . 'pt';
914
915 5
                    if ($columnDimension->getVisible() === false) {
916
                        $css['table.sheet' . $sheetIndex . ' col.col' . $column]['visibility'] = 'collapse';
917 5
                        $css['table.sheet' . $sheetIndex . ' col.col' . $column]['*display'] = 'none'; // target IE6+7
918
                    }
919
                }
920
            }
921
922
            // Default row height
923 13
            $rowDimension = $sheet->getDefaultRowDimension();
924
925
            // table.sheetN tr { }
926 13
            $css['table.sheet' . $sheetIndex . ' tr'] = [];
927
928 13
            if ($rowDimension->getRowHeight() == -1) {
929 13
                $pt_height = SharedFont::getDefaultRowHeightByFont($this->spreadsheet->getDefaultStyle()->getFont());
930
            } else {
931
                $pt_height = $rowDimension->getRowHeight();
932
            }
933 13
            $css['table.sheet' . $sheetIndex . ' tr']['height'] = $pt_height . 'pt';
934 13
            if ($rowDimension->getVisible() === false) {
935
                $css['table.sheet' . $sheetIndex . ' tr']['display'] = 'none';
936
                $css['table.sheet' . $sheetIndex . ' tr']['visibility'] = 'hidden';
937
            }
938
939
            // Calculate row heights
940 13
            foreach ($sheet->getRowDimensions() as $rowDimension) {
941 2
                $row = $rowDimension->getRowIndex() - 1;
942
943
                // table.sheetN tr.rowYYYYYY { }
944 2
                $css['table.sheet' . $sheetIndex . ' tr.row' . $row] = [];
945
946 2
                if ($rowDimension->getRowHeight() == -1) {
947 2
                    $pt_height = SharedFont::getDefaultRowHeightByFont($this->spreadsheet->getDefaultStyle()->getFont());
948
                } else {
949 1
                    $pt_height = $rowDimension->getRowHeight();
950
                }
951 2
                $css['table.sheet' . $sheetIndex . ' tr.row' . $row]['height'] = $pt_height . 'pt';
952 2
                if ($rowDimension->getVisible() === false) {
953
                    $css['table.sheet' . $sheetIndex . ' tr.row' . $row]['display'] = 'none';
954 13
                    $css['table.sheet' . $sheetIndex . ' tr.row' . $row]['visibility'] = 'hidden';
955
                }
956
            }
957
        }
958
959
        // Cache
960 13
        if ($this->cssStyles === null) {
961 13
            $this->cssStyles = $css;
962
        }
963
964
        // Return
965 13
        return $css;
966
    }
967
968
    /**
969
     * Create CSS style.
970
     *
971
     * @param Style $pStyle
972
     *
973
     * @return array
974
     */
975 13
    private function createCSSStyle(Style $pStyle)
976
    {
977
        // Create CSS
978 13
        $css = array_merge(
979 13
            $this->createCSSStyleAlignment($pStyle->getAlignment()),
980 13
            $this->createCSSStyleBorders($pStyle->getBorders()),
981 13
            $this->createCSSStyleFont($pStyle->getFont()),
982 13
            $this->createCSSStyleFill($pStyle->getFill())
983
        );
984
985
        // Return
986 13
        return $css;
987
    }
988
989
    /**
990
     * Create CSS style (\PhpOffice\PhpSpreadsheet\Style\Alignment).
991
     *
992
     * @param Alignment $pStyle \PhpOffice\PhpSpreadsheet\Style\Alignment
993
     *
994
     * @return array
995
     */
996 13
    private function createCSSStyleAlignment(Alignment $pStyle)
997
    {
998
        // Construct CSS
999 13
        $css = [];
1000
1001
        // Create CSS
1002 13
        $css['vertical-align'] = $this->mapVAlign($pStyle->getVertical());
1003 13
        if ($textAlign = $this->mapHAlign($pStyle->getHorizontal())) {
1004 5
            $css['text-align'] = $textAlign;
1005 5
            if (in_array($textAlign, ['left', 'right'])) {
1006 4
                $css['padding-' . $textAlign] = (string) ((int) $pStyle->getIndent() * 9) . 'px';
1007
            }
1008
        }
1009
1010 13
        return $css;
1011
    }
1012
1013
    /**
1014
     * Create CSS style (\PhpOffice\PhpSpreadsheet\Style\Font).
1015
     *
1016
     * @param Font $pStyle
1017
     *
1018
     * @return array
1019
     */
1020 13
    private function createCSSStyleFont(Font $pStyle)
1021
    {
1022
        // Construct CSS
1023 13
        $css = [];
1024
1025
        // Create CSS
1026 13
        if ($pStyle->getBold()) {
1027 5
            $css['font-weight'] = 'bold';
1028
        }
1029 13
        if ($pStyle->getUnderline() != Font::UNDERLINE_NONE && $pStyle->getStrikethrough()) {
1030
            $css['text-decoration'] = 'underline line-through';
1031 13
        } elseif ($pStyle->getUnderline() != Font::UNDERLINE_NONE) {
1032 4
            $css['text-decoration'] = 'underline';
1033 13
        } elseif ($pStyle->getStrikethrough()) {
1034
            $css['text-decoration'] = 'line-through';
1035
        }
1036 13
        if ($pStyle->getItalic()) {
1037 4
            $css['font-style'] = 'italic';
1038
        }
1039
1040 13
        $css['color'] = '#' . $pStyle->getColor()->getRGB();
1041 13
        $css['font-family'] = '\'' . $pStyle->getName() . '\'';
1042 13
        $css['font-size'] = $pStyle->getSize() . 'pt';
1043
1044 13
        return $css;
1045
    }
1046
1047
    /**
1048
     * Create CSS style (Borders).
1049
     *
1050
     * @param Borders $pStyle Borders
1051
     *
1052
     * @return array
1053
     */
1054 13
    private function createCSSStyleBorders(Borders $pStyle)
1055
    {
1056
        // Construct CSS
1057 13
        $css = [];
1058
1059
        // Create CSS
1060 13
        $css['border-bottom'] = $this->createCSSStyleBorder($pStyle->getBottom());
1061 13
        $css['border-top'] = $this->createCSSStyleBorder($pStyle->getTop());
1062 13
        $css['border-left'] = $this->createCSSStyleBorder($pStyle->getLeft());
1063 13
        $css['border-right'] = $this->createCSSStyleBorder($pStyle->getRight());
1064
1065 13
        return $css;
1066
    }
1067
1068
    /**
1069
     * Create CSS style (Border).
1070
     *
1071
     * @param Border $pStyle Border
1072
     *
1073
     * @return string
1074
     */
1075 13
    private function createCSSStyleBorder(Border $pStyle)
1076
    {
1077
        //    Create CSS - add !important to non-none border styles for merged cells
1078 13
        $borderStyle = $this->mapBorderStyle($pStyle->getBorderStyle());
1079 13
        $css = $borderStyle . ' #' . $pStyle->getColor()->getRGB() . (($borderStyle == 'none') ? '' : ' !important');
1080
1081 13
        return $css;
1082
    }
1083
1084
    /**
1085
     * Create CSS style (Fill).
1086
     *
1087
     * @param Fill $pStyle Fill
1088
     *
1089
     * @return array
1090
     */
1091 13
    private function createCSSStyleFill(Fill $pStyle)
1092
    {
1093
        // Construct HTML
1094 13
        $css = [];
1095
1096
        // Create CSS
1097 13
        $value = $pStyle->getFillType() == Fill::FILL_NONE ?
1098 13
            'white' : '#' . $pStyle->getStartColor()->getRGB();
1099 13
        $css['background-color'] = $value;
1100
1101 13
        return $css;
1102
    }
1103
1104
    /**
1105
     * Generate HTML footer.
1106
     */
1107 13
    public function generateHTMLFooter()
1108
    {
1109
        // Construct HTML
1110 13
        $html = '';
1111 13
        $html .= '  </body>' . PHP_EOL;
1112 13
        $html .= '</html>' . PHP_EOL;
1113
1114 13
        return $html;
1115
    }
1116
1117
    /**
1118
     * Generate table header.
1119
     *
1120
     * @param Worksheet $pSheet The worksheet for the table we are writing
1121
     *
1122
     * @return string
1123
     */
1124 13
    private function generateTableHeader($pSheet)
1125
    {
1126 13
        $sheetIndex = $pSheet->getParent()->getIndex($pSheet);
1127
1128
        // Construct HTML
1129 13
        $html = '';
1130 13
        $html .= $this->setMargins($pSheet);
1131
1132 13
        if (!$this->useInlineCss) {
1133 10
            $gridlines = $pSheet->getShowGridlines() ? ' gridlines' : '';
1134 10
            $html .= '    <table border="0" cellpadding="0" cellspacing="0" id="sheet' . $sheetIndex . '" class="sheet' . $sheetIndex . $gridlines . '">' . PHP_EOL;
1135
        } else {
1136 4
            $style = isset($this->cssStyles['table']) ?
1137 4
                $this->assembleCSS($this->cssStyles['table']) : '';
1138
1139 4
            if ($this->isPdf && $pSheet->getShowGridlines()) {
1140 1
                $html .= '    <table border="1" cellpadding="1" id="sheet' . $sheetIndex . '" cellspacing="1" style="' . $style . '">' . PHP_EOL;
1141
            } else {
1142 3
                $html .= '    <table border="0" cellpadding="1" id="sheet' . $sheetIndex . '" cellspacing="0" style="' . $style . '">' . PHP_EOL;
1143
            }
1144
        }
1145
1146
        // Write <col> elements
1147 13
        $highestColumnIndex = Coordinate::columnIndexFromString($pSheet->getHighestColumn()) - 1;
1148 13
        $i = -1;
1149 13
        while ($i++ < $highestColumnIndex) {
1150 13
            if (!$this->isPdf) {
1151 10
                if (!$this->useInlineCss) {
1152 10
                    $html .= '        <col class="col' . $i . '">' . PHP_EOL;
1153
                } else {
1154
                    $style = isset($this->cssStyles['table.sheet' . $sheetIndex . ' col.col' . $i]) ?
1155
                        $this->assembleCSS($this->cssStyles['table.sheet' . $sheetIndex . ' col.col' . $i]) : '';
1156
                    $html .= '        <col style="' . $style . '">' . PHP_EOL;
1157
                }
1158
            }
1159
        }
1160
1161 13
        return $html;
1162
    }
1163
1164
    /**
1165
     * Generate table footer.
1166
     */
1167 13
    private function generateTableFooter()
1168
    {
1169 13
        $html = '    </table>' . PHP_EOL;
1170
1171 13
        return $html;
1172
    }
1173
1174
    /**
1175
     * Generate row.
1176
     *
1177
     * @param Worksheet $pSheet \PhpOffice\PhpSpreadsheet\Worksheet\Worksheet
1178
     * @param array $pValues Array containing cells in a row
1179
     * @param int $pRow Row number (0-based)
1180
     * @param string $cellType eg: 'td'
1181
     *
1182
     * @throws WriterException
1183
     *
1184
     * @return string
1185
     */
1186 13
    private function generateRow(Worksheet $pSheet, array $pValues, $pRow, $cellType)
1187
    {
1188
        // Construct HTML
1189 13
        $html = '';
1190
1191
        // Sheet index
1192 13
        $sheetIndex = $pSheet->getParent()->getIndex($pSheet);
1193
1194
        // Dompdf and breaks
1195 13
        if ($this->isPdf && count($pSheet->getBreaks()) > 0) {
1196
            $breaks = $pSheet->getBreaks();
1197
1198
            // check if a break is needed before this row
1199
            if (isset($breaks['A' . $pRow])) {
1200
                // close table: </table>
1201
                $html .= $this->generateTableFooter();
1202
1203
                // insert page break
1204
                $html .= '<div style="page-break-before:always" />';
1205
1206
                // open table again: <table> + <col> etc.
1207
                $html .= $this->generateTableHeader($pSheet);
1208
            }
1209
        }
1210
1211
        // Write row start
1212 13
        if (!$this->useInlineCss) {
1213 10
            $html .= '          <tr class="row' . $pRow . '">' . PHP_EOL;
1214
        } else {
1215 4
            $style = isset($this->cssStyles['table.sheet' . $sheetIndex . ' tr.row' . $pRow])
1216 4
                ? $this->assembleCSS($this->cssStyles['table.sheet' . $sheetIndex . ' tr.row' . $pRow]) : '';
1217
1218 4
            $html .= '          <tr style="' . $style . '">' . PHP_EOL;
1219
        }
1220
1221
        // Write cells
1222 13
        $colNum = 0;
1223 13
        foreach ($pValues as $cellAddress) {
1224 13
            $cell = ($cellAddress > '') ? $pSheet->getCell($cellAddress) : '';
1225 13
            $coordinate = Coordinate::stringFromColumnIndex($colNum + 1) . ($pRow + 1);
1226 13
            if (!$this->useInlineCss) {
1227 10
                $cssClass = 'column' . $colNum;
1228
            } else {
1229 4
                $cssClass = [];
1230 4
                if ($cellType == 'th') {
1231
                    if (isset($this->cssStyles['table.sheet' . $sheetIndex . ' th.column' . $colNum])) {
1232
                        $this->cssStyles['table.sheet' . $sheetIndex . ' th.column' . $colNum];
1233
                    }
1234
                } else {
1235 4
                    if (isset($this->cssStyles['table.sheet' . $sheetIndex . ' td.column' . $colNum])) {
1236
                        $this->cssStyles['table.sheet' . $sheetIndex . ' td.column' . $colNum];
1237
                    }
1238
                }
1239
            }
1240 13
            $colSpan = 1;
1241 13
            $rowSpan = 1;
1242
1243
            // initialize
1244 13
            $cellData = '&nbsp;';
1245
1246
            // Cell
1247 13
            if ($cell instanceof Cell) {
1248 13
                $cellData = '';
1249 13
                if ($cell->getParent() === null) {
1250
                    $cell->attach($pSheet);
1251
                }
1252
                // Value
1253 13
                if ($cell->getValue() instanceof RichText) {
1254
                    // Loop through rich text elements
1255 5
                    $elements = $cell->getValue()->getRichTextElements();
1256 5
                    foreach ($elements as $element) {
1257
                        // Rich text start?
1258 5
                        if ($element instanceof Run) {
1259 5
                            $cellData .= '<span style="' . $this->assembleCSS($this->createCSSStyleFont($element->getFont())) . '">';
1260
1261 5
                            if ($element->getFont()->getSuperscript()) {
1262
                                $cellData .= '<sup>';
1263 5
                            } elseif ($element->getFont()->getSubscript()) {
1264
                                $cellData .= '<sub>';
1265
                            }
1266
                        }
1267
1268
                        // Convert UTF8 data to PCDATA
1269 5
                        $cellText = $element->getText();
1270 5
                        $cellData .= htmlspecialchars($cellText);
1271
1272 5
                        if ($element instanceof Run) {
1273 5
                            if ($element->getFont()->getSuperscript()) {
1274
                                $cellData .= '</sup>';
1275 5
                            } elseif ($element->getFont()->getSubscript()) {
1276
                                $cellData .= '</sub>';
1277
                            }
1278
1279 5
                            $cellData .= '</span>';
1280
                        }
1281
                    }
1282
                } else {
1283 13
                    if ($this->preCalculateFormulas) {
1284 13
                        $cellData = NumberFormat::toFormattedString(
1285 13
                            $cell->getCalculatedValue(),
1286 13
                            $pSheet->getParent()->getCellXfByIndex($cell->getXfIndex())->getNumberFormat()->getFormatCode(),
1287 13
                            [$this, 'formatColor']
1288
                        );
1289
                    } else {
1290
                        $cellData = NumberFormat::toFormattedString(
1291
                            $cell->getValue(),
1292
                            $pSheet->getParent()->getCellXfByIndex($cell->getXfIndex())->getNumberFormat()->getFormatCode(),
1293
                            [$this, 'formatColor']
1294
                        );
1295
                    }
1296 13
                    $cellData = htmlspecialchars($cellData);
1297 13
                    if ($pSheet->getParent()->getCellXfByIndex($cell->getXfIndex())->getFont()->getSuperscript()) {
1298
                        $cellData = '<sup>' . $cellData . '</sup>';
1299 13
                    } elseif ($pSheet->getParent()->getCellXfByIndex($cell->getXfIndex())->getFont()->getSubscript()) {
1300
                        $cellData = '<sub>' . $cellData . '</sub>';
1301
                    }
1302
                }
1303
1304
                // Converts the cell content so that spaces occuring at beginning of each new line are replaced by &nbsp;
1305
                // Example: "  Hello\n to the world" is converted to "&nbsp;&nbsp;Hello\n&nbsp;to the world"
1306 13
                $cellData = preg_replace('/(?m)(?:^|\\G) /', '&nbsp;', $cellData);
1307
1308
                // convert newline "\n" to '<br>'
1309 13
                $cellData = nl2br($cellData);
1310
1311
                // Extend CSS class?
1312 13
                if (!$this->useInlineCss) {
1313 10
                    $cssClass .= ' style' . $cell->getXfIndex();
1314 10
                    $cssClass .= ' ' . $cell->getDataType();
1315
                } else {
1316 4
                    if ($cellType == 'th') {
1317
                        if (isset($this->cssStyles['th.style' . $cell->getXfIndex()])) {
1318
                            $cssClass = array_merge($cssClass, $this->cssStyles['th.style' . $cell->getXfIndex()]);
1319
                        }
1320
                    } else {
1321 4
                        if (isset($this->cssStyles['td.style' . $cell->getXfIndex()])) {
1322 4
                            $cssClass = array_merge($cssClass, $this->cssStyles['td.style' . $cell->getXfIndex()]);
1323
                        }
1324
                    }
1325
1326
                    // General horizontal alignment: Actual horizontal alignment depends on dataType
1327 4
                    $sharedStyle = $pSheet->getParent()->getCellXfByIndex($cell->getXfIndex());
1328 4
                    if ($sharedStyle->getAlignment()->getHorizontal() == Alignment::HORIZONTAL_GENERAL
1329 4
                        && isset($this->cssStyles['.' . $cell->getDataType()]['text-align'])
1330
                    ) {
1331 4
                        $cssClass['text-align'] = $this->cssStyles['.' . $cell->getDataType()]['text-align'];
1332
                    }
1333
                }
1334
            }
1335
1336
            // Hyperlink?
1337 13
            if ($pSheet->hyperlinkExists($coordinate) && !$pSheet->getHyperlink($coordinate)->isInternal()) {
1338 4
                $cellData = '<a href="' . htmlspecialchars($pSheet->getHyperlink($coordinate)->getUrl()) . '" title="' . htmlspecialchars($pSheet->getHyperlink($coordinate)->getTooltip()) . '">' . $cellData . '</a>';
1339
            }
1340
1341
            // Should the cell be written or is it swallowed by a rowspan or colspan?
1342 13
            $writeCell = !(isset($this->isSpannedCell[$pSheet->getParent()->getIndex($pSheet)][$pRow + 1][$colNum])
1343 13
                && $this->isSpannedCell[$pSheet->getParent()->getIndex($pSheet)][$pRow + 1][$colNum]);
1344
1345
            // Colspan and Rowspan
1346 13
            $colspan = 1;
1347 13
            $rowspan = 1;
1348 13
            if (isset($this->isBaseCell[$pSheet->getParent()->getIndex($pSheet)][$pRow + 1][$colNum])) {
1349 6
                $spans = $this->isBaseCell[$pSheet->getParent()->getIndex($pSheet)][$pRow + 1][$colNum];
1350 6
                $rowSpan = $spans['rowspan'];
1351 6
                $colSpan = $spans['colspan'];
1352
1353
                //    Also apply style from last cell in merge to fix borders -
1354
                //        relies on !important for non-none border declarations in createCSSStyleBorder
1355 6
                $endCellCoord = Coordinate::stringFromColumnIndex($colNum + $colSpan) . ($pRow + $rowSpan);
1356 6
                if (!$this->useInlineCss) {
1357 3
                    $cssClass .= ' style' . $pSheet->getCell($endCellCoord)->getXfIndex();
1358
                }
1359
            }
1360
1361
            // Write
1362 13
            if ($writeCell) {
1363
                // Column start
1364 13
                $html .= '            <' . $cellType;
1365 13
                if (!$this->useInlineCss) {
1366 10
                    $html .= ' class="' . $cssClass . '"';
1367
                } else {
1368
                    //** Necessary redundant code for the sake of \PhpOffice\PhpSpreadsheet\Writer\Pdf **
1369
                    // We must explicitly write the width of the <td> element because TCPDF
1370
                    // does not recognize e.g. <col style="width:42pt">
1371 4
                    $width = 0;
1372 4
                    $i = $colNum - 1;
1373 4
                    $e = $colNum + $colSpan - 1;
1374 4
                    while ($i++ < $e) {
1375 4
                        if (isset($this->columnWidths[$sheetIndex][$i])) {
1376 4
                            $width += $this->columnWidths[$sheetIndex][$i];
1377
                        }
1378
                    }
1379 4
                    $cssClass['width'] = $width . 'pt';
1380
1381
                    // We must also explicitly write the height of the <td> element because TCPDF
1382
                    // does not recognize e.g. <tr style="height:50pt">
1383 4
                    if (isset($this->cssStyles['table.sheet' . $sheetIndex . ' tr.row' . $pRow]['height'])) {
1384 1
                        $height = $this->cssStyles['table.sheet' . $sheetIndex . ' tr.row' . $pRow]['height'];
1385 1
                        $cssClass['height'] = $height;
1386
                    }
1387
                    //** end of redundant code **
1388
1389 4
                    $html .= ' style="' . $this->assembleCSS($cssClass) . '"';
1390
                }
1391 13
                if ($colSpan > 1) {
1392 6
                    $html .= ' colspan="' . $colSpan . '"';
1393
                }
1394 13
                if ($rowSpan > 1) {
1395
                    $html .= ' rowspan="' . $rowSpan . '"';
1396
                }
1397 13
                $html .= '>';
1398
1399 13
                $html .= $this->writeComment($pSheet, $coordinate);
1400
1401
                // Image?
1402 13
                $html .= $this->writeImageInCell($pSheet, $coordinate);
1403
1404
                // Chart?
1405 13
                if ($this->includeCharts) {
1406
                    $html .= $this->writeChartInCell($pSheet, $coordinate);
1407
                }
1408
1409
                // Cell data
1410 13
                $html .= $cellData;
1411
1412
                // Column end
1413 13
                $html .= '</' . $cellType . '>' . PHP_EOL;
1414
            }
1415
1416
            // Next column
1417 13
            ++$colNum;
1418
        }
1419
1420
        // Write row end
1421 13
        $html .= '          </tr>' . PHP_EOL;
1422
1423
        // Return
1424 13
        return $html;
1425
    }
1426
1427
    /**
1428
     * Takes array where of CSS properties / values and converts to CSS string.
1429
     *
1430
     * @param array $pValue
1431
     *
1432
     * @return string
1433
     */
1434 13
    private function assembleCSS(array $pValue = [])
1435
    {
1436 13
        $pairs = [];
1437 13
        foreach ($pValue as $property => $value) {
1438 13
            $pairs[] = $property . ':' . $value;
1439
        }
1440 13
        $string = implode('; ', $pairs);
1441
1442 13
        return $string;
1443
    }
1444
1445
    /**
1446
     * Get images root.
1447
     *
1448
     * @return string
1449
     */
1450 4
    public function getImagesRoot()
1451
    {
1452 4
        return $this->imagesRoot;
1453
    }
1454
1455
    /**
1456
     * Set images root.
1457
     *
1458
     * @param string $pValue
1459
     *
1460
     * @return HTML
1461
     */
1462
    public function setImagesRoot($pValue)
1463
    {
1464
        $this->imagesRoot = $pValue;
1465
1466
        return $this;
1467
    }
1468
1469
    /**
1470
     * Get embed images.
1471
     *
1472
     * @return bool
1473
     */
1474
    public function getEmbedImages()
1475
    {
1476
        return $this->embedImages;
1477
    }
1478
1479
    /**
1480
     * Set embed images.
1481
     *
1482
     * @param bool $pValue
1483
     *
1484
     * @return HTML
1485
     */
1486
    public function setEmbedImages($pValue)
1487
    {
1488
        $this->embedImages = $pValue;
1489
1490
        return $this;
1491
    }
1492
1493
    /**
1494
     * Get use inline CSS?
1495
     *
1496
     * @return bool
1497
     */
1498
    public function getUseInlineCss()
1499
    {
1500
        return $this->useInlineCss;
1501
    }
1502
1503
    /**
1504
     * Set use inline CSS?
1505
     *
1506
     * @param bool $pValue
1507
     *
1508
     * @return HTML
1509
     */
1510 8
    public function setUseInlineCss($pValue)
1511
    {
1512 8
        $this->useInlineCss = $pValue;
1513
1514 8
        return $this;
1515
    }
1516
1517
    /**
1518
     * Add color to formatted string as inline style.
1519
     *
1520
     * @param string $pValue Plain formatted value without color
1521
     * @param string $pFormat Format code
1522
     *
1523
     * @return string
1524
     */
1525 4
    public function formatColor($pValue, $pFormat)
1526
    {
1527
        // Color information, e.g. [Red] is always at the beginning
1528 4
        $color = null; // initialize
1529 4
        $matches = [];
1530
1531 4
        $color_regex = '/^\\[[a-zA-Z]+\\]/';
1532 4
        if (preg_match($color_regex, $pFormat, $matches)) {
1533
            $color = str_replace(['[', ']'], '', $matches[0]);
1534
            $color = strtolower($color);
1535
        }
1536
1537
        // convert to PCDATA
1538 4
        $value = htmlspecialchars($pValue);
1539
1540
        // color span tag
1541 4
        if ($color !== null) {
1542
            $value = '<span style="color:' . $color . '">' . $value . '</span>';
1543
        }
1544
1545 4
        return $value;
1546
    }
1547
1548
    /**
1549
     * Calculate information about HTML colspan and rowspan which is not always the same as Excel's.
1550
     */
1551 13
    private function calculateSpans()
1552
    {
1553
        // Identify all cells that should be omitted in HTML due to cell merge.
1554
        // In HTML only the upper-left cell should be written and it should have
1555
        //   appropriate rowspan / colspan attribute
1556 13
        $sheetIndexes = $this->sheetIndex !== null ?
1557 13
            [$this->sheetIndex] : range(0, $this->spreadsheet->getSheetCount() - 1);
1558
1559 13
        foreach ($sheetIndexes as $sheetIndex) {
1560 13
            $sheet = $this->spreadsheet->getSheet($sheetIndex);
1561
1562 13
            $candidateSpannedRow = [];
1563
1564
            // loop through all Excel merged cells
1565 13
            foreach ($sheet->getMergeCells() as $cells) {
1566 6
                list($cells) = Coordinate::splitRange($cells);
1567 6
                $first = $cells[0];
1568 6
                $last = $cells[1];
1569
1570 6
                list($fc, $fr) = Coordinate::coordinateFromString($first);
1571 6
                $fc = Coordinate::columnIndexFromString($fc) - 1;
1572
1573 6
                list($lc, $lr) = Coordinate::coordinateFromString($last);
1574 6
                $lc = Coordinate::columnIndexFromString($lc) - 1;
1575
1576
                // loop through the individual cells in the individual merge
1577 6
                $r = $fr - 1;
1578 6
                while ($r++ < $lr) {
1579
                    // also, flag this row as a HTML row that is candidate to be omitted
1580 6
                    $candidateSpannedRow[$r] = $r;
1581
1582 6
                    $c = $fc - 1;
1583 6
                    while ($c++ < $lc) {
1584 6
                        if (!($c == $fc && $r == $fr)) {
1585
                            // not the upper-left cell (should not be written in HTML)
1586 6
                            $this->isSpannedCell[$sheetIndex][$r][$c] = [
1587 6
                                'baseCell' => [$fr, $fc],
1588
                            ];
1589
                        } else {
1590
                            // upper-left is the base cell that should hold the colspan/rowspan attribute
1591 6
                            $this->isBaseCell[$sheetIndex][$r][$c] = [
1592 6
                                'xlrowspan' => $lr - $fr + 1, // Excel rowspan
1593 6
                                'rowspan' => $lr - $fr + 1, // HTML rowspan, value may change
1594 6
                                'xlcolspan' => $lc - $fc + 1, // Excel colspan
1595 6
                                'colspan' => $lc - $fc + 1, // HTML colspan, value may change
1596
                            ];
1597
                        }
1598
                    }
1599
                }
1600
            }
1601
1602
            // Identify which rows should be omitted in HTML. These are the rows where all the cells
1603
            //   participate in a merge and the where base cells are somewhere above.
1604 13
            $countColumns = Coordinate::columnIndexFromString($sheet->getHighestColumn());
1605 13
            foreach ($candidateSpannedRow as $rowIndex) {
1606 6
                if (isset($this->isSpannedCell[$sheetIndex][$rowIndex])) {
1607 6
                    if (count($this->isSpannedCell[$sheetIndex][$rowIndex]) == $countColumns) {
1608 6
                        $this->isSpannedRow[$sheetIndex][$rowIndex] = $rowIndex;
1609
                    }
1610
                }
1611
            }
1612
1613
            // For each of the omitted rows we found above, the affected rowspans should be subtracted by 1
1614 13
            if (isset($this->isSpannedRow[$sheetIndex])) {
1615 4
                foreach ($this->isSpannedRow[$sheetIndex] as $rowIndex) {
1616 4
                    $adjustedBaseCells = [];
1617 4
                    $c = -1;
1618 4
                    $e = $countColumns - 1;
1619 13
                    while ($c++ < $e) {
1620 4
                        $baseCell = $this->isSpannedCell[$sheetIndex][$rowIndex][$c]['baseCell'];
1621
1622 4
                        if (!in_array($baseCell, $adjustedBaseCells)) {
1623
                            // subtract rowspan by 1
1624 4
                            --$this->isBaseCell[$sheetIndex][$baseCell[0]][$baseCell[1]]['rowspan'];
1625 4
                            $adjustedBaseCells[] = $baseCell;
1626
                        }
1627
                    }
1628
                }
1629
            }
1630
1631
            // TODO: Same for columns
1632
        }
1633
1634
        // We have calculated the spans
1635 13
        $this->spansAreCalculated = true;
1636 13
    }
1637
1638 13
    private function setMargins(Worksheet $pSheet)
1639
    {
1640 13
        $htmlPage = '@page { ';
1641 13
        $htmlBody = 'body { ';
1642
1643 13
        $left = StringHelper::formatNumber($pSheet->getPageMargins()->getLeft()) . 'in; ';
1644 13
        $htmlPage .= 'margin-left: ' . $left;
1645 13
        $htmlBody .= 'margin-left: ' . $left;
1646 13
        $right = StringHelper::formatNumber($pSheet->getPageMargins()->getRight()) . 'in; ';
1647 13
        $htmlPage .= 'margin-right: ' . $right;
1648 13
        $htmlBody .= 'margin-right: ' . $right;
1649 13
        $top = StringHelper::formatNumber($pSheet->getPageMargins()->getTop()) . 'in; ';
1650 13
        $htmlPage .= 'margin-top: ' . $top;
1651 13
        $htmlBody .= 'margin-top: ' . $top;
1652 13
        $bottom = StringHelper::formatNumber($pSheet->getPageMargins()->getBottom()) . 'in; ';
1653 13
        $htmlPage .= 'margin-bottom: ' . $bottom;
1654 13
        $htmlBody .= 'margin-bottom: ' . $bottom;
1655
1656 13
        $htmlPage .= "}\n";
1657 13
        $htmlBody .= "}\n";
1658
1659 13
        return "<style>\n" . $htmlPage . $htmlBody . "</style>\n";
1660
    }
1661
1662
    /**
1663
     * Write a comment in the same format as LibreOffice.
1664
     *
1665
     * @see https://github.com/LibreOffice/core/blob/9fc9bf3240f8c62ad7859947ab8a033ac1fe93fa/sc/source/filter/html/htmlexp.cxx#L1073-L1092
1666
     *
1667
     * @param Worksheet $pSheet
1668
     * @param string $coordinate
1669
     *
1670
     * @return string
1671
     */
1672 13
    private function writeComment(Worksheet $pSheet, $coordinate)
1673
    {
1674 13
        $result = '';
1675 13
        if (!$this->isPdf && isset($pSheet->getComments()[$coordinate])) {
1676 6
            $result .= '<a class="comment-indicator"></a>';
1677 6
            $result .= '<div class="comment">' . nl2br($pSheet->getComment($coordinate)->getText()->getPlainText()) . '</div>';
1678 6
            $result .= PHP_EOL;
1679
        }
1680
1681 13
        return $result;
1682
    }
1683
}
1684