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

Learn how to use C# and the pdfRest Add to PDF API Tool to create structured tables in PDF documents from .NET applications.
Share this page

Why Add Tables to PDF with C#?

The pdfRest Add to PDF API Tool is a powerful feature that allows developers to programmatically add tables to PDF documents. This tutorial will guide you through the process of sending an API call to the Add to PDF endpoint using C#. By integrating this tool into your C# applications, you can automate the process of enhancing PDF documents with structured data, such as tables, without manually editing the files.

Businesses often need to generate reports or documents that include tables with data such as project statuses, financial summaries, or inventory lists. Using the Add to PDF API, a company can automatically generate these documents from their applications, ensuring consistency and saving time on manual document creation. This can be particularly useful for project management tools that need to provide stakeholders with up-to-date status reports.

Add Tables to PDF with C# Code Example

/*
 * What this sample does:
 * - Adds a tagged project-status table with styled headers, status cells, and a footer.
 * - Routed from Program.cs as: `dotnet run -- pdf-with-added-tables-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 PdfWithAddedTables
{
    public static async Task Execute(string[] args)
    {
        var inputPath = SampleInput.RequireFile(args, "pdf-with-added-tables-multipart");
        var apiKey = SampleInput.RequireApiKey();
        using var client = SampleInput.CreateClient();
        using var request = new HttpRequestMessage(HttpMethod.Post, "pdf-with-added-tables");
        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(CreateTable().ToString(), Encoding.UTF8), "table_objects");
        content.Add(new StringContent("true"), "tag_enabled");
        content.Add(new StringContent("en-US"), "tag_language");
        content.Add(new StringContent("project-status"), "output");
        request.Content = content;

        await SampleInput.PrintResponse(client, request);
    }

    internal static JArray CreateTable() => JArray.Parse("""
        [{
          "page":1,"x":54,"y":540,"width":504,
          "columns":[{"width":210},{"width":144},{"width":150}],
          "tag_structure_type":"Table",
          "style":{"padding":{"top":6,"right":8,"bottom":6,"left":8},"text_size":10},
          "header_rows":[{"cells":[
            {"text":"Milestone","tag_structure_type":"TH","style":{"background_color_rgb":[26,72,112],"text_color_rgb":[255,255,255]}},
            {"text":"Owner","tag_structure_type":"TH","style":{"background_color_rgb":[26,72,112],"text_color_rgb":[255,255,255]}},
            {"text":"Status","tag_structure_type":"TH","style":{"background_color_rgb":[26,72,112],"text_color_rgb":[255,255,255]}}
          ]}],
          "rows":[
            {"cells":[{"text":"Requirements review"},{"text":"Maya Chen"},{"text":"Complete","tag_structure_type":"TD","style":{"background_color_rgb":[220,252,231]}}]},
            {"cells":[{"text":"Prototype delivery"},{"text":"Jordan Lee"},{"text":"In progress","tag_structure_type":"TD","style":{"background_color_rgb":[254,249,195]}}]},
            {"cells":[{"text":"Stakeholder approval"},{"text":"Avery Patel"},{"text":"Planned","tag_structure_type":"TD","style":{"background_color_rgb":[239,246,255]}}]}
          ],
          "footer_rows":[{"cells":[{"text":"Next review: Friday, 10:00 AM","col_span":3,"tag_structure_type":"TD","style":{"background_color_rgb":[245,247,250],"text_color_rgb":[55,65,81]}}]}]
        }]
        """);
}

Source: GitHub

Breaking Down the Code

The code begins by setting up the environment and ensuring the necessary API key is available. The `Execute` method is the main function that processes the API call.

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

These lines retrieve the input file path and the API key, which are essential for the API call.

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

A new HTTP client and request are created. The request is configured to POST to the "pdf-with-added-tables" endpoint, and the API key is added to the headers for authentication.

using var content = new MultipartFormDataContent();
content.Add(new ByteArrayContent(await File.ReadAllBytesAsync(inputPath)), "file", Path.GetFileName(inputPath));
content.Add(new StringContent(CreateTable().ToString(), Encoding.UTF8), "table_objects");
content.Add(new StringContent("true"), "tag_enabled");
content.Add(new StringContent("en-US"), "tag_language");
content.Add(new StringContent("project-status"), "output");
request.Content = content;

The request content is set up as a multipart form. It includes the PDF file, table objects, and additional parameters such as `tag_enabled`, `tag_language`, and `output` to specify the document's characteristics.

internal static JArray CreateTable() => JArray.Parse("""
    [{
      "page":1,"x":54,"y":540,"width":504,
      "columns":[{"width":210},{"width":144},{"width":150}],
      "tag_structure_type":"Table",
      "style":{"padding":{"top":6,"right":8,"bottom":6,"left":8},"text_size":10},
      "header_rows":[{"cells":[
        {"text":"Milestone","tag_structure_type":"TH","style":{"background_color_rgb":[26,72,112],"text_color_rgb":[255,255,255]}},
        {"text":"Owner","tag_structure_type":"TH","style":{"background_color_rgb":[26,72,112],"text_color_rgb":[255,255,255]}},
        {"text":"Status","tag_structure_type":"TH","style":{"background_color_rgb":[26,72,112],"text_color_rgb":[255,255,255]}}
      ]}],
      "rows":[
        {"cells":[{"text":"Requirements review"},{"text":"Maya Chen"},{"text":"Complete","tag_structure_type":"TD","style":{"background_color_rgb":[220,252,231]}}]},
        {"cells":[{"text":"Prototype delivery"},{"text":"Jordan Lee"},{"text":"In progress","tag_structure_type":"TD","style":{"background_color_rgb":[254,249,195]}}]},
        {"cells":[{"text":"Stakeholder approval"},{"text":"Avery Patel"},{"text":"Planned","tag_structure_type":"TD","style":{"background_color_rgb":[239,246,255]}}]}
      ],
      "footer_rows":[{"cells":[{"text":"Next review: Friday, 10:00 AM","col_span":3,"tag_structure_type":"TD","style":{"background_color_rgb":[245,247,250],"text_color_rgb":[55,65,81]}}]}]
    }]
    """);

The `CreateTable` method constructs the JSON array that defines the table to be added to the PDF. It specifies the table's position, dimensions, and style, as well as the content of the header, body, and footer rows.

Beyond the Tutorial

In this tutorial, you learned how to use C# to make an API call to pdfRest's Add to PDF endpoint, adding a structured table to a PDF document. This example illustrates the use of multipart form data to send complex payloads, such as files and JSON objects, to an API.

To explore more capabilities of the pdfRest API, you can demo all the tools available in the API Lab. For further details on API endpoints, refer to the API Reference Guide.

Note: This is an example of a multipart API call. 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.