使用PDFsharp将PDF转换为JPEG(资源为空)

3
我将尝试使用PDFsharp将PDF转换为JPEG。
以下是我的代码:
PdfSharp.Pdf.PdfDocument document = PdfSharp.Pdf.IO.PdfReader.Open(doc);
PdfSharp.Pdf.PdfPage page = document.Pages[0];

// get resources dictionary
PdfSharp.Pdf.PdfDictionary resources = page.Elements.GetDictionary("/resources");
if (resources != null)
{
    // get external objects dictionary
    PdfSharp.Pdf.PdfDictionary xobjects = resources.Elements.GetDictionary("/xobject");
    if (xobjects != null)
    {
        ICollection<PdfSharp.Pdf.PdfItem> items = xobjects.Elements.Values;

        // iterate references to external objects
        foreach (PdfSharp.Pdf.PdfItem item in items)
        {
            PdfSharp.Pdf.Advanced.PdfReference reference = item as PdfSharp.Pdf.Advanced.PdfReference;
            if (reference != null)
            {
                PdfSharp.Pdf.PdfDictionary xobject = reference.Value as PdfSharp.Pdf.PdfDictionary;

                // is external object an image?
                if (xobject != null && xobject.Elements.GetString("/subtype") == "/image")
                {
                    ExportJpegImage(xobject);
                }
            }
        }
    }
}

这一行代码:if (resources != null) 返回的是 false。我不确定 resources 应该包含什么,但它似乎对于其余的转换非常重要。我从 PDFsharp 示例网站复制了此代码。我的 PDF 文件可能会有问题吗?我是使用 Word 2010 制作的。


1
资源键应以大写字母'R'开头。您是否尝试使用 /Resources 而不是 /resources?其他键的大小写也有误。或者PDFSharp是否以不区分大小写的方式查找? - mkl
1个回答

3
如果您想将PDF转换为JPEG,并希望使用免费软件库进行操作,请考虑使用ImageMagick。它可以在所有主要平台上运行,因此在Windows上也可以使用。它可以从命令行启动,并且可以设置首选的有损压缩级别。
编辑:啊,我在另一个问题中看到您正在使用ImageMagick的.NET接口。如果您能让它正常工作,那就太好了,但您可能会发现直接使用convert命令更容易!

谢谢回复。是的,我一直在使用ImageMagickNet,但发现它比我预期的更困难。我对.NET世界还比较新,但您知道我是否能够在我的网站中使用convert命令吗? - PFranchise
1
我相信你能做到。只需找到一种在网页内执行系统命令的方法(我不是 .net 程序员),并调用 convert.exe -quality 85 infile.pdf /temp/path/tempfile.jpg - halfer

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接