2015-09-07 37 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