2012-11-28 118 views
3

我使用ImageMagik嘗試將PDF的內容轉換爲JPG格式,但仍然獲取空的jpg。我已經確定了所有測試中的777,所以我有點迷路了。使用PHP將PDF轉換爲JPG格式圖像

這裏是我跑

<?php 

    exec('convert testfile.pdf output.jpg', $output, $return_var); 

?> 
+0

您可能需要指定完整的轉換路徑。您的輸入和輸出與您運行轉換的位置相同的目錄中嗎?檢查$ output變量是否有錯誤消息? Imagemagick包含代表Ghostscript和libjpeg嗎? – fmw42

回答

6

試試這個。

<?php 
    $pdf = 'testfile.pdf'; 
    $save = 'output.jpg'; 

    exec('convert "'.$pdf.'" -colorspace RGB -resize 800 "'.$save.'"', $output, $return_var); 

?> 
+1

+1如果你使用'escapeshellarg' – silly

+0

這工作,謝謝 – tony2

+0

我最近的經驗ghostScript比轉換命令更快,試試這個完整的庫我寫了哪個這樣做超級快https://github.com/imalhasaranga/PDFBox –

1

使用絕對路徑二進制腳本,像這樣:

exec('/usr/bin/convert testfile.pdf output.jpg', $output, $return_var); 

但要確保你的convert二進制文件實際上是對/usr/bin可以檢查用以下命令:

which convert

1
convert -normalize yourfile.pdf[0] yourdestination.jpg 
0

ImageMagick的內部使用GhostScript的和一般的ImageMagick的轉換是比較緩慢的向Ghoastscript,所以如果你只在得到PDF轉換爲圖像,然後Ghostscript的gs命令更快感興趣。下面的 是我幾天前寫的一個Ghostscript的示例包裝器。

PDFLib-Php

$pdflib = new ImalH\PDFLib\PDFLib(); 
$pdflib->setPdfPath($pdf_file_path); 
$pdflib->setOutputPath($folder_path_for_images); 
$pdflib->setImageQuality(95); 
$pdflib->setDPI(300); 
$pdflib->setPageRange(1,$pdflib->getNumberOfPages()); 
$pdflib->convert(); 
+0

不,那不是PDFBox。 PDFBox的正確URL是https://pdfbox.apache.org/。 –

+0

你的伴侶是什麼問題? PDFBox是爲Java和這對於PHP和問題是問如何做到這一點在Java中沒有在Java中 –

0

這裏有我的解決辦法。直接在你的php代碼中使用Imagick。

轉換PDF的所有網頁,以JPG

// create Imagick object 
$imagick = new Imagick(); 
// Reads image from PDF 
$imagick->readImage('file.pdf'); 
// Writes an image 
$imagick->writeImages('converted.jpg', false); 

轉換特定PDF頁面JPG

// create Imagick object 
$imagick = new Imagick(); 
// Read image from PDF 
$imagick->readImage('test.pdf[0]'); 
// Writes an image 
$imagick->writeImages('converted_page_one.jpg'); 

另一種方式來處理這個問題是使用spatie/PDF到影像庫。

乾杯!