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

Try to use ghostscript directly for page count #171

Closed
wants to merge 3 commits into from
Closed
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
32 changes: 27 additions & 5 deletions src/Pdf.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,11 +35,7 @@ public function __construct(string $pdfFile)
throw new PdfDoesNotExist("File `{$pdfFile}` does not exist");
}

$this->imagick = new Imagick();

$this->imagick->pingImage($pdfFile);

$this->numberOfPages = $this->imagick->getNumberImages();
$this->numberOfPages = $this->getPdfPageCount($pdfFile);

$this->pdfFile = $pdfFile;
}
Expand Down Expand Up @@ -217,4 +213,30 @@ protected function determineOutputFormat(string $pathToImage): string

return $outputFormat;
}

protected function getPdfPageCount(string $pdfFile): int
{
$cmd = sprintf('gs -q -dNODISPLAY -c "(%s) (r) file runpdfbegin pdfpagecount = quit"', addslashes($pdfFile));

try {
$result = exec($cmd, $output, $return);

if ($return === 0) {
return (int) $result;
}

return $this->getImagickPdfPageCount($pdfFile);
} catch (\Exception $e) {
return $this->getImagickPdfPageCount($pdfFile);
}
}

protected function getImagickPdfPageCount(string $pdfFile): int
{
$this->imagick = new Imagick();

$this->imagick->pingImage($pdfFile);

return $this->imagick->getNumberImages();
}
}
15 changes: 15 additions & 0 deletions tests/PdfTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,21 @@ public function it_will_set_compression_quality()
$this->assertEquals(99, $imagick->getCompressionQuality());
}

/** @test */
public function it_will_correctly_return_the_number_of_pages_in_pdf_with_imagick_file()
{
$reflection = new \ReflectionMethod(Pdf::class, 'getImagickPdfPageCount');
$reflection->setAccessible(true);

$mock = $this->getMockBuilder(Pdf::class)
->disableOriginalConstructor()
->getMock();

$count = $reflection->invokeArgs($mock, [$this->multipageTestFile]);

$this->assertTrue($count === 3);
}

public function invalid_page_number_provider()
{
return [[5], [0], [-1]];
Expand Down