php
Imal Perera  

PDF to Images using Php

Spread the love

There are two options if you are looking for a solution in php,

1. ImageMagick
2. GhostScript

Imagick provide you a php wrapper as well so it is easy for a developer to just write the code, but Imageick itself is very slow. once you wrote the code then after few days your project manager will come and say, ‘Hey your code take ages, can you make it faster ?’ now you will start to look for alternatives and then you will find GhostScript.

I had a similar incident where I felt Imagick is ridiculously slow, so when i’m searching and reading I found that Imagick internally uses GhostScript and direct usage of GhostScript can make more faster execution, but Unfortunatly there were no good wrappers available for php which utilizes the GhostScript commands so this is my effort to gift a library for the community.

Install

 composer require imal-h/pdf-box

Usage
Convert PDF to Images

 $pdfBox = new ImalH\PDFBox\PDFBox();
 $pdflib = new ImalH\PDFLib\PDFLib();
 $pdflib->setPdfPath($pdf_file_path);
 $pdflib->setOutputPath($folder_path_for_images);
 $pdflib->setImageFormat(\ImalH\PDFLib\PDFLib::$IMAGE_FORMAT_PNG);
 $pdflib->setDPI(300);
 $pdflib->setPageRange(1,$pdflib->getNumberOfPages());
 $pdflib->convert();

Convert Images to PDF

 $pdfBox = new ImalH\PDFBox\PDFBox();
 $pdflib = new ImalH\PDFLib\PDFLib();
 $imagePaths = ["images-1.jpg","images-2.jpg"];
 $pdflib->makePDF($destination_pdf_file_path,$imagePaths);

Github : https://github.com/imalhasaranga/PDFLib

I’m happy to here what you guys think 🙂

Leave A Comment