2021-12-24 18:46:37
浏览数 (2)
- 开发过程中总会遇到pdf预览的问题,下面是其中一个解决方案
- 无论是转化为多张还是单张图片,都需要安装PHP的Imagick扩展。可以根据下面的代码进行优化,比如自定义分辨率,自动检测文件目录,进行压缩等
代码语言:javascript
复制/**
* 将pdf文件转化为多张png图片
* @param string $pdf pdf所在路径 (/www/pdf/test.pdf pdf所在的绝对路径)
* @param string $path 新生成图片所在路径 (/www/images/)
*
* @return array|bool
*/
function pdf2png($pdf, $path)
{
if (!extension_loaded('imagick')) {
return false;
}
if (!file_exists($pdf)) {
return false;
}
$im = new Imagick();
$im->setResolution(120, 120); //设置分辨率 值越大分辨率越高
$im->setCompressionQuality(100);
$im->readImage($pdf);
foreach ($im as $k => $v) {
$v->setImageFormat('png');
$fileName = $path . md5($k . time()) . '.png';
if ($v->writeImage($fileName) == true) {
$return[] = $fileName;
}
}
return $return;
}
/**
* 将pdf转化为单一png图片
* @param string $pdf pdf所在路径 (/www/pdf/test.pdf pdf所在的绝对路径)
* @param string $path 新生成图片所在路径 (/www/images/)
*
* @throws Exception
*/
function pdf2png2($pdf, $path)
{
try {
$im = new Imagick();
$im->setCompressionQuality(100);
$im->setResolution(120, 120);//设置分辨率 值越大分辨率越高
$im->readImage($pdf);
$canvas = new Imagick();
$imgNum = $im->getNumberImages();
//$canvas->setResolution(120, 120);
foreach ($im as $k => $sub) {
$sub->setImageFormat('png');
//$sub->setResolution(120, 120);
$sub->stripImage();
$sub->trimImage(0);
$width = $sub->getImageWidth() 10;
$height = $sub->getImageHeight() 10;
if ($k 1 == $imgNum) {
$height = 10;
} //最后添加10的height
$canvas->newImage($width, $height, new ImagickPixel('white'));
$canvas->compositeImage($sub, Imagick::COMPOSITE_DEFAULT, 5, 5);
}
$canvas->resetIterator();
$canvas->appendImages(true)->writeImage($path . microtime(true) . '.png');
} catch (Exception $e) {
throw $e;
}
}