2015-09-07 132 views
0

我有一個MVC應用程序正在上傳PDF文件並使用Magick.NET將每個頁面呈現爲單個PNG圖像。在大多數情況下,轉換效果並不理想,但在一些情況下,我獲得了空白圖像,其中應顯示文本,並在同一圖像中正確顯示其他文本行。有誰知道這可能是什麼原因造成的?使用Magick.NET將PDF轉換爲PNG時缺少文本

以下是我正在使用的代碼。

public FileResult PNGPreview(Guid id, Int32 index) 
{ 
    MagickReadSettings settings = new MagickReadSettings(); 
    // Settings the density to 300 dpi will create an image with a better quality 
    settings.FrameIndex = index; 
    settings.FrameCount = 1; 
    settings.Density = new PointD(300, 300); 
    settings.UseMonochrome = true; 
    using (MagickImageCollection images = new MagickImageCollection()) 
    { 
     // Add all the pages of the pdf file to the collection 
     images.Read(CreateDocument(id), settings); 

     using (MemoryStream stream = new MemoryStream()) 
     { 

      images[0].Write(stream, MagickFormat.Png24); 
      stream.Close(); 
      byte[] result = stream.ToArray(); 
      return File(result, "image/png"); 
     } 
    } 
} 

private byte[] CreateDocument(Guid id) 
{ 
    PdfReader reader = new PdfReader(Server.MapPath(String.Format("~/documenttemplates/{0}.pdf", id))); 
    byte[] result = null; 
    using (MemoryStream ms = new MemoryStream()) 
    { 
     PdfStamper stamper = new PdfStamper(reader, ms, '\0', false); 
     stamper.Close(); 
     reader.Close(); 
     result = ms.ToArray(); 
    } 

    return result; 
} 
+0

問題是隨機的,還是一些PDF文件一直轉換爲空白圖像? – Micke

+0

一些PDF文件一致轉換。我首先想到它可能是一個字體問題,但PDF具有像Helvetica,Arial等標準字體。 – Steve

+0

我認爲這將是有益的,如果你可以共享一個PDF文件轉換爲空白圖像,如果有的話。 – Micke

回答

1

導致此問題是由電子郵件提供給我,我被告知,該文件是用Word中創建的,然後用福昕專業編輯的PDF文件。

Magick.NET使用Ghostscript將PDF文件轉換爲圖像。執行類似於下面的命令。

"c:\Program Files (x86)\gs\gs9.16\bin\gswin32c.exe" -q -dQUIET -dSAFER -dBATCH -dNOPAUSE 
-dNOPROMPT -dMaxBitmap=500000000 -dAlignToPixels=0 -dGridFitTT=2 -sDEVICE=pnggray" 
-dTextAlphaBits=4 -dGraphicsAlphaBits=4 "-r72x72" "-sOutputFile=Test.%d.png" "-fTest.pdf" 

而這會告訴我們,創建的文件已損壞。

**** Error reading a content stream. The page may be incomplete. 
**** File did not complete the page properly and may be damaged. 
**** Error reading a content stream. The page may be incomplete. 
**** File did not complete the page properly and may be damaged. 

**** This file had errors that were repaired or ignored. 
**** The file was produced by: 
**** >>>> Microsoft? Word 2013 <<<< 
**** Please notify the author of the software that produced this 
**** file that it does not conform to Adobe's published PDF 
**** specification. 

這可以通過使用不同的程序創建輸入文件來解決。

+0

將Word 2013中的文件保存爲PDF是導致此問題的原因。使用另一種方法從Word轉換爲PDF解決了此問題。謝謝你的幫助。 – Steve