3

这个问题已经在这里讨论过:GhostscriptRasterizer Objects Returns 0 as PageCount value 但是这个问题的答案并没有帮助我解决问题。

就我而言,从 kat 到旧版本的 Ghostscript 没有帮助。26 和 25。我的 PageCount = 0,如果版本低于 27,我收到错误“未找到本机 Ghostscript 库”。

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);
                 }


            }
4

1 回答 1

3

我在同样的问题上苦苦挣扎,最终使用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;
}

不是一个完美的解决方案,但这正是解决我的问题的原因。我把那条评论留在那里是为了提醒自己,我必须以某种方式找到更好的方法,但我从来没有费心回来,因为它工作得很好......

PdfReader类在iTextSharp.text.pdf命名空间中定义。

我正在使用Ghostscript.NET.GhostscriptPngDevice而不是GhostscriptRasterizer栅格化 PDF 文档的特定页面。

这是我将页面栅格化并将其保存到 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();
}

希望这会有所帮助...

于 2019-08-29T14:05:54.277 回答