Code Monkey home page Code Monkey logo

pdf-to-image's Introduction

Convert a pdf to an image

Latest Version on Packagist Software License 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

You can specify the width of the resulting image:

$pdf
   ->width(400)
   ->saveImage($pathToWhereImageShouldBeStored);

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've found a bug regarding security please mail [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.

pdf-to-image's People

Contributors

4n70w4 avatar abarta avatar adrianmrn avatar akoepcke avatar alexvanderbist avatar benjaminrehn avatar bobvandevijver avatar dependabot[bot] avatar dsinn avatar freekmurze avatar garak avatar github-actions[bot] avatar introwit avatar jamesdb avatar michael-wolfram avatar miclf avatar nielsvanpach avatar ntaylor-86 avatar patinthehat avatar philhil avatar robert197 avatar rubenvanassche avatar tvke avatar wintersilence avatar wqj97 avatar zaherg avatar zandzpider avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pdf-to-image's Issues

Bad quality of images

Thanks for simple and awesome package.
I've found an issue.
All images which were generated from PDF have bad quality. I've tried to change resolution, but it changed nothing. So I've researched your code and I've found resolution does not working in your package. To provide resolution you need to set value of resolution before of reading PDF file. You can find a lot of examles one of them here . So problem is you read PDF file in __construct and then set resolution in getImageData (you try to read again after changing resolution in getImageData but actually it does not work)
My suggestions
PDF file must be read in __construct because method getNumberOfPages works based on this. I suggest to change your getImageData method like this:

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;
    }

you can try by yourself and maybe find better solution. Thanks again for great package

Imagemagick cannot open file.pdf[0]

what version of the imagemagick do i need? on my server, the code fails on this line

https://github.com/spatie/pdf-to-image/blob/master/src/Pdf.php#L169
$imagick->readImage(sprintf('%s[%s]', $this->pdfFile, $this->page - 1));

saying it can't read a file ...path/to/pdf.pdf[0] (0 because my pdf has one page)

i am using it in combination with medialibrary

ImagickException in Pdf.php line 170:
Failed to read the file
in Pdf.php line 170

at Imagick->readimage('/path_to_project/storage/medialibrary/temp/cO4tPRH3f3POL5X1/A7Vyz9sE2YEQ16AM.pdf[0]') in Pdf.php line 170
at Pdf->getImageData('/path_to_project/storage/medialibrary/temp/cO4tPRH3f3POL5X1/A7Vyz9sE2YEQ16AM.jpg[0]') in Pdf.php line 120

i have tried opening a jpg file and it can read the image. the only problem only occurs with pdfs :(

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

Add access to appendImages()

Hi there,

Firstly, thank you for writing this package.

Recently, I needed to append multiple files from a PDF into one JPG file and could not. I could not access the appendImages() method of imagick.php class from your class as $imagick property is protected.

I suggest adding a new method that allows setting $this->imagick->appendImages(true) if needed.

Thanks!

Creating image with white area around

Hi,
I am getting mostly what I want but some files are generating images with white areas around image with no particular reason (same settings, PDFs have no white borders or something).
I have attached image that I get and original PDF.

Please if you can help me how to handle this kind of bugs would be cool.
Thanks a lot.

planeo.pdf
cs9zieuaxeatwiinm3thwvra

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');
            }

File conversion is really slow...

I have been using this package for some time now in our dev enviroment and I love how well it's built, I have struggled how ever with the slowness of the process. I hope it's just my code or something I am doing wrong. We are coming close to launch and I need a faster solution. Would you be willing to look at this and tell me if I am using this code wrong and any thoughts on optimizing it? Currently I am averaging between 2 seconds and as much as 10 seconds per page. So a 30 page document is taking 5 mins to process.

