Thursday, 12 December 2013 07:44

Extract Image from PDF and Save it to New PDF File in C#

Written by  Administrator
Rate this item
(0 votes)

Extracting image from PDF is not a complex operation, but sometimes we need to save the image to new PDF file. So the article describes the simple c# code to extract image from PDF and save it to new PDF file through a professional PDF .NET library Spire.PDF.

First we need to complete the preparatory work before the procedure:

  • Download the Spire.PDF and install it on your machine.
  • Add the Spire.PDF.dll files as reference.
  • Open bin folder and select the three dll files under .NET 4.0.
  • Right click property and select properties in its menu.
  • Set the target framework as .NET 4.
  • Add Spire.PDF as namespace.

The following steps will show you how to do this with ease:

Step 1: Create a PDF document.

[C#]
PdfDocument doc = new PdfDocument();
doc.LoadFromFile(@"..\..\Sample.pdf");

Step 2: Extract the image from PDF document.

[C#]
doc.ExtractImages();

Step 3: Save image file.

[C#]
image.Save("image.png",System.Drawing.Imaging.ImageFormat.Png);
PdfImage image2 = PdfImage.FromFile(@"image.png");
PdfDocument doc2=new PdfDocument ();
PdfPageBase page=doc2.Pages.Add();

Step 4: Draw image to new PDF file.

[C#]
float width = image.Width * 0.75f;
float height = image.Height * 0.75f;
float x = (page.Canvas.ClientSize.Width - width) / 2;
page.Canvas.DrawImage(image2,x,60,width,height);
doc2.SaveToFile(@"..\..\Image.pdf");

Here is the whole code:

[C#]
static void Main(string[] args)
        {
            PdfDocument doc = new PdfDocument();
            doc.LoadFromFile(@"..\..\Sample.pdf");
            doc.ExtractImages();
            image.Save("image.png",System.Drawing.Imaging.ImageFormat.Png);
            PdfImage image2 = PdfImage.FromFile(@"image.png");
            PdfDocument doc2=new PdfDocument ();
            PdfPageBase page=doc2.Pages.Add();
            float width = image.Width * 0.75f;
            float height = image.Height * 0.75f;
            float x = (page.Canvas.ClientSize.Width - width) / 2;
            page.Canvas.DrawImage(image2,x,60,width,height);
            doc2.SaveToFile(@"..\..\Image.pdf");
        }

Here comes to the preview of the effect picture:

extract image from pdf

draw image to new pdf

Additional Info

  • tutorial_title: Extract Image and Save it to New PDF
Last modified on Tuesday, 15 July 2014 07:29