diff --git a/src/Smalot/PdfParser/Font.php b/src/Smalot/PdfParser/Font.php index b6207bb8..2e05cff5 100644 --- a/src/Smalot/PdfParser/Font.php +++ b/src/Smalot/PdfParser/Font.php @@ -283,7 +283,9 @@ public function calculateTextWidth(string $text, array &$missing = null): ?float { $index_map = array_flip($this->table); $details = $this->getDetails(); - $widths = $details['Widths']; + + // Usually, Widths key is set in $details array, but if it isn't use an empty array instead. + $widths = $details['Widths'] ?? []; // Widths array is zero indexed but table is not. We must map them based on FirstChar and LastChar $width_map = array_flip(range($details['FirstChar'], $details['LastChar'])); diff --git a/tests/PHPUnit/Integration/FontTest.php b/tests/PHPUnit/Integration/FontTest.php index c1aeabba..e76a051d 100644 --- a/tests/PHPUnit/Integration/FontTest.php +++ b/tests/PHPUnit/Integration/FontTest.php @@ -454,6 +454,29 @@ public function testCalculateTextWidth(): void $this->assertEquals([], $missing); } + /** + * Check behavior if getDetails() does return an array without a Widths-key. + * + * @see https://github.com/smalot/pdfparser/issues/619 + */ + public function testCalculateTextWidthNoWidthsKey(): void + { + $document = $this->createMock(Document::class); + + $header = $this->createMock(Header::class); + $header->method('getDetails')->willReturn([ + 'FirstChar' => '', + 'LastChar' => '', + // 'Widths' key is not set, so without the fix in Font.php a warning would be thrown. + ]); + + $font = new Font($document, $header); + $font->setTable([]); + $width = $font->calculateTextWidth('foo'); + + $this->assertNull($width); + } + /** * Check behavior if iconv function gets input which contains illegal characters. *