Add, Remove, Extract, and Replace Images in PDF using C#
Live Chat Icon For mobile
Live Chat Icon
Popular Categories.NET  (174).NET Core  (29).NET MAUI  (207)Angular  (109)ASP.NET  (51)ASP.NET Core  (82)ASP.NET MVC  (89)Azure  (41)Black Friday Deal  (1)Blazor  (215)BoldSign  (14)DocIO  (24)Essential JS 2  (107)Essential Studio  (200)File Formats  (66)Flutter  (133)JavaScript  (221)Microsoft  (119)PDF  (81)Python  (1)React  (100)Streamlit  (1)Succinctly series  (131)Syncfusion  (915)TypeScript  (33)Uno Platform  (3)UWP  (4)Vue  (45)Webinar  (51)Windows Forms  (61)WinUI  (68)WPF  (159)Xamarin  (161)XlsIO  (36)Other CategoriesBarcode  (5)BI  (29)Bold BI  (8)Bold Reports  (2)Build conference  (8)Business intelligence  (55)Button  (4)C#  (147)Chart  (131)Cloud  (15)Company  (443)Dashboard  (8)Data Science  (3)Data Validation  (8)DataGrid  (63)Development  (628)Doc  (8)DockingManager  (1)eBook  (99)Enterprise  (22)Entity Framework  (5)Essential Tools  (14)Excel  (40)Extensions  (22)File Manager  (7)Gantt  (18)Gauge  (12)Git  (5)Grid  (31)HTML  (13)Installer  (2)Knockout  (2)Language  (1)LINQPad  (1)Linux  (2)M-Commerce  (1)Metro Studio  (11)Mobile  (507)Mobile MVC  (9)OLAP server  (1)Open source  (1)Orubase  (12)Partners  (21)PDF viewer  (43)Performance  (12)PHP  (2)PivotGrid  (4)Predictive Analytics  (6)Report Server  (3)Reporting  (10)Reporting / Back Office  (11)Rich Text Editor  (12)Road Map  (12)Scheduler  (52)Security  (3)SfDataGrid  (9)Silverlight  (21)Sneak Peek  (31)Solution Services  (4)Spreadsheet  (11)SQL  (10)Stock Chart  (1)Surface  (4)Tablets  (5)Theme  (12)Tips and Tricks  (112)UI  (387)Uncategorized  (68)Unix  (2)User interface  (68)Visual State Manager  (2)Visual Studio  (31)Visual Studio Code  (19)Web  (592)What's new  (332)Windows 8  (19)Windows App  (2)Windows Phone  (15)Windows Phone 7  (9)WinRT  (26)
Add, Remove, Extract and Replace Images in PDF using C

Add, Remove, Extract, and Replace Images in PDF using C#

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. 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 is a .NET PDF library that allows users to add and manipulate images in PDF files without any reference to Adobe dependencies.

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

Experience a leap in PDF technology with Syncfusion's PDF Library, shaping the future of digital document processing.

Getting started with app creation

  1. Create a Console application using 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.
    Install-Package Syncfusion.Pdf.Net.Core

Add an Image in a 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#.

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#
Image added in a PDF Document Using C#

Unleash the full potential of Syncfusion's PDF Library! Explore our advanced resources and empower your apps with cutting-edge functionalities.

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 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#.

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 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#.

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#
Removing an image from a PDF using C#

Embark on a virtual tour of Syncfusion's PDF Library through interactive demos.

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 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.

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#
Replacing an image in a PDF using C#

Resource

Also, you can get the complete example on GitHub: Add, Extract, Remove, and Replace Images from PDF documents using C#.

Syncfusion’s high-performance PDF Library allows you to create PDF documents from scratch without Adobe dependencies.

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 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, 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, Direct-Trac, or feedback portal. We are happy to assist you!

Related blogs

Tags:

Share this post:

Popular Now

Be the first to get updates

Subscribe RSS feed

Be the first to get updates

Subscribe RSS feed