Skip to content

Commit

Permalink
Init
Browse files Browse the repository at this point in the history
  • Loading branch information
janbarasek committed Nov 12, 2019
0 parents commit 1b6f44b
Show file tree
Hide file tree
Showing 4 changed files with 206 additions and 0 deletions.
24 changes: 24 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
PDF to image convertor
======================

Convert PDF to image and save to disk. Convert PDF to JPG, PNG or GIF in PHP.

Install
-------

By Composer:

```shell
composer require baraja-core/php-pdf-to-image
```

Usage
-----

```php
$pdfPath = __DIR__ . '/example.pdf';
$imagePath = __DIR__ . '/example.jpg';

// Render PDF to image and save to disk.
\Baraja\PdfToImage\Convertor::convert($pdfPath, $imagePath, 'jpg');
```
21 changes: 21 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
"name": "baraja-core/php-pdf-to-image",
"description": "Convert PDF to JPG, PNG or GIF in PHP.",
"homepage": "https://github.com/baraja-core/php-pdf-to-image",
"authors": [
{
"name": "Jan Barášek",
"homepage": "https://baraja.cz"
}
],
"require": {
"php": ">=7.1.0",
"ext-imagick": "*"
},
"autoload": {
"classmap": [
"src/"
]
},
"minimum-stability": "stable"
}
121 changes: 121 additions & 0 deletions src/Convertor.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
<?php

declare(strict_types=1);

namespace Baraja\PdfToImage;


final class Convertor
{

public const FORMAT_JPG = 'jpg';
public const FORMAT_PNG = 'png';
public const FORMAT_GIF = 'gif';

public const SUPPORTED_FORMATS = [self::FORMAT_JPG, self::FORMAT_PNG, self::FORMAT_GIF];

/**
* @throws \Error
*/
public function __construct()
{
throw new \Error('Class ' . get_class($this) . ' is static and cannot be instantiated.');
}

/**
* Convert first page of PDF to image and save to disk.
*
* @param string $pdfPath
* @param string $savePath
* @param string $format
* @param bool $trim
* @throws ConvertorException
*/
public static function convert(string $pdfPath, string $savePath, string $format = 'jpg', bool $trim = false): void
{
if (\in_array($format = strtolower($format), self::SUPPORTED_FORMATS, true) === false) {
ConvertorException::unsupportedFormat($format);
}

if (\is_file($pdfPath) === false) {
ConvertorException::fileDoesNotExist($pdfPath);
}

try {
$im = self::process($pdfPath, $savePath);

if ($trim === true) {
$im->setImageBorderColor('rgb(255,255,255)');
$im->trimImage(1);
self::write($savePath, (string) $im);
}
} catch (\ImagickException $e) {
throw new ConvertorException($e->getMessage(), $e->getCode(), $e);
}
}

/**
* @param string $pdfPath
* @param string $savePath
* @return \Imagick
* @throws ConvertorException|\ImagickException
*/
private static function process(string $pdfPath, string $savePath): \Imagick
{
if (class_exists('\imagick') === false) {
ConvertorException::imagicKIsNotInstalled();
}

$im = new \imagick($pdfPath);
$im->setImageFormat('jpg');
self::write($savePath, (string) $im);

return $im;
}

/**
* Writes a string to a file.
* Moved from nette/utils
*
* @param string $file
* @param string $content
* @param int|null $mode
* @throws ConvertorException
*/
private static function write(string $file, string $content, ?int $mode = 0666): void
{
static::createDir(dirname($file));
if (@file_put_contents($file, $content) === false) { // @ is escalated to exception
throw new ConvertorException('Unable to write file "' . $file . '": ' . self::getLastError());
}
if ($mode !== null && !@chmod($file, $mode)) { // @ is escalated to exception
throw new ConvertorException('Unable to chmod file "' . $file . '": ' . self::getLastError());
}
}

/**
* Creates a directory.
* Moved from nette/utils
*
* @param string $dir
* @param int $mode
* @throws ConvertorException
*/
private static function createDir(string $dir, int $mode = 0777): void
{
if (!is_dir($dir) && !@mkdir($dir, $mode, true) && !is_dir($dir)) { // @ - dir may already exist
throw new ConvertorException('Unable to create directory "' . $dir . '": ' . self::getLastError());
}
}

/**
* Moved from nette/utils
*
* @return string
*/
private static function getLastError(): string
{
return preg_replace('#^\w+\(.*?\): #', '', error_get_last()['message']);
}

}
40 changes: 40 additions & 0 deletions src/ConvertorException.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<?php

declare(strict_types=1);

namespace Baraja\PdfToImage;


final class ConvertorException extends \Exception
{

/**
* @param string $path
* @throws ConvertorException
*/
public static function fileDoesNotExist(string $path): void
{
throw new self('File "' . $path . '" does not exist.');
}

/**
* @param string $format
* @throws ConvertorException
*/
public static function unsupportedFormat(string $format): void
{
throw new self(
'Format "' . $format . '" is not supported. '
. 'Did you mean "' . implode('", "', Convertor::SUPPORTED_FORMATS) . '"?'
);
}

/**
* @throws ConvertorException
*/
public static function imagicKIsNotInstalled(): void
{
throw new self('Imagick is not installed.');
}

}

0 comments on commit 1b6f44b

Please sign in to comment.