`$files = $request->file('uploadfiles') ?: $request->file('templatefiles');

    if (!file_exists('../storage/app/documents/tmp')) {
        mkdir('../storage/app/documents/tmp', 0777, true);
    }

    foreach($files as $file){
        $title = pathinfo($file->getClientOriginalName(), PATHINFO_FILENAME);
        $description = $request->file('templatefiles') ? 'signable-template' : 'signable-document';
        $fileMime = $file->getClientOriginalExtension();
        $name = str_slug($title);
        $path = '../storage/app/documents/tmp';
        $collection = Auth::id().'-'.str_random(30);

        if($fileMime == 'pdf'){
            // increase timeout on server for really big files.
            ini_set('default_socket_timeout', 900); // 900 Seconds = 15 Minutes
            ini_set('upload_max_filesize', '30M');
            ini_set('post_max_size', '30M');
            ini_set('max_input_time', 900);
            ini_set('max_execution_time', 900);

            $pdf = new Pdf($file->path());
            $totalNumberOfPages = $pdf->getNumberOfPages($file);

            if(isset($totalNumberOfPages)){
                foreach (range(1, $totalNumberOfPages) as $pageNumber) {
                    $pdfPngName = $name.$pageNumber.'.png';
                    $pdfPngPath = $path.'/'.$pdfPngName;
                    $pdf->setPage($pageNumber, $file)->saveImage($pdfPngPath);
                    $document = $this->documentCreate($name, $pdfPngName, $description, $collection);
                    $documentIdArray[] = ['collection' => $collection, 'document_id' => $document->id, 'name' => $title];
                    $document->addMedia($pdfPngPath)->usingFileName($pdfPngName)->toCollection($collection);
                    File::delete($pdfPngPath);
                }
            }

        }`

Giving class a blob rather than a file name?

Hello.

Is there a way to use this by give the Pdf class a blob of a PDF rather than a file path?

I want to create an image from a pdf saved in the database on the fly without having to save it to the filesystem first.

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?

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...

Class 'Imagick' not found

Hello! I'm trying to use this package but when I install the package and try to use it, I'm having this error:

Class 'Imagick' not found

I'm using Laravel 5.5 and with Laravel Valet 2.0.12.

Any idea?

Thank you!

No Decode Delegate For This Image Format

Hi, I'm using this library to convert a PDF file to PNG image but when I execute my PHP code I get this error:

"Uncaught exception: NoDecodeDelegateForThisImageFormat `PDF' @ error/constitute.c/ReadImage/501"

Throwed in PathToLibrary\Pdf.php:42

PDF line 42 is: $this->imagick = new Imagick($pdfFile); in the construct of the class.

I've tried with some pdfs, and I get the same error with all of them. They only have text.

Thanks for your attention.

Catch ImagickException

Thank you for this class, very useful! As I using this class for generating thumbnails from user provided PDFs it turns out that every once in a while ImagickException throws an exception. As the conversion with ImagickException has no try/catch this exception is not catched and is also not catchable from outside the class, as its already terminating the process within the class.
More precisely this happens for me every once in a while in getImageData() when $imagick->readImage() is called. Would it be feasible to introduce a try/catch there, so one could catch the error from outside the class and handle it appropriately?

Thanks so much!

Solution for error with Imagick and Ghostscript x64 in Windows

I've installed Ghostscript in Windows to work with the library, however I was getting the following message:

