Render a part of a PDF document to an image file

Asked

Viewed 320 times

1

Good morning, you guys! I wonder if there is any php function that renders a part of the pdf file to an image file. There is the Imagemagick function, but I’m not quite sure about that.

  • You need to generate or manipulate the pdf and then convert to image using php?

  • I upload the pdf to a folder, but the path of the folder saved in the database. I would just like to render only one image of the pdf file to be displayed in the browser using php.

  • I’ll draw up an answer

1 answer

2

To solve your problem I used the package SPATIE available on github.

Only perform package installation via commiserate as per package documentation.

Follows code:

<?php

use Spatie\PdfToImage\Pdf as Render;

require __DIR__ . '/vendor/autoload.php';

$pdf_path = __DIR__ . '/pdf/file.pdf';
$images_path = __DIR__ . '/pdf/images/';

if (!file_exists($images_path)) {
    echo printf('Path %s não encontrado', $images_path);
    die;
}

if (!file_exists($pdf_path)) {
    echo printf('Path %s não encontrado', $pdf_path);
    die;
}

$pdf_to_image = new Render($pdf_path);

$image = $pdf_to_image->setPage(3)
    ->setOutputFormat('png')
    ->saveImage($images_path . date('now'));

if (!$image) {
    echo 'Erro ao renderizar PDF';
    die;
}

echo 'Sucesso ao renderizar PDF';

Obs.:

  • I used the date('now') to generate the file name
  • Attention to folder structure

    Projeto
    -> pdf
        ->images
    -> vendor
    
  • The archives composer.json and index.php are at the root of the project

Browser other questions tagged

You are not signed in. Login or sign up in order to post.