首页 文章

如何使用iTextSharp将PDF页面绘制到System.Drawing.Image中?

提问于
浏览
0

我是使用iTextSharp的新手 . 我在工作中有一个PDF文档存储库,我需要将其复制到图像中(每页一个图像)并处理它们 . 这些PDF包含文本,光栅图像和矢量图像,可能还包含更多内容 . 我对PDF结构不太熟悉,在购买一些PDF包之前我宁愿使用iTextSharp .

我已经完成了使用C#上的iTextSharp从每个PDF文档中提取文本和光栅图像的工作,但是尝试将它们渲染到图像中会产生混合结果,如果有矢量图形,我无法轻易地提取和渲染它们 . .

我为PDF内部工作和iTextSharp缺乏知识而道歉,但有没有办法使用iTextSharp将每个PDF页面绘制成System.Drawing.Image对象,就像它们在PDF阅读器上出现一样程序?如果有一个像 System.Drawing.Bitmap RenderPage(PdfReader reader, int iPage) 这样的方法会很棒 .

谢谢大家 . 任何帮助将不胜感激 .

1 回答

  • 1

    我找到了一种方法来使用另一个库 . 我用过Ghostscript.NET .

    Ghostscript.NET是Ghostscript库本机代码的.NET包装器,因此,它可能无法在Windows RT设备上运行,因为它需要实际的本机代码DLL才能工作 .

    通过NuGet包安装Ghostscript.NET的说明在本网站:

    https://www.nuget.org/packages/Ghostscript.NET/

    安装软件包后,您需要Ghostscript本机代码DLL . 要获得它,首先从下面的链接安装Ghostscript,然后在安装目录中找到gsdll32.dll并将其复制到一个安全的地方:

    http://www.ghostscript.com/download/gsdnld.html

    此DLL用于32位 . 如果您使用64位编程,则应下载并安装64位版本 . 获取DLL后,您可以卸载Ghostscript,因为DLL是独立的 .

    最后,我编写了以下代码(假设Ghostscript本机DLL与应用程序在同一路径上),以将PDF页面呈现为System.Drawing.Images:

    string sDLLPath = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath),
        "gsdll32.dll");
    GhostscriptVersionInfo gvi = new GhostscriptVersionInfo(sDLLPath);
    using (GhostscriptRasterizer rasterizer = new GhostscriptRasterizer())
    {
        rasterizer.Open("sample.pdf", gvi, false);
    
        int dpi_x = 96;
        int dpi_y = 96;
        for (int i = 1; i <= rasterizer.PageCount; i++)
        {
            Image img = rasterizer.GetPage(dpi_x, dpi_y, i);
            // System.Drawing.Image obtained. Now it can be used at will.
            // Simply save it to storage as an example.
            img.Save(Path.Combine("C:\\Temp", "page_" + i + ".png")),
                System.Drawing.Imaging.ImageFormat.Png);
        }
    }
    

相关问题