Convert PDF Page to Image in C#

Image is one of the major data components except for text information, so convert PDF to image is a common need for users. Due to the complexity of PDF format, it is difficult to parse, draw and display content from PDF document. This article offers you a solution of convert PDF page to image in C# by using Spire.PDF.

By using Spire.PDF, you can easily convert any specific page of PDF document to BMP and Metafile image in .NET applications like console, Win Forms and ASP.NET. Make sure Spire.PDF for .NET has been installed correctly. The following steps demonstrate how to convert PDF to image with C# code in detail.

Step 1: Firstly Create a Console application, and reference System. Drawing.dll, Spire. Pdf.dll.

Step 2: Initiate an object of Spire. Pdf. PdfDocument

PdfDocument doc = new PdfDocument();

Step3: Call Spire. Pdf. PdfDocument object LoadFromFile method, and load a PDF document.

doc.LoadFromFile("sample.pdf");

Step 4: Now you can call SaveAsImage method of Spire. Pdf. PdfDocument object and save particular page as System.Drawing.Image object.

Image bmp = doc.SaveAsImage(0);

Step 5: Next, call another reload method of SaveAsImage from object of Spire.Pdf.PdfDocument, and save the particular page in the PDF file as System.Drawing.Imaging.Metafile object.

Image emf = doc.SaveAsImage(0,Spire.Pdf.Graphics.PdfImageType.Metafile);
Image zoomImg = new Bitmap((int)(emf.Size.Width * 2), (int)(emf.Size.Height * 2));
using (Graphics g = Graphics.FromImage(zoomImg))
{
  g.ScaleTransform(2.0f, 2.0f);
  g.DrawImage(emf, new Rectangle(new Point(0, 0), emf.Size), new Rectangle(new Point(0, 0), emf.Size), GraphicsUnit.Pixel);              
}

The following is the full code snippet used to display complete code needed when convert PDF to Image:

static void Main(string[] args)
{
 PdfDocument doc = new PdfDocument();
 doc.LoadFromFile("sample.pdf");
 Image bmp = doc.SaveAsImage(0);
 Image emf = doc.SaveAsImage(0,Spire.Pdf.Graphics.PdfImageType.Metafile);
 Image zoomImg = new Bitmap((int)(emf.Size.Width * 2), (int)(emf.Size.Height * 2));
 using (Graphics g = Graphics.FromImage(zoomImg))
  {
   g.ScaleTransform(2.0f, 2.0f);
   g.DrawImage(emf, new Rectangle(new Point(0, 0), emf.Size), new Rectangle(new Point(0, 0), emf.Size), GraphicsUnit.Pixel);              
  }
 bmp.Save("convertToBmp.bmp", ImageFormat.Bmp);
 System.Diagnostics.Process.Start("convertToBmp.bmp");
 emf.Save("convertToEmf.png", ImageFormat.Png);
 System.Diagnostics.Process.Start("convertToEmf.png");
 zoomImg.Save("convertToZoom.png", ImageFormat.Png);
 System.Diagnostics.Process.Start("convertToZoom.png");
 }

Run it, then you will get the image like the following:

Convert PDF Page to Image in C#