Skip to content
Advertisement

Spatie/pdf-to-image get number of images always returns 0

I’m using the spatie/pdf-to-image with laravel to create thumbnails of uploaded pdf files. What is weird is that the code was working at one point now it isn’t. $pdf->getNumberOfPages(); always returns 0 no matter how many pages the pdf contains.

This is the constructor in the Spatie Pdf class. As you can see it is just using imagick’s getNumberImages();

public function __construct($pdfFile)
{
    if (! filter_var($pdfFile, FILTER_VALIDATE_URL) && ! file_exists($pdfFile)) {
        throw new PdfDoesNotExist();
    }
    $this->imagick = new Imagick($pdfFile);
    $this->numberOfPages = $this->imagick->getNumberImages();
    $this->pdfFile = $pdfFile;
}

This is a simplified version of my controller:

   public function uploadDocument(Request $request) {

       $doc = $request->file('document');

       $pdf = new SpatiePdfToImagePdf($doc);

       $pages = $pdf->getNumberOfPages();
       dd($pdf);

The output of the dump is:

    Pdf {#315 ▼
      #pdfFile: UploadedFile {#236 ▶}
      #resolution: 144
      #outputFormat: "jpg"
      #page: 1
      +imagick: Imagick {#407}
      #numberOfPages: 0
      #validOutputFormats: array:3 [▼
          0 => "jpg"
          1 => "jpeg"
          2 => "png"
      ]
      #layerMethod: 14
      #colorspace: null
      #compressionQuality: null
   }

I know for a fact this was working at one point and I’m leaning towards imagick as the culprit. No errors and no exceptions. Is there a simple way to test this theory?

Advertisement

Answer

I know this is old, but I think I find the issue. I was running into the same problem, but it only happens when I was an instance of IlluminateHttpUploadedFile.

To solve it, I actually had to save the file to the local disk (not S3 or any other remote disk) and then manipulate the saved PDF. Worked prefectly!

Here’s a sample of my code (note: I loop manually due to business rules in the application.

     * generates a PNG preview from a PDF file
     * @param UploadedFile $file  PDF file to be converted
     * @param $historyID integer asset_file_history_id
     * @return bool whether or not the preview was successfully created
     */
    function generatePreviewImage(UploadedFile $file,$historyID)
    {

        $file =  storage_path('app/'.$file->store('temp'));
        try {
            $pdf = new Pdf($file);
            $pdf->setCompressionQuality(85);
            $pdf->setOutputFormat('png');
            $pdf->setColorspace(1);
            $pageLimit = $pdf->getNumberOfPages() > 10 ? 10: $pdf->getNumberOfPages();
             if($pdf->getNumberOfPages() >1) {
                //using if to account for possible count of 0, rather than just relying on the loop
                for ($i = 1; $i <=$pageLimit; $i++) {
                    $name = md5(time()) . ".png";
                    $tempPath = sys_get_temp_dir() . "/" . $name;
                    //
                    $pdf->setPage($i)
                        ->saveImage($tempPath);
                    //
                    Storage::disk('s3')->put("/preview/{$name}", file_get_contents($tempPath), 'public');

                    $page = new PreviewImagePage();
                    $page->url = "preview/{$name}";
                    $page->asset_file_history_id = $historyID;
                    $page->save();

                }//loop through the pages
            }//if
            else
            {
                $name = md5(time()) . ".png";
                $tempPath = sys_get_temp_dir() . "/" . $name;
                //
                $pdf->saveImage($tempPath);
                //
                Storage::disk('s3')->put("/preview/{$name}", file_get_contents($tempPath), 'public');

                $page = new PreviewImagePage();
                $page->url = "preview/{$name}";
                $page->asset_file_history_id = $historyID;
                $page->save();

            }//else
}
        catch(Exception $e)
        {
            dd($e);
           // return false;
        }

Then, of course, go back through and clean up any files that didn’t need saving.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement