无法将PDF页面转换为图像



我想将pdf文件的每个页面转换为新图像。要做到这一点,我使用GhostScript.Net。问题是我无法弄清楚为什么pageImage在System.Drawing.Image pageImage = rasterizer.GetPage(dpi, i);行返回null。下面是我使用的方法:

public static List<string> GetPDFPageText(Stream pdfStream, string dataPath)
{
try
{
int dpi = 100;
GhostscriptVersionInfo lastInstalledVersion =
GhostscriptVersionInfo.GetLastInstalledVersion(
GhostscriptLicense.GPL | GhostscriptLicense.AFPL,
GhostscriptLicense.GPL);
List<string> textParagraphs = new List<string>();
using (GhostscriptRasterizer rasterizer = new GhostscriptRasterizer())
{
rasterizer.Open(pdfStream, lastInstalledVersion,false);
for (int i = 1; i <= rasterizer.PageCount; i++)
{
// here is the problem, pageImage returns null
System.Drawing.Image pageImage = rasterizer.GetPage(dpi, i);
// rest of code is unrelated to problem..

}
}
return textParagraphs;
}
catch (Exception ex)
{
throw new Exception("An error occurred.");
}

}

函数参数Stream pdfStream来自以下代码:

using (StreamCollection streamCollection = new StreamCollection())
{
FileStream imageStream = new FileStream(imagePath, FileMode.Open, FileAccess.Read);
// This is the parameter I used for "Stream pdfStream"
FileStream pdfStream = new FileStream(pdfPath, FileMode.Open, FileAccess.Read);
streamCollection.Streams.Add(imageStream);
streamCollection.Streams.Add(pdfStream);
PDFHelper.SavePDFByFilesTest(dataPath, streamCollection.Streams,mergedFilePath);
}

我已经习惯了使用StreamCollection类,因为我以前在类似的情况下使用过它,它工作了。我验证了文件路径为真,并且流正确地拥有该文件。此外,我尝试使用MemoryStream代替FileStreamfilename代替stream,只是为了看看问题是否与他们有关。你有什么建议吗?我真的很感激。

好了,我知道为什么它不起作用了。我使用kj提到的最新版本的Ghostscript(9.56.1)(感谢您的响应),它使用新的PDF解释器作为默认的PDF解释器。我猜想由于某些原因它没有正常工作,因为它是一个真正的新工具,现在仍然可能有一些小问题。我添加了以下行来使用老式的PDF解释器:

rasterizer.CustomSwitches.Add("-dNEWPDF=false");

还定义了生成图像的分辨率,如下行:

rasterizer.CustomSwitches.Add("-r300x300");

此外,我将分享StreamCollection类的结构,我在这里用作参考来实现这个类。希望能对大家有所帮助。

public class StreamCollection :  IDisposable
{
private bool disposedValue;

public List<Stream> Streams { get; set; }
public StreamCollection()
{
Streams = new List<Stream>();
}

protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
// TODO: dispose managed state (managed objects)
if (this.Streams != null && this.Streams.Count>0)
{
foreach (var stream in this.Streams)
{
if (stream != null)
stream.Dispose();
}
}
}
// TODO: free unmanaged resources (unmanaged objects) and override finalizer
// TODO: set large fields to null
disposedValue = true;
}
}
// // TODO: override finalizer only if 'Dispose(bool disposing)' has code to free unmanaged resources
// ~StreamCollection()
// {
//     // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
//     Dispose(disposing: false);
// }
public void Dispose()
{
// Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
}

最新更新