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 dont get nothing cl
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;
}
The library pdfiumviewer might be helpful here. It is also available as nuget.
Try out the following code (change paths to suit your setup).
try
{
using (var document = PdfiumViewer.PdfDocument.Load(@"input.pdf"))
{
var image = document.Render(0, 300, 300, true);
image.Save(@"output.png", ImageFormat.Png);
}
}
catch (Exception ex)
{
// handle exception here;
}
Edit 2: Changed code to show that page index is 0 based as pointed out in comment by S.C. below
Edit 1: Updated solution
Have you tried pdfsharp?
This link might be helpful
2020 ANSWER The new version of IronPDF support converting generated PDF back to .NET Bitmap
Array (for every page) so you can do whatever you want to it. Provided you've already purchased a license, but the license is for converting EVERTHING 2 PDF, not PDF 2 BITMAP, so it worths a shot.
using IronPdf;
using System.Drawing;
var pdf = PdfDocument.FromFile("Example.pdf");
Bitmap[] pageImages = pdf.ToBitmap();
// do whatever that suits your needs here with the array