I need to convert a pdf file into jpeg using C#. And the solution (library) have to be free.

I have searched a lot of information but seems that I don't get nothing clear.

I already tried itextsharp and pdfbox (but this, the pdf2image is only for java, i think) with no success.

I tried to extract the images from the pdf individually, but I have an error of invalid parameters when i try to extract the images... Seems that they have an strange encoding.

Anyone can recommend me any library to save a pdf into a jpeg? Examples will be very appreciated too.

Save pdf to jpeg using c#

Answers

The library xspdf might be helpful here. It is also available as nuget.

  • Create a new winforms app. Add nuget "xspdf" to it.
  • This will also add two native dll's named "xspdf.dll" in folders x86 and x64 to your project. Set "Copy to Output Directory" to "Copy Always".
  • Try out the following code (change paths to suit your setup).
    try
    {
        using (var document = new PdfImageConverter(@"input.pdf"))
        {
            var image = document.PageToImage(0, 300, 300);
            image.Save(@"output.png", ImageFormat.Png);
        }
    }
    catch (Exception ex)
    {
        // handle exception here;
    }

This is how I did it with PDFLibNet:

public void ConvertPDFtoHojas(string filename, String dirOut)
{
    PDFLibNet.PDFWrapper _pdfDoc = new PDFLibNet.PDFWrapper();
    _pdfDoc.LoadPDF(filename);

    for (int i = 0; i < _pdfDoc.PageCount; i++)
    {

        Image img = RenderPage(_pdfDoc, i);

        img.Save(Path.Combine(dirOut, string.Format("{0}{1}.jpg", i,DateTime.Now.ToString("mmss"))));

    }
    _pdfDoc.Dispose();
    return;
}
public  Image RenderPage(PDFLibNet.PDFWrapper doc, int page)
{
    doc.CurrentPage = page + 1;
    doc.CurrentX = 0;
    doc.CurrentY = 0;

    doc.RenderPage(IntPtr.Zero);

        // create an image to draw the page into
        var buffer = new Bitmap(doc.PageWidth, doc.PageHeight);
        doc.ClientBounds = new Rectangle(0, 0, doc.PageWidth, doc.PageHeight);
        using (var g = Graphics.FromImage(buffer))
        {
            var hdc = g.GetHdc();
            try
            {
                doc.DrawPageHDC(hdc);
            }
            finally
            {
                g.ReleaseHdc();
            }
        }
        return buffer;

}