Convert a pdf to an image

Overview

Convert a pdf to an image

Latest Version on Packagist Software License GitHub Workflow Status Quality Score StyleCI Total Downloads

This package provides an easy to work with class to convert PDF's to images.

Spatie is a webdesign agency in Antwerp, Belgium. You'll find an overview of all our open source projects on our website.

Support us

We invest a lot of resources into creating best in class open source packages. You can support us by buying one of our paid products.

We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on our contact page. We publish all received postcards on our virtual postcard wall.

Requirements

You should have Imagick and Ghostscript installed. See issues regarding Ghostscript.

Installation

The package can be installed via composer:

composer require spatie/pdf-to-image

Usage

Converting a pdf to an image is easy.

$pdf = new Spatie\PdfToImage\Pdf($pathToPdf);
$pdf->saveImage($pathToWhereImageShouldBeStored);

If the path you pass to saveImage has the extensions jpg, jpeg, or png the image will be saved in that format. Otherwise the output will be a jpg.

Other methods

You can get the total number of pages in the pdf:

$pdf->getNumberOfPages(); //returns an int

By default the first page of the pdf will be rendered. If you want to render another page you can do so:

$pdf->setPage(2)
    ->saveImage($pathToWhereImageShouldBeStored); //saves the second page

You can override the output format:

$pdf->setOutputFormat('png')
    ->saveImage($pathToWhereImageShouldBeStored); //the output wil be a png, no matter what

You can set the quality of compression from 0 to 100:

$pdf->setCompressionQuality(100); // sets the compression quality to maximum

Issues regarding Ghostscript