PDFDelegateFailed `The system cannot find the file specified. ' @ error/pdf.c/ReadPDFImage/801

I installed Ghostscript 9.21 for 64 bits in my Windows machine, so the executables of ghostscript are (gswin64.exe etc). That's why I looked the source code of the library to see if I could change someway the executable path, however the problem was someway in Imagick and that's nothing that you can simply change in some file. The issue here is that I'm using Xampp and it has installed Imagick x86 (32 bits), so installing Ghostscript for 32 bits solved the problem.

By itself, this is not an issue for the library but between imagick and Ghostscript, I am publishing this just in case that someone faces the same error and may need a light to solve it. Useful wrapper btw, thanks !

Unable to load

**I ran below command on my Ubuntu 16.04

ABC:~$ composer require spatie/pdf-to-image**

& following was shown:

PHP Warning: Module 'imagick' already loaded in Unknown on line 0
Using version ^1.4 for spatie/pdf-to-image
./composer.json has been updated
Loading composer repositories with package information
Updating dependencies (including require-dev)
Nothing to install or update
Generating autoload files

Now when I wrote following code:

saveImage('TEST.png'); ?>

I got following error:

PHP Fatal error: Uncaught Error: Class 'Spatie' not found in /var/www/html/ABC/ABC.php:16
Stack trace:
#0 {main}
thrown in /var/www/html/abc/TEST.php on line 16

Can You please tell me what is exactly is written wrong.

Note: I have Imagick & Ghostscript installed already. When I used following code:

$image = new Imagick( 'Local.pdf');
$image->setImageFormat( "png" );
$image->writeImage('TEST.png');

It created output. I was thinking of using spatie after visiting this site: https://murze.be/2015/07/convert-a-pdf-to-an-image-using-php/
So please let me know what needs to be done to get correct output.

Failed to Execute Command

why i getting this error? PHP 5.6.10

"" on line 29 of /Users/ihsan/Projects/sahabatjadisah/plugins/barndev/wedding/vendor/spatie/pdf-to-image/src/Pdf.php

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

Colour variation between original pdf and processed image

Hi,

I have using Spatie pdf-to-image converter in my laravel project. All working good but the color of original pdf and processed jpeg image is not the same. Image brightness is increased. Can you please give me a solution for solving this issue.

Thanks

Exceptions

How's the throw exceptions meant to work? I'm using the package with composer autoloading and the exceptions classes do not get loaded (other namespace). Am I meant to provide my own?

not work

When I try to convert a file shows the class message 'Imagick' is not found, try installing the class but the message persists. Any idea why that happens.

this it's my code:

$file_logo=Input::file('image');

        $folder = public_path().'/images/magazine';
        if(!file_exists($folder)){
            mkdir($folder, 0777, true);
            $pdf = new \Spatie\PdfToImage\Pdf($file_logo);
            foreach (range(1, $pdf->getNumberOfPages()) as $pageNumber) {
                $pdf->setPage($pageNumber)->saveImage($folder.'/'.'page'.$pageNumber.'jpg');
                $magazine = new Magazine;
                $magazine->img_magazine = 'images/magazine/'.'page'.$pageNumber.'jpg';
                $magazine->save();
            }
        }else{
            $pdf = new \Spatie\PdfToImage\Pdf($file_logo);
            foreach (range(1, $pdf->getNumberOfPages()) as $pageNumber) {
                $pdf->setPage($pageNumber)->saveImage($folder.'/'.'page'.$pageNumber.'jpg');
                $magazine = new Magazine;
                $magazine->img_magazine = 'images/magazine/'.'page'.$pageNumber.'jpg';
                $magazine->save();
            }
        }

"ext-imagick" : "*"

Hello,

is it really needed to have this:
"ext-imagick" : "*"
as a requirement?

We use some of spaties libraries and we like them.
But for example this one comes as a dependency (spatie/pdf-to-image)
and it is not used by our projects.

Maybe it could be moved to suggested or so?

I am just wondering :)

Thank you

Too many pages

Hi. I wasted the whole day to find a solution, but only got a bit closer to it... i hope. I transform pdfs to images. If the pdfs have not so much pages it works. But i try it with a pdf with 44 pages for example and got this error and nothing will happen...

@ error/delegate.c/ExternalDelegateCommand/463

After testing the whole day my last step forward was:
When I replace ...

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

to

$this->imagick = new Imagick($pdfFile.'[0]');

... first page is rendered. If I change the 0 to 1, 2, or something else everytime the first page is rendered. Hope somebody can help...

Feature request - Change the image file name

I am using the lib currently and I'd like to have the ability to set the saved image name. Right now, it is saved always using the name 1.

I started to work on this feature (#106) but @freekmurze suggested to change the code to pass a second argument to the saveImage method instead.

Sometimes works sometimes doesn't

I'm not quite sure why but new Pdf($src); works for some pdf files and doesn't work for some pdf files. It doesn't throw or output any error it just silently fails. Is there any requirement on the pdf file?

Postscript delegate failed: No such file or directory

THIS IS NOT AN ISSUE WITH THIS PACKAGE
This is just in case anyone runs in to this issue in the future, because there wasn't really a lot of help on google. I hope this helps somebody.

My Use Case:
I had written some code to convert a pdf to an image, then manipulate that image to attach further images/text so users could sign a pdf with their details and just a record of proof that the PDF was signed.

Problem
I had the code all setup, working wonderfully. Closed down my laptop at the end of the day, and learned through the night it had created over 1,000 files. I opened up my laptop this morning and came to the following error:

Error

file: "/path/to/my/vendor/directory/spatie/pdf-to-image/src/Pdf.php"
line: 169
message: "Postscript delegate failed path/to/public/directory/attachments/somefilename.pdf : No such file or directory @ error/pdf.c/ReadPDFImage/677"

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

Debugging
I'm using this package with Laravel 4.2, and the above was the only error I was getting however I was absolutely 100% sure file exists, I followed the path in my terminal exactly, file found, permissions were fine. I looked through NGINX error log, nothing relative. Laravel error log, the error above. Okay, so I restart nginx just in-case something funny is going on, still hitting the error. As a last resort, restarted php5-fpm, result. Error has disappeared.

Solution
sudo service php5-fpm restart

setPage not working

Greetings,

I have an error or misplaced line of code :(

I tried to upload a pdf, with pdf to image with each page represented as a -$i.jpg in the same folder.

It works but i now get the following:
attachments/file.pdf
attachments/file-1.jpg
attachments/file-2.jpg
attachments/file-3.jpg

But each jpg is the same, the image is an overlapping of all the pages.

Here is my code:

public function uploadSubmit(UploadRequest $request)
    {

    	foreach ($request->attachments as $attachment) {
			$filename = $attachment->store('public/attachments');

			if($attachment->extension() == "pdf")
			{	
				$url = explode('/', $filename)[2];
				$pdf = new \Spatie\PdfToImage\Pdf('{DOMAIN}/storage/attachments/' . $url);
				$newurl = '/var/www/vhosts/{DOMAIN}/httpdocs/storage/app/public/attachments/' . str_replace('.pdf', '-', $url);

				$pages = $pdf->getNumberOfPages();

				for($i = 1; $i < $pages + 1; $i++)
				{
					$pdf->setPage($i)->saveImage($newurl . $i . '.jpg');
				}
			}

            Attachment::create([
                'estimate_id' => $request->estimate_id,
                'space_id' => $request->space_id,
                'contact_id' => $request->contact_id,
                'filename' => $filename,
                'name' => $request->name,
                'description' => $request->description
            ]);
    	}

    	\Session::flash('flash_message_succes', 'Estimates are added');

    	return back();
    }

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.

Class 'Imagick' not found

I run phpinfo (); Inside a web application and php -i at the command line. Output of both if you mention that Imagick is installed. But still the same error. I don't know what's wrong

Option to stream image

Hi there,

I was wondering if we could have the option to stream the image to the browser, rather than saving it to disk?

In my application I would like to show a thumbnail of a dynamically generated PDF, so the image is only relevant for that particular request.

Can't extract one image from remote file

        $url = 'http://www.axmag.com/download/pdfurl-guide.pdf';
        $pdf = new Pdf($url);
        var_dump($pdf->getNumberOfPages());
        $pdf->saveImage('1.jpg');

Looks like it adds [0] to the URL, because number of pages is working. Is it possible to workaround it? Or I need to download the file manually?

file_put_contents failed to open stream: Permission denied

Here my code!

$pdf = new Spatie\PdfToImage\Pdf($_SERVER['DOCUMENT_ROOT'] ."/ocr/aa.pdf");

$pdf->saveImage(__DIR__."/uploadz");

The error message
Warning: file_put_contents(C:\Xampp\htdocs\ocr/uploadz): failed to open stream: Permission denied in C:\Xampp\htdocs\ocr\vendor\spatie\pdf-to-image\src\Pdf.php on line 164

Requested FirstPage is greater than the number of pages in the file

Hi I'm getting this error:

Fatal error: Uncaught ImagickException: PDFDelegateFailed `[ghostscript library 9.23] -q -dQUIET -dSAFER -dBATCH -dNOPAUSE -dNOPROMPT -dMaxBitmap=500000000 -dAlignToPixels=0 -dGridFitTT=2 "-sDEVICE=bmpsep8" -dTextAlphaBits=4 -dGraphicsAlphaBits=4 "-r144x144" -dUseCIEColor -dFirstPage=12 -dLastPage=12 "-sOutputFile=C:/Users/DESARR1/AppData/Local/Temp/magick-2980u-2q1FXLrAYr%d" "-fC:/Users/DESARR1/AppData/Local/Temp/magick-29804IzzgG7afazS" "-fC:/Users/DESARR~1/AppData/Local/Temp/magick-2980TSNyiXIaLZrd": Requested FirstPage is greater than the number of pages in the file: 11 No pages will be processed (FirstPage > LastPage). ' @ error/pdf.c/ReadPDFImage/801 in C:\xampp\htdocs\PDF\vendor\spatie\pdf-to-image\src\Pdf.php:239 Stack trace: #0 C:\xampp\htdocs\PDF\vendor\spatie\pdf-to-image\src\Pdf.php(239): Imagick->readimage('C:\xampp\tmp\ph...') #1 C:\xampp\htdocs\PDF\vendor\spatie\pdf-to-image\src\Pdf.php(178): Spatie\PdfToImage\Pdf->getImageData('C:/xampp/htdocs...') #2 C:\xampp\htdocs\PDF\php\process.php(92): Spati in C:\xampp\htdocs\PDF\vendor\spatie\pdf-to-image\src\Pdf.php on line 239

