Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting PDF to Jpeg using PDFsharp (resource is null)

I am attempting to convert a pdf to jpeg using PDFsharp.

Here is my code:

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

The line: if (resources != null) is returning false. I am not sure what resources is supposed to contain, but it seems to be important for the rest of the conversion. I copied this code from the PDFsharp example site. Could there be an issue with my PDF? I made it using Word 2010.

like image 219
PFranchise Avatar asked May 13 '26 07:05

PFranchise


1 Answers

If you want to convert a PDF to a JPEG, and want to do it with a free software library, consider ImageMagick. This runs on all major platforms, so you will be fine on Windows. It can be kicked off on the command line, and you can set your preferred lossy compression level.

Edit: ah, I've seen on another question that you're using a .net interface to ImageMagick. That's great if you can get it to work, but you may find it easier just to use the convert command!

like image 57
halfer Avatar answered May 14 '26 20:05

halfer