This package uses Ghostscript through Imagick. For this to work Ghostscripts gs command should be accessible from the PHP process. For the PHP CLI process (e.g. Laravel's asynchronous jobs, commands, etc...) this is usually already the case.

However for PHP on FPM (e.g. when running this package "in the browser") you might run into the following problem:

Uncaught ImagickException: FailedToExecuteCommand 'gs'

This can be fixed by adding the following line at the end of your php-fpm.conf file and restarting PHP FPM. If you're unsure where the php-fpm.conf file is located you can check phpinfo(). If you are using Laravel Valet the php-fpm.conf file will be located in the /usr/local/etc/php/YOUR-PHP-VERSION directory.

env[PATH] = /usr/local/bin:/usr/bin:/bin

This will instruct PHP FPM to look for the gs binary in the right places.

Testing

composer test

Changelog

Please see CHANGELOG for more information what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security

If you discover any security related issues, please email [email protected] instead of using the issue tracker.

Postcardware

You're free to use this package, but if it makes it to your production environment we highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using.

Our address is: Spatie, Kruikstraat 22, 2018 Antwerp, Belgium.

We publish all received postcards on our company website.

Credits

License

The MIT License (MIT). Please see License File for more information.

Comments
  • Failed to read file error

    Failed to read file error

    When converting a PDF (via Media Library Conversion) I get the error 'Failed to read file':

    "message": "Failed to read the file",
    "file": "/Users/samjones/Desktop/DEVELOPMENT/Safe/system/vendor/spatie/pdf-to-image/src/Pdf.php",
    "line": 40,
    "trace": [
        {
            "file": "/Users/samjones/Desktop/DEVELOPMENT/Safe/system/vendor/spatie/pdf-to-image/src/Pdf.php",
            "line": 40,
            "function": "__construct",
            "class": "Imagick",
            "type": "->",
            "args": [                   
    "/Users/samjones/Desktop/DEVELOPMENT/Safe/system/storage/medialibrary/temp/Vrc0otFnhMccJQ61BaGu96DUtVk1cwJs/c0ZJJdOuTNlTDeyZ.pdf"
            ]
        },
        ...
    ]
    

    File is there and permissions seem ok, PHP 7.1 and latest ImageMagick 7.0.7-0.

    Any ideas?

    UPDATE: after restarting the server and reinstalling ImageMagick I'm now getting an error with GhostScript (which presumable ImageMagick is delegating the conversion to.

    FailedToExecuteCommand 'gs' -sstdout=%stderr -dQUIET -dSAFER -dBATCH -dNOPAUSE -dNOPROMPT -dMaxBitmap=500000000 -dAlignToPixels=0 -dGridFitTT=2 '-sDEVICE=pngalpha' -dTextAlphaBits=4 -dGraphicsAlphaBits=4 '-r72x72' '-sOutputFile=/var/tmp/magick-266Xh1FBuVfcugv%d' '-f/var/tmp/magick-266OVALiKuMKxoy' '-f/var/tmp/magick-266dsJDEkjrkKzd'' (1) @ error/pdf.c/InvokePDFDelegate/291

    GhostScript is installed and working on the command line but it seems ImageMagick is struggling with it?!

    opened by slashequip 13
  • Wrong number of pages for native PDF

    Wrong number of pages for native PDF

    Hello !

    I'm having issues in a production environment with pdf-to-image, the package doesn't detect the good amount of pages in some files.

    The issue is very rare, and happens in less than 1% of the time and only with native PDFs

    See this issue #71

    Thank you,

    opened by Dylan-Duault 11
  • Wrong total of pages

    Wrong total of pages

    I want to convert all pages of a PDF files. The PDF is having 4 pages and this line of code gives me 16 pages for the same document, thus resulting in an exception error. $total_pages = $pdf->getNumberOfPages(); // 16 pages ??? there is only 4 in the document!

    Link to download this PDF file: https://agix-solution.com/temp/Predator-Ridges-Courses.pdf

    foreach (range(1, $pdf->getNumberOfPages()) as $pageNumber) { $src = $filename .'-'. $pageNumber.'.jpg'; $pdf->setPage($pageNumber); $pdf->saveImage($src); }

    I'm getting an exception: File: assets\pdf-to-image-1.4.5\src\Pdf.php Line #209 Message: Uncaught exception 'ImagickException' with message 'PDFDelegateFailed `[ghostscript library 9.20] Requested FirstPage is greater than the number of pages in the file: 4 No pages will be processed (FirstPage > LastPage). ' @ error/pdf.c/ReadPDFImage/801' in assets\pdf-to-image-1.4.5\src\Pdf.php:209

    EDIT: it seems only my localhost on Windows is affected. Live server on Centos get correctly 4 pages...

    opened by myrage18 10
  • First Image size is smaller then other Images

    First Image size is smaller then other Images

    I have used this extension for converting the pdf to image

    it converts perfectly every image but only issue is that first image is of the half resolution of the others

    what should be the problem??

    each and every variables are declared proper and also receives the values as well

    bug help wanted 
    opened by nitinjiniguru 10
  • Using saveImage on PDF makes background black

    Using saveImage on PDF makes background black

    I load up a PDF using $pdf = new Pdf($pathToPdf); and save it using $pdf->saveImage($pathToUploads);. It generates an image, but the background turns to black. Maybe this has to do with transparency?

    opened by AuditeMarlow 10
  • adding the ability to save more than one image

    adding the ability to save more than one image

    in the case of a file with multiple pages, this function will extract all the pages as images

    am not sure about the testing cause at the end it will need to save the files somewhere ..

    opened by zaherg 9
  • No GS-Path set

    No GS-Path set

    Hi, I'm facing this issue with normal use $pdf = new Pdf(asset('pdf/file.pdf')); $pdf->saveImage(asset('pdf'));

    I'm using windows and Xampp. I have installed imagemagick and ghostscript on my windows. What it is the issue now. Please help me. where I set the path.

    opened by rashidabbas7865 8
  • Class 'Imagick' not found

    Class 'Imagick' not found

    I've just taken over some code at work and run in to an issue with Imagick that I can't seem to fix. Currently running 2 versions of this code one for Laravel 4.2 then I've upgraded 90% of this app using Laravel Shift so we're now running 5.6 and this is the only thing I can't fix. It also has seemed to stop working for the Laravel 4.2 version on a local homestead.

    The version called in composer.json is "^1.2"

    Pdf.php

    public function getImageData($pathToImage)
          {
            $imagick = new \Imagick();
     
            $imagick->setResolution($this->resolution, $this->resolution);
     
            $imagick->readImage(sprintf('%s[%s]', $this->pdfFile, $this->page - 1));
     
            $imagick->mergeImageLayers(\Imagick::LAYERMETHOD_FLATTEN);
     
            $imagick->setFormat($this->determineOutputFormat($pathToImage));
     
            return $imagick;
        }
    

    Code I'm Debugging:

    if (pathinfo($attachement_path, PATHINFO_EXTENSION) == 'pdf') {
                    $pdf = new Pdf(public_path() . "/". $attachement_path);
                    $pdf->setResolution(264);
                    $pdf->saveImage(public_path() . "/" . 'attachment_path/' . pathinfo($attachement_path, PATHINFO_FILENAME) . '.jpg');
                }
    
    opened by mikerodham 8
  • Multiple Page to One Image

    Multiple Page to One Image

    Halo,

    I have to convert a transaction history that printed in two page pdf file. But when I convert it to jpg format, only the 1st page that converted to the image.

    opened by pararang 6
  • PHP out of memory and killing PHP process

    PHP out of memory and killing PHP process

    Hi, I'm using your library to process PDF files through Dropbox API in Laravel 5 queues with supervisor, It's working very slow and consuming lots of memory to process the PDF image file into JPG image. anyway that's not the actual problem, the problem is some time it struck with any PDF file and automatically the library kills the PHP processing and restart the queue job again and again from scratch, This only happens with some specific PDF files. Please let me know what to do, My Queue job process is based on your library else if there is not any solution then I need to find some else library.

    Thanks Adil

    opened by adilsaeed31 6
  • Call to undefined method Spatie\PdfToImage\Pdf::setCompressionQuality()

    Call to undefined method Spatie\PdfToImage\Pdf::setCompressionQuality()

    I get the the error below when trying to compress a converted image

    Call to undefined method Spatie\PdfToImage\Pdf::setCompressionQuality()

    My code is as below.

    use Spatie\PdfToImage\Pdf; // use statement is declared at the top of the file

    $pdf = new Pdf($file->getRealPath());
    $pdf->setCompressionQuality(75);
    $pdf->saveImage($storagePath . 'public/files/flipbooks/' . $savedFileName);
    

    Please advise.

    opened by temwa 5
  • Image size (width and height) issue

    Image size (width and height) issue

    Hi,

    I have an issue when I convert a specific pdf file (attached file below)..!

    The product images has not the same width and height as the pdf file.

    Thank you for your help

    test-0 956_1664183805.pdf

    opened by said15904 0
  • getNumberOfPages returns wrong number

    getNumberOfPages returns wrong number

    I have PDF with 12 pages image But method getNumberOfPages returns 48 pages. When i use saveAllPagesAsImages i got error:

    ImagickException
    PDFDelegateFailed ` Requested FirstPage is greater than the number of pages in the file: 12 No pages will be processed (FirstPage > LastPage). ' @ error/pdf.c/ReadPDFImage/794
    
    opened by projct1 2
  • Problem with large file.

    Problem with large file.

    Server is down with 503 error when loading big pdf(8Mb, 40 pages). It's because you puting file in construct method Imagick.

    $this->imagick = new Imagick($pdfFile);

    But why whole file if i need only one page. In method getImageData there is instruction that page is need use for generate preview.

    $this->imagick->readImage(sprintf('%s[%s]', $this->pdfFile, $this->page - 1));

    If you need read all file don't indicate index of page. Like this:

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

    After then i deleted file from constructor Imagick

    $this->imagick = new Imagick();

    And all works fine. If you want pick another page there is method setPage

    enhancement help wanted good first issue 
    opened by truechernyshov 2
Releases(2.2.0)
Owner
Spatie
We create products and courses for the developer community
Spatie
Gravity PDF is a GPLv2-licensed WordPress plugin that allows you to automatically generate, email and download PDF documents using Gravity Forms.

Gravity PDF Gravity PDF is a GPLv2-licensed WordPress plugin that allows you to automatically generate, email and download PDF documents using the pop

Gravity PDF 90 Nov 14, 2022
Magento 2 Invoice PDF Generator - helps you to customize the pdf templates for Magento 2

Magento 2 Invoice PDF Generator - helps you to customize the pdf templates for Magento 2. If you have an enabled template and a default template for the store you need your template the system will print the pdf template.

EAdesign 64 Oct 18, 2021
Convert HTML to PDF using Webkit (QtWebKit)

wkhtmltopdf and wkhtmltoimage wkhtmltopdf and wkhtmltoimage are command line tools to render HTML into PDF and various image formats using the QT Webk

wkhtmltopdf 13k Jan 4, 2023
A PHP tool that helps you write eBooks in markdown and convert to PDF.

Artwork by Eric L. Barnes and Caneco from Laravel News ❤️ . This PHP tool helps you write eBooks in markdown. Run ibis build and an eBook will be gene

Mohamed Said 1.6k Jan 2, 2023
Laravel package to convert HTML to PDF, supporting multiple drivers.

eve/pdf-converter A Laravel package to help convert HTML to PDF. Supports multiple drivers. Requirements and Installation eve/pdf-converter requires L

eve.io 11 Feb 15, 2022
Convert HTML to PDF using Webkit (QtWebKit)

wkhtmltopdf and wkhtmltoimage wkhtmltopdf and wkhtmltoimage are command line tools to render HTML into PDF and various image formats using the QT Webk

wkhtmltopdf 13k Jan 9, 2023
HTML to PDF converter for PHP

Dompdf Dompdf is an HTML to PDF converter At its heart, dompdf is (mostly) a CSS 2.1 compliant HTML layout and rendering engine written in PHP. It is

null 9.3k Jan 1, 2023
PHP library generating PDF files from UTF-8 encoded HTML

mPDF is a PHP library which generates PDF files from UTF-8 encoded HTML. It is based on FPDF and HTML2FPDF (see CREDITS), with a number of enhancement

null 3.8k Jan 2, 2023
PHP library allowing thumbnail, snapshot or PDF generation from a url or a html page. Wrapper for wkhtmltopdf/wkhtmltoimage

Snappy Snappy is a PHP library allowing thumbnail, snapshot or PDF generation from a url or a html page. It uses the excellent webkit-based wkhtmltopd

KNP Labs 4.1k Dec 30, 2022
Official clone of PHP library to generate PDF documents and barcodes

TCPDF PHP PDF Library Please consider supporting this project by making a donation via PayPal category Library author Nicola Asuni [email protected] co

Tecnick.com LTD 3.6k Jan 6, 2023
TCPDF - PHP PDF Library - https://tcpdf.org

tc-lib-pdf PHP PDF Library UNDER DEVELOPMENT (NOT READY) UPDATE: CURRENTLY ALL THE DEPENDENCY LIBRARIES ARE ALMOST COMPLETE BUT THE CORE LIBRARY STILL

Tecnick.com LTD 1.3k Dec 30, 2022
Pdf and graphic files generator library written in php

Information Examples Sample documents are in the "examples" directory. "index.php" file is the web interface to browse examples, "cli.php" is a consol

Piotr Śliwa 335 Nov 26, 2022
PdfParser, a standalone PHP library, provides various tools to extract data from a PDF file.

PdfParser Pdf Parser, a standalone PHP library, provides various tools to extract data from a PDF file. Website : https://www.pdfparser.org Test the A

Sebastien MALOT 1.9k Jan 2, 2023
Laravel Snappy PDF

Snappy PDF/Image Wrapper for Laravel 5 and Lumen 5.1 This package is a ServiceProvider for Snappy: https://github.com/KnpLabs/snappy. Wkhtmltopdf Inst

Barry vd. Heuvel 2.3k Jan 2, 2023
Sign PDF files with valid x509 certificate

Sign PDF files with valid x509 certificate Require this package in your composer.json and update composer. This will download the package and the depe

Lucas Nepomuceno 175 Jan 2, 2023
Generate simple PDF invoices with PHP

InvoiScript Generate simple PDF invoices with PHP. Installation Run: composer require mzur/invoiscript Usage Example use Mzur\InvoiScript\Invoice; re

Martin Zurowietz 16 Aug 24, 2022
PHP library allowing PDF generation or snapshot from an URL or an HTML page. Wrapper for Kozea/WeasyPrint

PhpWeasyPrint PhpWeasyPrint is a PHP library allowing PDF generation from an URL or an HTML page. It's a wrapper for WeasyPrint, a smart solution help

Pontedilana 23 Oct 28, 2022
Generate pdf file with printable labels

printable_labels_pdf Generate pdf file with printable labels with PHP code. CREATE A PDF FILE WITH LABELS EASELY: You can get a pdf file with labels f

Rafael Martin Soto 5 Sep 22, 2022
A Laravel package for creating PDF files using LaTeX

LaraTeX A laravel package to generate PDFs using LaTeX · Report Bug · Request Feature For better visualization you can find a small Demo and the HTML

Ismael Wismann 67 Dec 28, 2022