This package provides a wrapper for pdftoppm
.
\Ottosmops\Pdftothumb\Converter::create('/path/to/file.pdf')->convert();
//creates a thumb of the first page: '/path/to/file.jpg'
We use this as an alternative to the excellent spatie/pdf-to-image package as we sometimes have large PDFs to convert and then it seems to be faster and more memory friendly to use pdftoppm.
The Package uses pdftoppm. Make sure that this is installed: which pdftoppm
For Installation see: poppler-utils
If the installed binary is not found ("The command "which pdftoppm" failed.
") you can pass the full path to the _constructor
(see below) or use putenv('PATH=$PATH:/usr/local/bin/:/usr/bin')
(with the dir where pdftoppm lives) before you call the class Converter
.
composer require ottosmops/pdftothumb
Converting PDF to jpg:
$exitCode = (new Converter($source, $target, $executable))->convert();
$target
and $executable
are optional.
Or like this:
$converter = Converter::create($source);
$converter->convert()
You can set some options:
Converter::create('/path/to/source.pdf')
->target('/path/to/target.jpg')
->executable('path/to/pdftoppm')
->format('jpeg') // jpeg | png | tiff
->scaleTo(150)
->page(1) // or ->firstpage(1)->lastpage(1)
->convert();
You can add options:
Converter::create('/path/to/source.pdf')
->addOption('-gray')
->convert();
Or you can replace all options and set them by hand:
Converter::create('/path/to/source.pdf')
->setOptions('-f 3 -l 3 -scale-to 200 -png')
->convert();
Default options are: -f 1 -l 1 -scale-to 150 -jpeg
Tell the medialibrary not to use the standard ImageGenarator.
config/medialibrary.php
/*
* These generators will be used to created conversion of media files.
*/
'image_generators' => [
Spatie\MediaLibrary\ImageGenerators\FileTypes\Image::class ,
//Spatie\MediaLibrary\ImageGenerators\FileTypes\Pdf::class ,
Spatie\MediaLibrary\ImageGenerators\FileTypes\Svg::class ,
Spatie\MediaLibrary\ImageGenerators\FileTypes\Video::class ,
],
Create a new ImageGenerator
app/ImageGenarators/Pdf.php
<?php
namespace App\ImageGenerators;
use Illuminate\Support\Collection;
use Spatie\MediaLibrary\Conversion\Conversion;
use Spatie\MediaLibrary\ImageGenerators\BaseGenerator;
use Ottosmops\Pdftothumb\Converter;
class Pdf extends BaseGenerator
{
/**
* This function should return a path to an image representation of the given file.
*/
public function convert(string $path, Conversion $conversion = null) : string
{
$imageFile = pathinfo($path, PATHINFO_DIRNAME).'/'.pathinfo($path, PATHINFO_FILENAME).'.jpg';
Converter::create($path)->target($imageFile)->convert();
return $imageFile;
}
public function requirementsAreInstalled() : bool
{
return true;
}
public function supportedExtensions() : Collection
{
return collect(['pdf']);
}
public function supportedMimeTypes() : Collection
{
return collect('application/pdf');
}
}
The MIT License (MIT). Please see License File for more information.