Php сделать превью pdf

umidjons / pdf-thumbnail-php.md

Download and install right version of ghostscript. In my case my PHP was x86 architecture, so I download Ghostscript 9.14 for Windows (32 bit) .

Check, is imagick extension available and loaded.

This line should be present in your php.ini :

Also, check php_imagick.dll in PHP’s ext directory.

 function genPdfThumbnail($source, $target) < //$source = realpath($source); $target = dirname($source).DIRECTORY_SEPARATOR.$target; $im = new Imagick($source."[0]"); // 0-first page, 1-second page $im->setImageColorspace(255); // prevent image colors from inverting $im->setimageformat("jpeg"); $im->thumbnailimage(160, 120); // width and height $im->writeimage($target); $im->clear(); $im->destroy(); >
 genPdfThumbnail('/uploads/my.pdf','my.jpg'); // generates /uploads/my.jpg

This is very sweet. Thank you. Nevertheless, if the original PDF file is large (I have one around 36M), this method gets excruciatingly slow. I think that the problem is that Image Magick still parses the entire PDF, even if you tell it that you want only the first page. Fortunately, not all the files on our server are that large. I’m wondering if there is a way to tell Image Magick to stop reading after it’s found the first page (or whatever page you request).

@lsiden — Did you find a way to do this? I’ve just come across the same issue with a 668 page PDF killing my image preview script.

Use an PHP’s external program execution functions to call pdftoppm which has the ability select pages thereby avoiding the whole «loading everything into memory problem», it’s in poppler-utils on Ubuntu

pdftoppm -l 1 -scale-to 150 -jpeg example.pdf > thumb.jpg

which translates to take the last page as 1 (you can specify a first page), scale the largest size to 150 pixels and throw out a jpeg.

https://linux.die.net/man/1/pdftoppm if windows is required then the poppler libraries are listed as containing pdftocairo which use the same arguments and has some windows specific printing options.

2019-04-09 adaptation from https://gist.github.com/umidjons/11037635

added error capture when a source is not a pdf or not a file path, else function outputs the new file path.
added optional size and page number, defaults to 256 pix made from first page in the pdf.
added page orentation and relative resize of height vs width as whatever is smaller than the maximum given size.
added the option of putting the output jpeg into a sub folder, auto creating directory if not already existent.
added correction of black zones on transparency in a pdf.

to call my version of the function implement it for example like this:

to get page 2 as 150 pixel jpeg implement it for example as below.
however if the pdf does not have more than 1 page, be assured errors will occur.

to see the result from the function thereafter implement this:

 // we cannot have negative values $img = new Imagick($source."[$page]"); // [0] = first page, [1] = second page $imH = $img->getImageHeight(); $imW = $img->getImageWidth(); if ($imH==0) // if the pdf page has no height use 1 instead if ($imW==0) // if the pdf page has no width use 1 instead $sizR = round($size*(min($imW,$imH)/max($imW,$imH))); // relative pixels of the shorter side $img -> setImageColorspace(255); // prevent image colors from inverting $img -> setImageBackgroundColor('white'); // set background color and flatten $img = $img->flattenImages(); // prevents black zones on transparency in pdf $img -> setimageformat('jpeg'); if ($imH == $imW)thumbnailimage($size,$size);> // square page if ($imH < $imW) thumbnailimage($size,$sizR);> // landscape page orientation if ($imH > $imW) thumbnailimage($sizR,$size);> // portrait page orientation if(!is_dir(dirname($target))) // if not there make target directory $img-> writeimage($target); $img-> clear(); $img-> destroy(); if(file_exists( $target )) < return $target; >// return the path to the new file for further processing endif; return FALSE; // the source file was not available, or Imagick didn't create a file, so returns a failure > ?> 

below two questions to my own concept above:

A. Is it technically possible that a provided PDF contains zero pages, if so: how can we test this?
B. Can the img obtained from the PDF be 0 in width or height? As this would cause a NAN error.

2019-04-09 adaptation from https://gist.github.com/umidjons/11037635

added error capture when a source is not a pdf or not a file path, else function outputs the new file path.
added optional size and page number, defaults to 256 pix made from first page in the pdf.
added page orentation and relative resize of height vs width as whatever is smaller than the maximum given size.
added the option of putting the output jpeg into a sub folder, auto creating directory if not already existent.
added correction of black zones on transparency in a pdf.

to call my version of the function implement it for example like this:

$pdf_thumb = genPdfThumbnail(‘/nfs/vsp/servername/u/username/public_html/any.pdf’,’thumbs/any.jpg’)