The resulting images is correct but are in black and white

The PDF has 11 pages, if I try setting 2 pages it works fine but the images are too in black and white.

I have working with PDF's with 40 pages with no problem.

I have tried change the format too, but it doest work.

Hypothesis: use filesystem abstraction

Just a thought: do you think it would be interesting to extend pdf-to-image to support filesystem abstraction ?

I'm using pdf-to-image in my app and I'm circuventing things so that I can use Gaufrette to access my files. I was thinking to create a new "extension" to pdf-image but, if you think it could be usefull to others I can also try to add new methods to Pdf.php so that it can use Gaufrette....

What do you think ?

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?!

setPage not working

Hi, i think your setPage isn't working.

i did something like this:

for($i = 1; $i<($numpages+1); $i++){
$pdf->setPage($i)->saveImage($path.'/testcvrt_'.$i.'.png');
}

but all it ever converts is the first page of the pdf file. Same goes for

saveAllPagesAsImages()

It only converts the first page of the pdf file.

no decode delegate for this image format

Using symfony 2.8, php 5.5... Have "no decode delegate for this image format...".

Stack Trace
in vendor/spatie/pdf-to-image/src/Pdf.php at line 169 +
at Imagick ->readimage ('/home/prog/projects/hanko/src/AppBundle/Services/../../../app/tmp/egm95vf6fb3pghd4lqtpj22vb1/D6AA5FEC00000000:002FA9C56A95CBBC/dec[0]')
in vendor/spatie/pdf-to-image/src/Pdf.php at line 169 +
at Pdf ->getImageData ('/home/prog/projects/hanko/src/AppBundle/Services/../../../app/tmp/egm95vf6fb3pghd4lqtpj22vb1/D6AA5FEC00000000:002FA9C56A95CBBC/1.jpeg')
in vendor/spatie/pdf-to-image/src/Pdf.php at line 120 +
at Pdf ->saveImage ('/home/prog/projects/hanko/src/AppBundle/Services/../../../app/tmp/egm95vf6fb3pghd4lqtpj22vb1/D6AA5FEC00000000:002FA9C56A95CBBC/1.jpeg')
in src/AppBundle/Controller/DefaultController.php at line 165 +

