How to Add Vector Lines and Rectangles to PDF Files in .NET with C#

Learn how to use pdfRest Add to PDF API Tool with C# to add vector shapes to PDF documents.
Share this page

Why Add Vector Lines and Rectangles to PDF Files with C#?

The pdfRest Add to PDF API Tool is a powerful resource for developers who need to manipulate PDF documents programmatically. By using this tool, you can add shapes such as rectangles and lines to existing PDF files, which can be useful for highlighting areas, adding annotations, or creating custom layouts. This tutorial will guide you through the process of sending an API call to Add to PDF using C#.

Consider a real-world scenario where a company needs to create a review panel on a PDF document for internal audits. By using the Add to PDF API, they can programmatically add shapes like rectangles for background and lines for dividers, ensuring consistency and saving time compared to manual editing. This automation can be especially beneficial when dealing with large volumes of documents.

Add Vector Lines and Rectangles to PDF Files with C# Code Example

/*
 * What this sample does:
 * - Adds a review-panel background and divider line to a PDF via multipart/form-data.
 * - Routed from Program.cs as: `dotnet run -- pdf-with-added-shapes-multipart `.
 *
 * Setup (environment):
 * - Copy .env.example to .env
 * - Set PDFREST_API_KEY=your_api_key_here
 * - Optional: set PDFREST_URL to override the API region. For EU/GDPR compliance and proximity, use:
 *     PDFREST_URL=https://eu-api.pdfrest.com
 *   For more information visit https://pdfrest.com/pricing#how-do-eu-gdpr-api-calls-work
 */

using Newtonsoft.Json.Linq;
using System.Text;
using Samples;

namespace Samples.EndpointExamples.MultipartPayload;

public static class PdfWithAddedShapes
{
    public static async Task Execute(string[] args)
    {
        var inputPath = SampleInput.RequireFile(args, "pdf-with-added-shapes-multipart");
        var apiKey = SampleInput.RequireApiKey();
        var shapes = JArray.Parse("""
            [
              {"type":"rectangle","page":1,"x":54,"y":540,"width":504,"height":108,"fill_color_rgb":"245,247,250","stroke_color_rgb":"26,72,112","stroke_width":1,"tag_is_artifact":true},
              {"type":"line","page":1,"x1":72,"y1":576,"x2":540,"y2":576,"stroke_color_rgb":"26,72,112","stroke_width":1.5,"tag_actual_text":"Review section divider","tag_structure_type":"Figure"}
            ]
            """);

        using var client = SampleInput.CreateClient();
        using var request = new HttpRequestMessage(HttpMethod.Post, "pdf-with-added-shapes");
        request.Headers.TryAddWithoutValidation("Api-Key", apiKey);
        request.Headers.Accept.Add(new("application/json"));
        using var content = new MultipartFormDataContent();
        content.Add(new ByteArrayContent(await File.ReadAllBytesAsync(inputPath)), "file", Path.GetFileName(inputPath));
        content.Add(new StringContent(shapes.ToString(), Encoding.UTF8), "shape_objects");
        content.Add(new StringContent("true"), "tag_enabled");
        content.Add(new StringContent("review-panel"), "output");
        request.Content = content;

        await SampleInput.PrintResponse(client, request);
    }
}

Source: GitHub

Breaking Down the Code

The code begins by setting up the environment and requiring necessary inputs such as the input file path and API key:

var inputPath = SampleInput.RequireFile(args, "pdf-with-added-shapes-multipart");
var apiKey = SampleInput.RequireApiKey();

Next, a JSON array defines the shapes to be added, specifying attributes like type, page, coordinates, colors, and more:

var shapes = JArray.Parse("""
    [
      {"type":"rectangle","page":1,"x":54,"y":540,"width":504,"height":108,"fill_color_rgb":"245,247,250","stroke_color_rgb":"26,72,112","stroke_width":1,"tag_is_artifact":true},
      {"type":"line","page":1,"x1":72,"y1":576,"x2":540,"y2":576,"stroke_color_rgb":"26,72,112","stroke_width":1.5,"tag_actual_text":"Review section divider","tag_structure_type":"Figure"}
    ]
    """);

The HttpClient and HttpRequestMessage are initialized for making the API call. The API key is added to the request header:

using var client = SampleInput.CreateClient();
using var request = new HttpRequestMessage(HttpMethod.Post, "pdf-with-added-shapes");
request.Headers.TryAddWithoutValidation("Api-Key", apiKey);
request.Headers.Accept.Add(new("application/json"));

The content of the request is created using MultipartFormDataContent, which includes the PDF file and shape objects:

using var content = new MultipartFormDataContent();
content.Add(new ByteArrayContent(await File.ReadAllBytesAsync(inputPath)), "file", Path.GetFileName(inputPath));
content.Add(new StringContent(shapes.ToString(), Encoding.UTF8), "shape_objects");
content.Add(new StringContent("true"), "tag_enabled");
content.Add(new StringContent("review-panel"), "output");
request.Content = content;

Finally, the response from the API call is printed:

await SampleInput.PrintResponse(client, request);

Beyond the Tutorial

In this tutorial, you learned how to use C# to make an API call to pdfRest's Add to PDF tool, adding shapes to a PDF document. This example demonstrates how to enhance PDF documents programmatically, which can be useful for various applications like creating templates or adding annotations.

I encourage you to explore all the pdfRest API Tools available in the API Lab. For more detailed information, refer to the API Reference Guide. Note that this is an example of a multipart API call, and code samples using JSON payloads can be found at GitHub.

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