Live Chat Icon For mobile
Live Chat Icon
Popular Categories.NET  (151).NET Core  (25)Angular  (49)ASP.NET  (48)ASP.NET Core  (64)ASP.NET MVC  (86)Azure  (28)Blazor  (97)DocIO  (20)Essential JS 2  (71)Essential Studio  (163)File Formats  (20)Flutter  (111)JavaScript  (148)Microsoft  (101)PDF  (59)React  (33)Succinctly series  (122)Syncfusion  (480)TypeScript  (30)Uno Platform  (3)UWP  (4)Vue  (26)Webinar  (25)Windows Forms  (55)WinUI  (21)WPF  (122)Xamarin  (130)XlsIO  (24)Other CategoriesBarcode  (4)BI  (29)Bold BI  (3)Build conference  (6)Business intelligence  (53)Button  (4)C#  (107)Chart  (51)Cloud  (9)Company  (445)Dashboard  (6)Data Science  (3)Data Validation  (5)DataGrid  (47)Development  (257)Doc  (7)DockingManager  (1)eBook  (93)Enterprise  (22)Entity Framework  (5)Essential Tools  (14)Excel  (20)Extensions  (13)File Manager  (4)Gantt  (9)Gauge  (7)Git  (4)Grid  (27)HTML  (9)Installer  (2)Knockout  (2)LINQPad  (1)Linux  (2)M-Commerce  (1)Metro Studio  (11)Mobile  (227)Mobile MVC  (9)OLAP server  (1)Open source  (1)Orubase  (12)Partners  (21)PDF viewer  (23)Performance  (6)PHP  (1)PivotGrid  (4)Predictive Analytics  (6)Report Server  (3)Reporting  (10)Reporting / Back Office  (11)Rich Text Editor  (6)Road Map  (9)Scheduler  (26)SfDataGrid  (9)Silverlight  (21)Sneak Peek  (19)Solution Services  (2)Spreadsheet  (9)SQL  (7)Stock Chart  (1)Surface  (4)Tablets  (5)Theme  (11)Tips and Tricks  (60)UI  (131)Uncategorized  (68)Unix  (2)User interface  (68)Visual State Manager  (1)Visual Studio  (19)Visual Studio Code  (11)Web  (215)What's new  (140)Windows 8  (19)Windows App  (1)Windows Phone  (15)Windows Phone 7  (9)WinRT  (26)
Share on twitter
Share on facebook
Share on linkedin
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 the Adobe dependencies.

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

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

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#

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

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:

Share on twitter
Share on facebook
Share on linkedin
Popular Now

Be the first to get updates

Subscribe RSS feed
Scroll To Top