to get page 2 as 150 pixel jpeg implement it for example as below.
however if the pdf does not have more than 1 page, be assured errors will occur.

$pdf_thumb = genPdfThumbnail(‘/nfs/vsp/servername/u/username/public_html/any.pdf’,’any_p02.pdf.jpeg’,150,’02’)

to see the result from the function thereafter implement this:

if($pdf_thumb)< echo $pdf_thumb; >else

the function itself:

 // we cannot have negative values $img = new Imagick($source."[$page]"); // [0] = first page, [1] = second page $imH = $img->getImageHeight(); $imW = $img->getImageWidth(); if ($imH==0) // if the pdf page has no height use 1 instead if ($imW==0) // if the pdf page has no width use 1 instead $sizR = round($size*(min($imW,$imH)/max($imW,$imH))); // relative pixels of the shorter side $img -> setImageColorspace(255); // prevent image colors from inverting $img -> setImageBackgroundColor('white'); // set background color and flatten $img = $img->flattenImages(); // prevents black zones on transparency in pdf $img -> setimageformat('jpeg'); if ($imH == $imW)thumbnailimage($size,$size);> // square page if ($imH < $imW) thumbnailimage($size,$sizR);> // landscape page orientation if ($imH > $imW) thumbnailimage($sizR,$size);> // portrait page orientation if(!is_dir(dirname($target))) // if not there make target directory $img-> writeimage($target); $img-> clear(); $img-> destroy(); if(file_exists( $target )) < return $target; >// return the path to the new file for further processing endif; return FALSE; // the source file was not available, or Imagick didn't create a file, so returns a failure > ?> 

You’re the best! Exactly what I need! I had a tough situation when I could only use a SharedHosting. Can’t express how much thankful I am!

Источник

Создаем превью PDF файла в PHP.

Где это может пригодиться? Допустим, Вы создаете онлайн-библиотеку, в которой при добавлении новой книги (в нашем случае в формате PDF) из нее генерируется изображение первой страницы — превью.

Итак, для создания превью из PDF файла будем использовать библиотеки Imagick и Gostscript.

// путь к файлам с превью
function coverImagePath(string $pdfFileName)
$poster = pathinfo($pdfFileName, PATHINFO_FILENAME);
return __DIR__ . «/covers/$poster.jpg»;
>

// здесь создаем превью
// параметр файла — пусть к PDF-файлу
function createPoster(string $pdfFile)
$firstPage = ‘[0]’; // первая страница
$im = new Imagick($pdfFile . $firstPage); // читаем первую страницу из файла
$im->setImageFormat(‘jpg’); // устанавливаем формат jpg
file_put_contents(coverImagePath($pdfFile), $im); // сохраняем файл в папку
$im->clear(); // очищаем используемые ресурсы
>

// получаем все файлы в папке
const RootDir = ‘/home/myrusakov/Documents’;
$files = new DirectoryIterator(RootDir);

// проходимся по ним
foreach($files as $file)
// если файл — . или .. — пропускаем
if($file->isDot())
continue;

// получаем полный путь к файлу
$filePath = RootDir . DIRECTORY_SEPARATOR . $file->getFilename();

createPoster($filePath);
print($filePath . PHP_EOL);
>
>

Таким образом,после запуска программы мы получим превью — изображение первой страницы каждого файла.