getNumberOfPages()

I am posting this here for spatie... and for anyone else that is running into this issue. I have been trying to work with the getNumberOfPages() function and unfortunately on our server (centos) this function has returned 0 without fail. Imagick is installed correctly but fails to respond correctly. As far as I can tell there is no bug in the spatie/pdf-to-image repository... the code here is immaculate (thank you spatie).

So if you've found the same issue I found this code to work very well.

        $pdfcontent = file_get_contents($filePath, NULL, NULL, 0, 300);
        preg_match("~Linearized.*?\/N ([0-9]+)~s", $pdfcontent, $pages);
        if(isset($pages[1])){
            echo "Pages ".$pages[1];
        }

Spatie, if you would like to make some type of fallback system or change your getNumberOfPages() function I have found this to work very well...AND RIDICULOUSLY FAST.

Image quality

Hi,

I works great but image quality seems pixilated after converting.
How do i increase image quality?

Thank you

  • Ravi

Composer run error imagic, but its already installed on my environment

hi there, i tried to install this packages in my project then return this error:

Problem 1
    - Installation request for spatie/pdf-to-image ^1.3 -> satisfiable by spatie/pdf-to-image[1.3.0].
    - spatie/pdf-to-image 1.3.0 requires ext-imagick * -> the requested PHP extension imagick is missing from your system.

I have enable the imagick extension in my environtment

re: df7e0e356 and #38

The change introduced in df7e0e3 results in page 1 being rendered on on page 2

Only if we use null does the code behave as expected.

        $source = $this->repo->GetFileCopyForUuid($uuid);
        $pdf = new Pdf($source->getRealPath());
        $pdf->setResolution($dpi);
        $pdf->setLayerMethod(null);
        $pdf->setPage($page);
        $pdf->setOutputFormat($png ? 'png' : 'jpg');
        $out = tempnam(sys_get_temp_dir(), 'pdf-to-image');
        if ($pdf->saveImage($out) !== true) {
            throw new RuntimeException(
                'Could not transform PDF page to image!'
            );
        }

        return new SplFileInfo($out);

required arguments out of constructor

Could you please revise the way this useful object is instantiated?

You could consider some more flexible alternative way:

$spatiePdf = new Spatie\PdfToImage\Pdf();
$spatiePdf->setPdf('filePdf');
...

This way, your object can easily be registered as a service, thus could be injected inside other application dependencies.

It would be appreciated if you consider this ...

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.