Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions src/PhpSpreadsheet/Writer/Pdf/Tcpdf.php
Original file line number Diff line number Diff line change
Expand Up @@ -30,9 +30,15 @@ public function __construct(Spreadsheet $spreadsheet)
*/
protected function createExternalWriterInstance(string $orientation, string $unit, $paperSize): \TCPDF
{
$this->defines();

return new \TCPDF($orientation, $unit, $paperSize);
}

protected function defines(): void
{
}

/**
* Save Spreadsheet to file.
*
Expand Down
27 changes: 27 additions & 0 deletions src/PhpSpreadsheet/Writer/Pdf/TcpdfNoDie.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
<?php

namespace PhpOffice\PhpSpreadsheet\Writer\Pdf;

class TcpdfNoDie extends Tcpdf
{
/**
* By default, Tcpdf will die sometimes rather than throwing exception.
* And this is controlled by a defined constant in the global namespace,
* not by an instance property. Ugh!
* Using this class instead of the class which it extends will probably
* be suitable for most users. But not for those who have customized
* their config file. Which is why this isn't the default, so that
* there is no breaking change for those users.
* Note that if both Tcpdf and TcpdfNoDie are used in the same process,
* the first one used "wins" the battle of the defines.
*/
protected function defines(): void
{
if (!defined('K_TCPDF_EXTERNAL_CONFIG')) {
define('K_TCPDF_EXTERNAL_CONFIG', true);
}
if (!defined('K_TCPDF_THROW_EXCEPTION_ERROR')) {
define('K_TCPDF_THROW_EXCEPTION_ERROR', true);
}
}
}
37 changes: 37 additions & 0 deletions tests/PhpSpreadsheetTests/Writer/Tcpdf/NoDieTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
<?php

namespace PhpOffice\PhpSpreadsheetTests\Writer\Tcpdf;

use Exception;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Pdf\TcpdfNoDie;
use PHPUnit\Framework\Attributes;

class NoDieTest extends \PHPUnit\Framework\TestCase
{
private Spreadsheet $spreadsheet;

protected function setUp(): void
{
$this->spreadsheet = new Spreadsheet();
}

protected function tearDown(): void
{
unset($this->spreadsheet);
}

// Separate processes because of global defined names
#[Attributes\RunInSeparateProcess]
#[Attributes\PreserveGlobalState(false)]
public function testExceptionRatherThanDie(): void
{
$this->expectException(Exception::class);
$this->expectExceptionMessage('Could not include font definition file');
$sheet = $this->spreadsheet->getActiveSheet();
$sheet->setCellValue('A1', 'cell');
$writer = new TcpdfNoDie($this->spreadsheet);
$writer->setFont('xyz');
$writer->save('php://memory');
}
}