Создано 30.12.2021 08:47:24

  • Михаил Русаков
  • Копирование материалов разрешается только с указанием автора (Михаил Русаков) и индексируемой прямой ссылкой на сайт (http://myrusakov.ru)!

    Добавляйтесь ко мне в друзья ВКонтакте: http://vk.com/myrusakov.
    Если Вы хотите дать оценку мне и моей работе, то напишите её в моей группе: http://vk.com/rusakovmy.

    Если Вы не хотите пропустить новые материалы на сайте,
    то Вы можете подписаться на обновления: Подписаться на обновления

    Если у Вас остались какие-либо вопросы, либо у Вас есть желание высказаться по поводу этой статьи, то Вы можете оставить свой комментарий внизу страницы.

    Порекомендуйте эту статью друзьям:

    Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):

    1. Кнопка:
      Она выглядит вот так:
    2. Текстовая ссылка:
      Она выглядит вот так: Как создать свой сайт
    3. BB-код ссылки для форумов (например, можете поставить её в подписи):

    Комментарии ( 0 ):

    Для добавления комментариев надо войти в систему.
    Если Вы ещё не зарегистрированы на сайте, то сначала зарегистрируйтесь.

    Copyright © 2010-2023 Русаков Михаил Юрьевич. Все права защищены.

    Источник

    Создание превью Pdf — файлов

    Создаю превью для pdf — файлов. Нашел в интернете скрипт для конвертации:

    exec('convert "gazeta.pdf[0]" -colorspace RGB -geometry 200 "preview.png"');

    Он работал 3 месяца, потом перестал.
    Задал вопрос в службу технической поддержки хостинга о том установлены ли у них скрипты GhostScript и ImageMagick, на что они мне ответили: «GhostScript и ImageMagick установлены на нашей площадке как модули Perl.»

    Подскажите как все таки можно воспользоваться этими модулями для создания превьюшек для pdf-файлов?

    evgen

    1ive

    установлены на нашей площадке как модули Perl

    два варианта:
    меняй хостера
    переписывай скрипт на perl

    vital

    setImageColorspace(255); #устанавливаем цветовую палитру $obPdf->setCompression(Imagick::COMPRESSION_JPEG); #Устанавливаем компрессор $obPdf->setCompressionQuality(60); #И уровень сжатия $obPdf->setImageFormat(‘jpeg’); #При необходимости сделать превью ресайзим изображение $obPdf->resizeImage(250, 250, imagick::FILTER_LANCZOS, 1); #Ну и конечно же пишем в jpg-файл. $obPdf->writeImage(‘act_preview.jpg’); $obPdf->clear(); $obPdf->destroy(); ?>

    ^это просто обертка для того же конверта. Лучше юзайте так.
    Если не работает, то узнайте у хостера, у становлен(или возможо ли) установить расширение XPDF. А там..

     1. createFileFromReal(‘file1′, $fileName); unlink($fileName);?>

    evgen

    $obPdf = new Imagick( ‘act.pdf[0]‘ ); #Открываем наш PDF и указываем обработчику на первую страницу
    $obPdf->setImageColorspace(255); #устанавливаем цветовую палитру
    $obPdf->setCompression(Imagick::COMPRESSION_JPEG); #Устанавливаем компрессор
    $obPdf->setCompressionQuality(60); #И уровень сжатия
    $obPdf->setImageFormat(‘jpeg’);
    #При необходимости сделать превью ресайзим изображение
    $obPdf->resizeImage(250, 250, imagick::FILTER_LANCZOS, 1);
    #Ну и конечно же пишем в jpg-файл.
    $obPdf->writeImage(‘act_preview.jpg’);
    $obPdf->clear();
    $obPdf->destroy();
    ?>

    Да, они говорят, что ImageMagick у них установлен (Версия: ImageMagick-6.6.4.10), даже дали файл с тестом:

    Class 'imagick' not found in /htdocs/www/111/imagick.php on line 2

    как раз на том месте где создается новый объект класса.

    Также вопрос. каким образом можно переписать скрипт на perl. Опыта с perl никакого.

    Источник

    Создаем превью PDF файла в PHP.

    Создаем превью PDF файла в PHP.

    Где это может пригодиться? Допустим, Вы создаете онлайн-библиотеку, в которой
    при добавлении новой книги (в нашем случае в формате PDF) из нее генерируется
    изображение первой страницы — превью.

    Итак, для создания превью из PDF файла будем использовать библиотеки Imagick и Gostscript.

    // путь к файлам с превью
    function coverImagePath(string $pdfFileName)
    $poster = pathinfo($pdfFileName, PATHINFO_FILENAME);
    return __DIR__ . «/covers/$poster.jpg»;
    >

    // здесь создаем превью
    // параметр файла — пусть к PDF-файлу
    function createPoster(string $pdfFile)
    $firstPage = ‘[0]’; // первая страница
    $im = new Imagick($pdfFile . $firstPage); // читаем первую страницу из файла
    $im->setImageFormat(‘jpg’); // устанавливаем формат jpg
    file_put_contents(coverImagePath($pdfFile), $im); // сохраняем файл в папку
    $im->clear(); // очищаем используемые ресурсы
    >

    // получаем все файлы в папке
    const RootDir = ‘/home/myrusakov/Documents’;
    $files = new DirectoryIterator(RootDir);

    // проходимся по ним
    foreach($files as $file)
    // если файл — . или .. — пропускаем
    if($file->isDot())
    continue;

    // получаем полный путь к файлу
    $filePath = RootDir . DIRECTORY_SEPARATOR . $file->getFilename();

    createPoster($filePath);
    print($filePath . PHP_EOL);
    >
    >

    Таким образом,после запуска программы мы получим превью — изображение первой страницы каждого файла.

    Источник

    Читайте также:  Scripting in java example
    Оцените статью