PHP如何将PDF文档转换为预览图片

时间:2017-07-27
本文章向大家介绍PHP如何将PDF文档转换为预览图片,需要的朋友可以参考一下。

需求:

将PDF文档的一部分呈现给图像文件需要哪些库,扩展等?

我发现的大多数PHP PDF库都围绕创建PDF文档,但是有一种简单的方法可以将文档呈现为适合Web使用的图像格式吗?

实现方法:

方法一:ImageMagickGhostScript

<?php
$im = new imagick('file.pdf[0]');
$im->setImageFormat('jpg');
header('Content-Type: image/jpeg');
echo $im;
?>

file.pdf[0]中的0代表第一页。

方法二:使用php扩展名Imagick。

要控制所需的光栅输出图像大小,请使用setResolution函数

<?php    
$im = new Imagick();
$im->setResolution(300, 300);     //set the resolution of the resulting jpg
$im->readImage('file.pdf[0]');    //[0] for the first page
$im->setImageFormat('jpg');
header('Content-Type: image/jpeg');
echo $im;
?>

方法三:使用php 的GhostScript包装器

我是PDFlib的作者,这是一个 用于php 的GhostScript包装器,使用这个库的优点是,它已经过测试,不需要ImageMagic

GhostScript命令比ImageMagicpdf 更快,所以你应该选择GhostScript包装器或纯GhostScript命令

$pdflib = new ImalH\PDFLib\PDFLib();
$pdflib->setPdfPath($pdf_file_path);
$pdflib->setOutputPath($folder_path_for_images);
$pdflib->convert();