Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Font.php: hot fix for calculateTextWidth in case Widths key is not set #645

Merged
merged 3 commits into from
Oct 2, 2023
Merged
Show file tree
Hide file tree
Changes from 2 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
4 changes: 3 additions & 1 deletion src/Smalot/PdfParser/Font.php
Original file line number Diff line number Diff line change
Expand Up @@ -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'];

// TODO: Temporary fix, in the rare case the Widths-key is not set in $details array.
k00ni marked this conversation as resolved.
Show resolved Hide resolved
$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']));
Expand Down
23 changes: 23 additions & 0 deletions tests/PHPUnit/Integration/FontTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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.
*
Expand Down