DEV Community

Cover image for How to add images to PDF in C#
Mehr Muhammad Hamza
Mehr Muhammad Hamza

Posted on

How to add images to PDF in C#

Adding images to PDF documents is a common requirement in applications ranging from report generation to invoice creation. While there are several libraries available for PDF manipulation in C#, IronPDF stands out due to its simplicity, robust feature set, and seamless integration with .NET ecosystems. In this tutorial, we’ll explore how to add images to PDF Document programmatically using IronPDF, with practical examples and best practices.

Why Use IronPDF for PDF Manipulation?

IronPDF is a .NET library that simplifies PDF generation, editing, and rendering. It offers:

  • HTML-to-PDF Conversion: Render PDFs directly from HTML/CSS, enabling dynamic template-based designs.
  • Image Support: Add, resize, and position images in existing or new PDFs.
  • Cross-Platform Compatibility: Works with .NET Core, .NET Framework, and modern .NET versions.
  • Comprehensive API: Methods for text extraction, form filling, encryption, and more.

Unlike libraries that require low-level PDF syntax knowledge, IronPDF abstracts complexity while maintaining flexibility. Its performance and ease of use make it a preferred choice for developers needing to automate PDF workflows.

Prerequisites

Before we dive into the code, make sure you have IronPDF installed in your C# project. You can add it via NuGet Package Manager Console:

Install-Package IronPdf
Enter fullscreen mode Exit fullscreen mode

Adding an Image to a PDF Using IronPDF

When creating a new PDF, one of the simplest ways to embed an image is by leveraging HTML content. This method is particularly effective when you need to generate structured documents, such as reports or marketing materials, where images are part of the layout. The following example demonstrates how to create a new PDF document and embed an image using IronPDF's ChromePdfRenderer.

using IronPdf;


var renderer = new ChromePdfRenderer();
var htmlContent = "<h2>Company Report</h2><img src='company-logo.png' width='200' />";
var pdf = renderer.RenderHtmlAsPdf(htmlContent);
pdf.SaveAs("Output.pdf");
Enter fullscreen mode Exit fullscreen mode

In this code, we instantiate the ChromePdfRenderer class to convert HTML content into a PDF. The HTML string includes a heading and an <img> tag that references company-logo.png. The RenderHtmlAsPdf method processes the HTML and generates a PDF, which is then saved as Output.pdf. This approach is ideal for embedding images within structured content such as company reports, invoices, or newsletters.

Add Image to PDF in C#

Adding an Image to an Existing PDF

Sometimes, you may need to add images to an existing PDF document, such as stamping a signature on a contract or adding a logo to a pre-designed report. IronPDF simplifies this task with its ImageStamper class. Here's how you can achieve this:

using IronPdf.Editing;
using IronPdf;


var pdf = PdfDocument.FromFile("testPDF.pdf");

ImageStamper imageStamper = new ImageStamper("image.jpg")
{
VerticalAlignment = VerticalAlignment.Top,
};
// Stamp the image stamper
pdf.ApplyStamp(imageStamper, 0);

pdf.SaveAs("updatedPDF.pdf");
Enter fullscreen mode Exit fullscreen mode

In this example, we load an existing PDF file using PdfDocument.FromFile. We create an ImageStamper object with the image file we want to add, setting its vertical alignment to the top. We then apply the ImageStamper to the first PDF page of the PDF using the ApplyStamp method. Finally, we save the updated pdf file as updatedPDF.pdf. This method is perfect for adding elements like signatures, stamps, or logos to existing PDFs.

Stamp Image to PDF

Overlaying an Image on All Pages

You might want to apply a consistent watermark or logo across all pages when dealing with multi-page documents. This can be accomplished by iterating through each page of the PDF and stamping the image accordingly. The following code example can do it:

using IronPdf.Editing;
using IronPdf;

var pdf = PdfDocument.FromFile("testPDF.pdf");

ImageStamper imageStamper = new ImageStamper("image.jpg")
{
    VerticalAlignment = VerticalAlignment.Top,
    HorizontalAlignment = HorizontalAlignment.Left,
};

pdf.ApplyStamp(imageStamper, new List<int> { 0,1,2,3});

pdf.SaveAs("updatedPDF.pdf");
Enter fullscreen mode Exit fullscreen mode

In this code, we load an existing PDF file using PdfDocument.FromFile. We create an ImageStamper object with image.jpg, setting its vertical alignment to the top and horizontal alignment to the left. The ApplyStamp method is used to stamp the image on pages 0, 1, 2, and 3 of the PDF. Finally, the modified document is saved as updatedPDF.pdf, which contains the image on the specified pages. This approach is perfect for adding consistent watermarks, signatures, or logos across multiple pages of a PDF document.

Advanced Features

Adjusting Image Transparency

For watermarking purposes, it’s often necessary to adjust the transparency of the image to ensure the underlying content remains readable. IronPDF allows you to control the opacity of the stamped image:

  var pdf = PdfDocument.FromFile("testPDF.pdf");

  ImageStamper imageStamper = new ImageStamper("image.jpg")
  {
      VerticalAlignment = VerticalAlignment.Top,
      HorizontalAlignment = HorizontalAlignment.Left,
      Opacity = 60,
      IsStampBehindContent = true,
  };

  pdf.ApplyStamp(imageStamper, new List<int> { 0,1,2,3});

  pdf.SaveAs("updatedPDF.pdf");
Enter fullscreen mode Exit fullscreen mode

Here, the Opacity parameter is set to 60, which means the image will be semi-transparent. Additionally, the IsStampBehindContent property is set to true, ensuring the image appears behind the main content. This feature is particularly useful for adding subtle watermarks without obstructing the document’s primary content. When adding a new page to your PDF, you can easily manipulate images in various image formats, ensuring they fit perfectly within your document.

Extract images

You might want to extract all embedded images from a PDF for reuse or analysis. This can be accomplished by loading the PDF, extracting all images, and saving them individually. The following code example demonstrates how to do this:

using IronPdf;


var pdf = PdfDocument.FromFile("testPDF.pdf");

  var images = pdf.ExtractAllImages();

  for (int i = 0; i < images.Count; i++)
  {
      var image = images[i];
      image.SaveAs(@$"images\image_{i}");
}
Enter fullscreen mode Exit fullscreen mode

This code demonstrates how to extract all images from a PDF file using IronPDF. It starts by loading the PDF document named "testPDF.pdf" with the PdfDocument.FromFile method. The ExtractAllImages function is then called on the PDF object to retrieve all embedded images, which are stored in a collection. A for loop iterates through each image in the collection, and the SaveAs method is used to save each image as a separate file in the "images" folder with filenames like "image_0", "image_1", and so on. This approach efficiently extracts and stores all images from the PDF for further use.

Conclusion:

In conclusion, IronPDF offers a powerful, easy-to-use solution for working with images in PDFs, whether you're adding, extracting, or overlaying images. Its robust feature set, including image transparency adjustments, cross-platform compatibility, and seamless integration with .NET, makes it an excellent choice for developers looking to automate PDF workflows. IronPDF provides the flexibility and performance you need, whether you're working with single-page documents or multi-page reports.

If you're satisfied with the capabilities demonstrated here, consider trying out the IronPDF free trial to explore all its features, or review the commercial license options for ongoing use in your projects.

Top comments (0)