How to Create a Blank PDF in .NET with C#

Learn how to use the pdfRest Create Blank PDF API to generate an empty PDF that can be filled with content using C#.
Share this page

Why Create Blank PDF with C#?

The pdfRest Create Blank PDF API Tool is a powerful resource for developers looking to automate the creation of blank PDF documents. This tutorial will guide you through the process of sending an API call to the Create Blank PDF endpoint using C#. By leveraging this tool, you can generate blank PDFs with customizable attributes such as page size, count, and orientation, directly from your C# applications.

Imagine you're developing a document management system that requires generating placeholders for future content. By using the Create Blank PDF API, you can efficiently create these placeholder PDFs programmatically, saving time and reducing manual effort. This can be particularly useful in scenarios where documents need to be dynamically generated and stored for later use.

Create Blank PDF with C# Code Example

/*
 * What this sample does:
 * - Calls /blank-pdf via multipart/form-data to create a three-page blank PDF.
 * - Routed from Program.cs as: `dotnet run -- blank-pdf-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
 *
 * Usage:
 *   dotnet run -- blank-pdf-multipart
 *
 * Output:
 * - Prints the JSON response. Validation errors (args/env) exit non-zero.
 */

namespace Samples.EndpointExamples.MultipartPayload
{
    public static class BlankPdf
    {
        public static async Task Execute(string[] args)
        {
            var apiKey = Environment.GetEnvironmentVariable("PDFREST_API_KEY");
            if (string.IsNullOrWhiteSpace(apiKey))
            {
                Console.Error.WriteLine("Missing required environment variable: PDFREST_API_KEY");
                Environment.Exit(1);
                return;
            }

            var baseUrl = Environment.GetEnvironmentVariable("PDFREST_URL") ?? "https://api.pdfrest.com";

            using (var httpClient = new HttpClient { BaseAddress = new Uri(baseUrl) })
            using (var request = new HttpRequestMessage(HttpMethod.Post, "blank-pdf"))
            {
                request.Headers.TryAddWithoutValidation("Api-Key", apiKey);
                request.Headers.Accept.Add(new("application/json"));

                var multipartContent = new MultipartFormDataContent
                {
                    { new StringContent("letter"), "page_size" },
                    { new StringContent("3"), "page_count" },
                    { new StringContent("portrait"), "page_orientation" }
                };

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

                Console.WriteLine("blank-pdf response received.");
                Console.WriteLine(apiResult);

                if (!response.IsSuccessStatusCode)
                {
                    Environment.ExitCode = 1;
                }
            }
        }
    }
}

Source: GitHub Repository

Breaking Down the Code

The code begins by retrieving the API key from the environment variables:

var apiKey = Environment.GetEnvironmentVariable("PDFREST_API_KEY");

This key is essential for authenticating the request. If the key is missing, the program exits with an error message.

The base URL for the API is determined next, with an option to override it for GDPR compliance:

var baseUrl = Environment.GetEnvironmentVariable("PDFREST_URL") ?? "https://api.pdfrest.com";

An HTTP client is then configured to send a POST request to the "blank-pdf" endpoint:

using (var httpClient = new HttpClient { BaseAddress = new Uri(baseUrl) })
using (var request = new HttpRequestMessage(HttpMethod.Post, "blank-pdf"))

The request headers include the API key and specify that the response should be in JSON format:

request.Headers.TryAddWithoutValidation("Api-Key", apiKey);
request.Headers.Accept.Add(new("application/json"));

The request content is prepared using MultipartFormDataContent, setting parameters for page size, count, and orientation:

var multipartContent = new MultipartFormDataContent
{
    { new StringContent("letter"), "page_size" },
    { new StringContent("3"), "page_count" },
    { new StringContent("portrait"), "page_orientation" }
};

Finally, the request is sent, and the response is read and printed:

var response = await httpClient.SendAsync(request);
var apiResult = await response.Content.ReadAsStringAsync();
Console.WriteLine("blank-pdf response received.");
Console.WriteLine(apiResult);

Beyond the Tutorial

In this tutorial, you learned how to create a blank PDF using the pdfRest API with C#. This example demonstrated a multipart API call, setting parameters for the PDF's attributes. To further explore the capabilities of pdfRest, try out all the available API tools in the API Lab.

For detailed information on the API's capabilities, refer to the API Reference Guide. Additionally, for examples using JSON payloads, visit the GitHub Repository.

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