Add, Remove, Extract and Replace Images in PDF using C#
Tags: csharp, dotnet, pdf, productivity
Published: 2021-08-23 13:48:04

---
title: Add, Remove, Extract and Replace Images in PDF using C#
published: true
date: 2021-08-23 11:30:49 UTC
tags: csharp, dotnet, PDF, productivity
canonical_url: https://www.syncfusion.com/blogs/post/add-remove-extract-and-replace-images-in-pdf-using-csharp.aspx
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1gj25n62027ppxhtbgl2.png
---

PDF has become one of the most popular and widely used file formats. Images are a vital part of PDF files. Adding, removing, extracting, and replacing images in a PDF file is usually very hard without [Adobe Acrobat Pro DC](https://www.adobe.com/in/acrobat/acrobat-pro.html "Link to Adobe Acrobat Pro DC"). In this article, we are going to learn how to do this in a PDF document using C# with the help of our Syncfusion PDF Library.

The Syncfusion [PDF Library](https://www.syncfusion.com/pdf-framework/net/ "Link to Syncfusion .NET PDF Library") is a .NET PDF library that allows users to add and manipulate images in PDF files without any reference to the Adobe dependencies.

The following are the steps we will see in this article:

- [Getting started with app creation](#getting-started-with-app-creation)
- [Add an image in a PDF using C#](#add-an-image-in-pdf-file-using-c-sharp)
- [Extract images from a PDF using C#](#extract-images-from-a-pdf-using-c-sharp)
- [Remove images from a PDF using C#](#remove-images-from-a-pdf-using-c-sharp)
- [Replace image in a PDF using C#](#replace-images-in-a-pdf-using-c-sharp)

## Getting started with app creation

1. Create a [Console application using Visual Studio](https://docs.microsoft.com/en-us/visualstudio/get-started/csharp/tutorial-console?view=vs-2019 "Link to Tutorial: Create a simple C# console app in Visual Studio").
2. Open the Package Manager Console from **Tools > NuGet Package Manager > Package Manager Console**.
3. Execute the following command to install the [Syncfusion PDF .NET Core NuGet package](https://www.nuget.org/packages/Syncfusion.Pdf.Net.Core/ "Link to the Syncfusion.Pdf.Net.Core NuGet package").  

| Install-Package Syncfusion.Pdf.Net.Core |

## Add an Image in PDF file using C#

Follow these steps to add an image to a PDF file using the Syncfusion PDF library:

1. Use the  **_PdfLoadedDocument_** class to load an existing PDF document.
2. Then, get the reference of the page (where you want to include the image) in the **_PdfLoadedPage _** object.
3. Now, get the **_PdfGraphics_**  object from the page.
4. Load the image from a file to the **_PdfBitmap_ ** object.
5. Draw the image on the page using the **_DrawImage_** method.
6. Finally, save the PDF file using the **_Save _** method.

The following code example shows how to add an image to a PDF file using C#.

```csharp
using System.IO;
using Syncfusion.Drawing;
using Syncfusion.Pdf;
using Syncfusion.Pdf.Graphics;
using Syncfusion.Pdf.Parsing;

namespace Add_image
{
    class Program
    {
        static void Main(string[] args)
        {
            //Load a PDF document.
            PdfLoadedDocument doc = new PdfLoadedDocument(new FileStream("../../../../../Data/input.pdf",FileMode.Open));
            //Get first page from document.
            PdfLoadedPage page = doc.Pages[0] as PdfLoadedPage;
            //Create PDF graphics for the page.
            PdfGraphics graphics = page.Graphics;
            //Load the image from the disk.
            PdfBitmap image = new PdfBitmap(new FileStream("../../../../../Data/Sample.jpg",FileMode.Open));
            //Draw the image.
            graphics.DrawImage(image, new RectangleF(50, 150, 400, 250));
            //Create stream object to save file.
            FileStream stream = new FileStream("Output.pdf", FileMode.Create);
            //Save the document.
            doc.Save(stream);
            //Close the document.
            doc.Close(true);
            //Close stream.
            stream.Close();
        }
    }
}
```

By executing this code example, you will get a PDF document similar to the following screenshot.

![Adding an Image in a PDF Document Using C#](https://www.syncfusion.com/blogs/wp-content/uploads/2021/08/Adding-an-Image-in-a-PDF-Document-Using-C.png)<figcaption>Image added in a PDF Document Using C#</figcaption>

## Extract images from a PDF using C#

Let’s see how to extract all the images from a PDF file by following these steps:

1. Use the  **_PdfLoadedDocument_** class to load an existing PDF document.
2. Get the reference of the page (Which contains the images) in the **_PdfLoadedPage_** object.
3. Then, call the method **_ExtractImages_** to extract all the images from that particular page.
4. Finally, save the extracted images on the disk.

**Note:** Install the [Syncfusion.Pdf.Imaging.Net.Core](https://www.nuget.org/packages/Syncfusion.Pdf.Imaging.Net.Core/ "Link to the Syncfusion.Pdf.Imaging.Net.Core NuGet package") NuGet Package to extract images in a .NET Core application.

The following code example shows how to extract images from an existing PDF document using C#.

```csharp
using System.Drawing;
using System.IO;
using Syncfusion.Pdf;
using Syncfusion.Pdf.Exporting;
using Syncfusion.Pdf.Parsing;

namespace Extract_images
{
    class Program
    {
        static void Main(string[] args)
        {
            //Load the template document.
            PdfLoadedDocument doc = new PdfLoadedDocument(new FileStream("../../../../../Data/ImageInput.pdf",FileMode.Open));
            //Load the first page.
            PdfPageBase pageBase = doc.Pages[0];
            //Extract images from first page.
            Image[] extractedImages = pageBase.ExtractImages();
            //Save images to file.
            for (int i = 0; i < extractedImages.Length; i++)
            {
                extractedImages[i].Save("Image" + i + ".jpg");
            }

            //Close the document.
            doc.Close(true);

        }
    }
}
```

## Remove images from a PDF using C#

You can easily remove the unwanted images from a PDF document with the help of our Syncfusion PDF Library. This will reduce the file size considerably.

Follow these steps to remove images from a PDF document:

- Use the **_PdfLoadedDocument_** class to load an existing PDF document.
- Get the reference for the page (Where you want to remove the image) in the **_PdfLoadedPage _** object_._
- Then, call the **_RemoveImage_** method with the  **_PdfImageInfo_**  object to remove the image.
- Finally, save the modified PDF document.

**Note:** Install the [Syncfusion.Pdf.Imaging.Net.Core](https://www.nuget.org/packages/Syncfusion.Pdf.Imaging.Net.Core/ "Link to the Syncfusion.Pdf.Imaging.Net.Core NuGet package") NuGet package to remove an image in a .NET Core application.

The following code example shows how to remove an image from an existing PDF document using C#.

```csharp
using Syncfusion.Pdf;
using Syncfusion.Pdf.Exporting;
using Syncfusion.Pdf.Parsing;
using System.IO;

namespace Remove_images
{
    class Program
    {
        static void Main(string[] args)
        {
            //Load the template document.
            PdfLoadedDocument doc = new PdfLoadedDocument(new FileStream("../../../../../Data/ImageInput.pdf",FileMode.Open));
            //Get first page of the document.
            PdfLoadedPage page = doc.Pages[0] as PdfLoadedPage;
            //Remove first image in the page.
            page.RemoveImage(page.GetImagesInfo()[0]);
            FileStream stream = new FileStream("output.pdf", FileMode.Create);
            //Save the modified document to file.
            doc.Save(stream);
            //Close the PDF document.
            doc.Close(true);
            stream.Close();

        }
    }
}
```

By executing this code example, you will get an output similar to the following screenshot.

![Removing an image from a PDF using C#](https://www.syncfusion.com/blogs/wp-content/uploads/2021/08/Removing-images-from-a-PDF-using-C.png)<figcaption>Removing an image from a PDF using C#</figcaption>

## Replace images in a PDF using C#

You can replace an existing image with a new image or modify an existing image in a PDF document.

To do so, we have to:

1. First, remove the image that needs to be replaced.
2. Then, draw the new image where the removed image was.

**Note:** Please install the [Syncfusion.Pdf.Imaging.Net.Core](https://www.nuget.org/packages/Syncfusion.Pdf.Imaging.Net.Core/ "Link to the Syncfusion.Pdf.Imaging.Net.Core NuGet package") NuGet package to replace an image in a .NET Core application.

In the following example, we have replaced an existing image in a PDF document with a pixelated image.

```csharp
using Syncfusion.Pdf;
using Syncfusion.Pdf.Exporting;
using Syncfusion.Pdf.Graphics;
using Syncfusion.Pdf.Parsing;
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;

namespace Replace_image
{
    class Program
    {
        static void Main(string[] args)
        {
            //Load the template document.
            PdfLoadedDocument doc = new PdfLoadedDocument(new FileStream("../../../../../../Data/ImageInput.pdf",FileMode.Open));
            //Get first page of the document.
            PdfLoadedPage page = doc.Pages[0] as PdfLoadedPage;
            //Get image info of the first image.
            PdfImageInfo pdfImageInfo = page.GetImagesInfo()[0];
            RectangleF bounds = pdfImageInfo.Bounds;
            //Remove first image in the page.
            page.RemoveImage(pdfImageInfo);
            //Pixlate the existing image.
            Stream pixlated = Pixelate((Bitmap)pdfImageInfo.Image, new Rectangle(0, 0, pdfImageInfo.Image.Width, pdfImageInfo.Image.Height), 15);
            //Draw the pixlated image in the existing image bounds.
            page.Graphics.DrawImage(new PdfBitmap(pixlated), bounds.X,bounds.Y,bounds.Width,bounds.Height);

            FileStream stream = new FileStream("output.pdf", FileMode.Create);
            //Save the modified document to file.
            doc.Save(stream);
            //Close the PDF document.
            doc.Close(true);

        }

        private static Stream Pixelate(Bitmap image, Rectangle rectangle, Int32 pixelateSize)
        {
            Bitmap pixelated = new System.Drawing.Bitmap(image.Width, image.Height);

            // Make an exact copy of the bitmap provided.
            using (Graphics graphics = System.Drawing.Graphics.FromImage(pixelated))
                graphics.DrawImage(image, new System.Drawing.Rectangle(0, 0, image.Width, image.Height),
                    new Rectangle(0, 0, image.Width, image.Height), GraphicsUnit.Pixel);

            // look at every pixel in the rectangle while making sure we're within the image bounds.
            for (Int32 xx = rectangle.X; xx < rectangle.X + rectangle.Width && xx < image.Width; xx += pixelateSize)
            {
                for (Int32 yy = rectangle.Y; yy < rectangle.Y + rectangle.Height && yy < image.Height; yy += pixelateSize)
                {
                    Int32 offsetX = pixelateSize / 2;
                    Int32 offsetY = pixelateSize / 2;

                    // Make sure that the offset is within the boundry of the image.
                    while (xx + offsetX >= image.Width) offsetX--;
                    while (yy + offsetY >= image.Height) offsetY--;

                    // Get the pixel color in the center.
                    Color pixel = pixelated.GetPixel(xx + offsetX, yy + offsetY);

                    // For each pixel in the pixelate size, set it to the center color.
                    for (Int32 x = xx; x < xx + pixelateSize && x < image.Width; x++)
                        for (Int32 y = yy; y < yy + pixelateSize && y < image.Height; y++)
                            pixelated.SetPixel(x, y, pixel);
                }
            }

            MemoryStream stream = new MemoryStream();
            pixelated.Save(stream, ImageFormat.Jpeg);
            stream.Position = 0;
            pixelated.Dispose();
            return stream;
        }
    }
}
```

By executing this code example, you will get an image similar to the following screenshot.

![Replacing an image in a PDF using C#](https://www.syncfusion.com/blogs/wp-content/uploads/2021/08/Replacing-image-in-a-PDF-using-C.png)<figcaption>Replacing an image in a PDF using C#</figcaption>

## Resource

Also, you can get the complete example on GitHub: [Add, Extract, Remove, and Replace Images from PDF documents using C#](https://github.com/SyncfusionExamples/pdf_image_handling "Link to PDF Image Handling demo on GitHub").

## Conclusion

Thanks for reading! In this blog post, you have learned how to add, extract, remove, and replace images in a PDF document using C#. Our Syncfusion [PDF Library](https://www.syncfusion.com/pdf-framework/net/ "Link to Syncfusion PDF Library") offers PDF viewer controls to view, review, and print PDF files. Its powerful conversion APIs make it easy to convert HTML, Word, Excel, PowerPoint, and images to PDF format. Take a moment to peruse our [documentation](https://help.syncfusion.com/file-formats/pdf/working-with-images "Link to Working with images using various options"), where you’ll find other options and features, all with accompanying code examples.

A single image can say a thousand words. So, let’s use our Syncfusion PDF Library to easily handle images in a PDF document using C#!

If you have any questions about these features, please let us know in the comments section of this blog post. You can also contact us through our [support forum](https://www.syncfusion.com/forums "Link to the Syncfusion support forum"), [Direct-Trac](https://www.syncfusion.com/support/directtrac "Link to the Syncfusion support system Direct Trac"), or [feedback portal](https://www.syncfusion.com/feedback/pdf "Link to Syncfusion Feedback Portal"). We are happy to assist you!

## Related blogs

- [6 Easy Ways to Split a PDF Document Using C#](https://dev.to/karthickramasamy08/6-easy-ways-to-split-a-pdf-document-using-c-1hem-temp-slug-8330313 "Link to 6 Easy Ways to Split a PDF Document Using C# blog")
- [Double-Check Content Using Redaction Annotation in PDFs with C#](https://dev.to/syncfusion/double-check-content-using-redaction-annotation-in-pdfs-with-c-1h3n "Link to Double-Check Content Using Redaction Annotation in PDFs with C# blog")
- [9 Types of Useful Data You Can Extract from a PDF Using C#](https://dev.to/kartik110895/9-types-of-useful-data-you-can-extract-from-a-pdf-using-c-5d69-temp-slug-7256836 "Link to 9 Types of Useful Data You Can Extract from a PDF Using C# blog")
- [7 Ways to Compress PDF Files in C#, VB.NET](https://www.syncfusion.com/blogs/post/7-ways-to-compress-pdf-files.aspx "Link to 7 Ways to Compress PDF Files in C#, VB.NET blog")