<?php
namespace PhpOffice\PhpSpreadsheet\Writer\Pdf;
use PhpOffice\PhpSpreadsheet\Worksheet\PageSetup;
use PhpOffice\PhpSpreadsheet\Writer\Pdf;
class Mpdf extends Pdf
{
protected function createExternalWriterInstance($config)
{
return new \Mpdf\Mpdf($config);
}
public function save($pFilename): void
{
$fileHandle = parent::prepareForSave($pFilename);
$paperSize = 'LETTER';
if (null === $this->getSheetIndex()) {
$orientation = ($this->spreadsheet->getSheet(0)->getPageSetup()->getOrientation()
== PageSetup::ORIENTATION_LANDSCAPE) ? 'L' : 'P';
$printPaperSize = $this->spreadsheet->getSheet(0)->getPageSetup()->getPaperSize();
} else {
$orientation = ($this->spreadsheet->getSheet($this->getSheetIndex())->getPageSetup()->getOrientation()
== PageSetup::ORIENTATION_LANDSCAPE) ? 'L' : 'P';
$printPaperSize = $this->spreadsheet->getSheet($this->getSheetIndex())->getPageSetup()->getPaperSize();
}
$this->setOrientation($orientation);
if (null !== $this->getOrientation()) {
$orientation = ($this->getOrientation() == PageSetup::ORIENTATION_DEFAULT)
? PageSetup::ORIENTATION_PORTRAIT
: $this->getOrientation();
}
$orientation = strtoupper($orientation);
if (null !== $this->getPaperSize()) {
$printPaperSize = $this->getPaperSize();
}
if (isset(self::$paperSizes[$printPaperSize])) {
$paperSize = self::$paperSizes[$printPaperSize];
}
$config = ['tempDir' => $this->tempDir . '/mpdf'];
$pdf = $this->createExternalWriterInstance($config);
$ortmp = $orientation;
$pdf->_setPageSize($paperSize, $ortmp);
$pdf->DefOrientation = $orientation;
$pdf->AddPageByArray([
'orientation' => $orientation,
'margin-left' => $this->inchesToMm($this->spreadsheet->getActiveSheet()->getPageMargins()->getLeft()),
'margin-right' => $this->inchesToMm($this->spreadsheet->getActiveSheet()->getPageMargins()->getRight()),
'margin-top' => $this->inchesToMm($this->spreadsheet->getActiveSheet()->getPageMargins()->getTop()),
'margin-bottom' => $this->inchesToMm($this->spreadsheet->getActiveSheet()->getPageMargins()->getBottom()),
]);
$pdf->SetTitle($this->spreadsheet->getProperties()->getTitle());
$pdf->SetAuthor($this->spreadsheet->getProperties()->getCreator());
$pdf->SetSubject($this->spreadsheet->getProperties()->getSubject());
$pdf->SetKeywords($this->spreadsheet->getProperties()->getKeywords());
$pdf->SetCreator($this->spreadsheet->getProperties()->getCreator());
$html = $this->generateHTMLAll();
foreach (\array_chunk(\explode(PHP_EOL, $html), 1000) as $lines) {
$pdf->WriteHTML(\implode(PHP_EOL, $lines));
}
fwrite($fileHandle, $pdf->Output('', 'S'));
parent::restoreStateAfterSave();
}
private function inchesToMm($inches)
{
return $inches * 25.4;
}
}