Skip to content

Commit 891a3cf

Browse files
committed
chore: Add document page sizes method to extract layout faster
1 parent 590690c commit 891a3cf

2 files changed

Lines changed: 61 additions & 0 deletions

File tree

src/Document.php

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,36 @@ public function getPageCount(): int
3636
return $this->ffi->FPDF_GetPageCount($this->handler);
3737
}
3838

39+
public function getPageSizeByIndex(int $pageIndex): ?Size
40+
{
41+
$size = $this->ffi->new('FS_SIZEF');
42+
43+
$result = $this->ffi->FPDF_GetPageSizeByIndexF(
44+
$this->handler,
45+
$pageIndex,
46+
\FFI::addr($size),
47+
);
48+
49+
if (0 === $result) {
50+
return null;
51+
}
52+
53+
return new Size(
54+
$size->width,
55+
$size->height,
56+
);
57+
}
58+
59+
/**
60+
* @return list<Size>
61+
*/
62+
public function pageSizeIterator(): iterable
63+
{
64+
for ($index = 0; $index < $this->getPagesCount(); ++$index) {
65+
yield $this->getPageSizeByIndex($index);
66+
}
67+
}
68+
3969
public function loadPage(int $pageIndex): ?Page
4070
{
4171
$pageHandler = $this->ffi->FPDF_LoadPage($this->handler, $pageIndex);

tests/unit/DocumentTest.php

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,37 @@ public function testRenderAllPagesIterable(): void
3838
self::assertCount(38, $files);
3939
}
4040

41+
public function testGetPageSizeByIndex(): void
42+
{
43+
$notice = $this->loadDocument('notice');
44+
$size = $notice->getPageSizeByIndex(0);
45+
self::assertSame(595, (int)$size->width);
46+
self::assertSame(841, (int)$size->height);
47+
48+
$badIndex = $notice->getPageSizeByIndex(-5);
49+
self::assertNull($badIndex);
50+
51+
$badIndex2 = $notice->getPageSizeByIndex(1000);
52+
self::assertNull($badIndex2);
53+
}
54+
55+
public function testPageSizeIterator()
56+
{
57+
$layout = [];
58+
$notice = $this->loadDocument('yolo');
59+
foreach ($notice->pageSizeIterator() as $size) {
60+
$layout[] = [
61+
'width' => (int)$size->width,
62+
'height' => (int)$size->height,
63+
];
64+
}
65+
self::assertCount(36, $layout);
66+
foreach ($layout as $pageSize) {
67+
self::assertSame(595, $pageSize['width']);
68+
self::assertSame(841, $pageSize['height']);
69+
}
70+
}
71+
4172
public function testSaveFlattenedCopy(): void
4273
{
4374
$cerfaDoc = $this->loadDocument('cerfa_13750-05');

0 commit comments

Comments
 (0)