这个问题已经在这里讨论过了:GhostscriptRasterizer Objects Returns 0 as PageCount value,但是这个问题的答案并没有帮助我解决这个问题。
在我的例子中,从kat到旧版本的Ghostscript没有帮助。26和25。我总是让PageCount = 0,如果版本低于27,我会得到一个错误"Native Ghostscript library not found“。
private static void PdfToPng(string inputFile, string outputFileName)
{
var xDpi = 100; //set the x DPI
var yDpi = 100; //set the y DPI
var pageNumber = 1; // the pages in a PDF document
using (var rasterizer = new GhostscriptRasterizer()) //create an instance for GhostscriptRasterizer
{
rasterizer.Open(inputFile); //opens the PDF file for rasterizing
//set the output image(png's) complete path
var outputPNGPath = Path.Combine(outputFolder, string.Format("{0}_Page{1}.png", outputFileName,pageNumber));
//converts the PDF pages to png's
var pdf2PNG = rasterizer.GetPage(xDpi, yDpi, pageNumber);
//save the png's
pdf2PNG.Save(outputPNGPath, ImageFormat.Png);
Console.WriteLine("Saved " + outputPNGPath);
}
}发布于 2019-08-29 22:05:54
我也在为同样的问题而苦苦挣扎,最终我使用了iTextSharp来获取页数。以下是产品代码的一段代码:
using (var reader = new PdfReader(pdfFile))
{
// as a matter of fact we need iTextSharp PdfReader (and all of iTextSharp) only to get the page count of PDF document;
// unfortunately GhostScript itself doesn't know how to do it
pageCount = reader.NumberOfPages;
}这不是一个完美的解决方案,但这恰恰解决了我的问题。我在那里留下这条评论是为了提醒自己,我必须找到一种更好的方法,但我从来没有费心回来,因为它就是这样工作得很好……
在iTextSharp.text.pdf命名空间中定义了PdfReader类。
我使用Ghostscript.NET.GhostscriptPngDevice而不是GhostscriptRasterizer来栅格化文档中的特定页面。
下面是我的方法,它将页面栅格化并保存到PNG文件中
private static void PdfToPngWithGhostscriptPngDevice(string srcFile, int pageNo, int dpiX, int dpiY, string tgtFile)
{
GhostscriptPngDevice dev = new GhostscriptPngDevice(GhostscriptPngDeviceType.PngGray);
dev.GraphicsAlphaBits = GhostscriptImageDeviceAlphaBits.V_4;
dev.TextAlphaBits = GhostscriptImageDeviceAlphaBits.V_4;
dev.ResolutionXY = new GhostscriptImageDeviceResolution(dpiX, dpiY);
dev.InputFiles.Add(srcFile);
dev.Pdf.FirstPage = pageNo;
dev.Pdf.LastPage = pageNo;
dev.CustomSwitches.Add("-dDOINTERPOLATE");
dev.OutputPath = tgtFile;
dev.Process();
}希望这能帮上忙。
https://stackoverflow.com/questions/57709390
复制相似问题