How to Add Images to PDF Files in .NET with C#

Learn how to use .NET to add an image to a PDF by calling Add to PDF API Tool by pdfRest.
Share this page

Why Add Images to PDF with C#?

The pdfRest Add to PDF API Tool is a powerful resource for developers looking to automate the process of manipulating PDF files. This API allows you to programmatically add images to PDF documents, which can be useful for generating reports, creating personalized documents, or simply enhancing the visual aspect of your PDFs.

This tutorial will guide you through the steps of sending an API call to the Add to PDF endpoint using C#.

In the real world, you might use the Add to PDF feature to embed company logos, signatures, or product images into invoices, contracts, or brochures. For example, a real estate agency might use it to add photos of properties to their PDF brochures, or a legal firm might embed signed pages into contract PDFs. This functionality is essential for businesses looking to streamline their document workflows and maintain a high level of professionalism in their digital documents.

Add Images to PDF with C# Code Example

using System.Text;

using (var httpClient = new HttpClient { BaseAddress = new Uri("https://api.pdfrest.com") })
{
    using (var request = new HttpRequestMessage(HttpMethod.Post, "pdf-with-added-image"))
    {
        request.Headers.TryAddWithoutValidation("Api-Key", "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx");
        request.Headers.Accept.Add(new("application/json"));
        var multipartContent = new MultipartFormDataContent();

        var byteArray = File.ReadAllBytes("/path/to/file");
        var byteAryContent = new ByteArrayContent(byteArray);
        multipartContent.Add(byteAryContent, "file", "file_name");
        byteAryContent.Headers.TryAddWithoutValidation("Content-Type", "application/pdf");

        var byteArray2 = File.ReadAllBytes("/path/to/file");
        var byteAryContent2 = new ByteArrayContent(byteArray2);
        multipartContent.Add(byteAryContent2, "image_file", "file_name");
        byteAryContent2.Headers.TryAddWithoutValidation("Content-Type", "image/png");

        var byteArrayOption = new ByteArrayContent(Encoding.UTF8.GetBytes("1"));
        multipartContent.Add(byteArrayOption, "page");

        var byteArrayOption2 = new ByteArrayContent(Encoding.UTF8.GetBytes("0"));
        multipartContent.Add(byteArrayOption2, "x");
        var byteArrayOption3 = new ByteArrayContent(Encoding.UTF8.GetBytes("0"));
        multipartContent.Add(byteArrayOption3, "y");

        request.Content = multipartContent;
        var response = await httpClient.SendAsync(request);

        var apiResult = await response.Content.ReadAsStringAsync();

        Console.WriteLine("API response received.");
        Console.WriteLine(apiResult);
    }
}

Source: pdf-rest-api-samples on GitHub

Breaking Down the Code

The provided C# code demonstrates how to make a multipart/form-data POST request to the pdfRest API to add an image to a PDF file. Let's break down the key components:

using (var httpClient = new HttpClient { BaseAddress = new Uri("https://api.pdfrest.com") })

This initializes a new instance of the HttpClient class and sets the base address for the API calls to the pdfRest API.

request.Headers.TryAddWithoutValidation("Api-Key", "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx");

An API key is added to the request headers for authentication. Replace the placeholder with your actual pdfRest API key.

var multipartContent = new MultipartFormDataContent();

This creates a new instance of MultipartFormDataContent, which will hold the PDF and image files, as well as additional options.

multipartContent.Add(byteAryContent, "file", "file_name");
byteAryContent.Headers.TryAddWithoutValidation("Content-Type", "application/pdf");

The PDF file content is added to the multipart form data. The "file" key is used for the PDF, and the Content-Type is set to "application/pdf".

multipartContent.Add(byteAryContent2, "image_file", "file_name");
byteAryContent2.Headers.TryAddWithoutValidation("Content-Type", "image/png");

Similarly, the image file content is added with the key "image_file", and its Content-Type is set based on the image format (in this case, "image/png").

multipartContent.Add(byteArrayOption, "page");
multipartContent.Add(byteArrayOption2, "x");
multipartContent.Add(byteArrayOption3, "y");

Additional options are added to specify the page number and the x, y coordinates on the page where the image should be placed. These are encoded as byte arrays and added to the multipart content.

var response = await httpClient.SendAsync(request);

The request is sent asynchronously, and the response is awaited.

var apiResult = await response.Content.ReadAsStringAsync();

The content of the response is read as a string, which contains the result of the API call.

Beyond the Tutorial

This tutorial has demonstrated how to use C# to make an API call to the pdfRest Add to PDF endpoint to add an image to a PDF file. By following these steps, you can integrate this functionality into your own applications and automate the process of enhancing PDF documents with images.

To explore further and demo all of the pdfRest API Tools, visit the API Lab. For comprehensive documentation and additional details on the API endpoints, refer to the API Reference Guide.

Note: This is an example of a multipart API call. For code samples using JSON payloads, visit the pdf-rest-api-samples on GitHub.

Generate a self-service API Key now!
Create your FREE API Key to start processing PDFs in seconds, only possible with pdfRest.