How to Resize PDF Pages with C# in .NET

Learn how to use pdfRest Set Page Boxes API to resize PDF pages with C#.
Share this page

Why Resize PDF Pages with C#?

The pdfRest Set Page Boxes API Tool allows you to modify the page boxes of a PDF document, specifically the MediaBox, to control the physical dimensions of the pages. This tutorial will guide you through the process of sending an API call to the Set Page Boxes API Tool endpoint using C# in a .NET environment to resize all pages of a PDF document.

Imagine you have a PDF document where all pages need to conform to a specific standard dimension for consistent display or processing. By using the Set Page Boxes API Tool and the "all" range, you can efficiently resize all PDF pages to meet your requirements in a single API call.

Resize PDF Pages with C# Code Example

using System;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.Json;
using System.Threading.Tasks;

public class ResizePdfPages
{
    public static async Task Main(string[] args)
    {
        string apiKey = "YOUR_API_KEY"; // Replace with your actual API key
        string pdfFilePath = "/path/to/your/file.pdf"; // Replace with the actual path to your PDF file
        string outputName = "resized_all_to_a4_out.pdf";
        string pdfWithPageBoxesEndpointUrl = "https://api.pdfrest.com/pdf-with-page-boxes-set";

        // Define the MediaBox adjustments to resize all pages from Letter to A4
        // Letter: 612 x 792 points
        // A4:    595 x 842 points
        double deltaWidthInward = (612 - 595) / 2;   // Positive margin to shrink width inward
        double deltaHeightOutward = (792 - 842) / 2;  // Negative margin to expand height outward

        var resizeBoxOptions = new
        {
            boxes = new[]
            {
                new
                {
                    box = "media",
                    pages = new[]
                    {
                        new
                        {
                            range = "all",
                            left = deltaWidthInward,
                            top = deltaHeightOutward,
                            bottom = deltaHeightOutward,
                            right = deltaWidthInward
                        }
                    }
                }
            }
        };

        using (var httpClient = new HttpClient())
        using (var formData = new MultipartFormDataContent())
        using (var fileStream = File.OpenRead(pdfFilePath))
        {
            httpClient.DefaultRequestHeaders.Add("Api-Key", apiKey);

            formData.Add(new StreamContent(fileStream), "file", Path.GetFileName(pdfFilePath));
            formData.Add(new StringContent(JsonSerializer.Serialize(resizeBoxOptions)), "boxes");
            formData.Add(new StringContent(Path.GetFileNameWithoutExtension(outputName)), "output");

            Console.WriteLine("Sending POST request to pdf-with-page-boxes-set endpoint to resize all PDF pages to A4...");
            var response = await httpClient.PostAsync(pdfWithPageBoxesEndpointUrl, formData);

            Console.WriteLine($"Response status code: {(int)response.StatusCode}");

            if (response.IsSuccessStatusCode)
            {
                var responseContent = await response.Content.ReadAsStringAsync();
                Console.WriteLine($"Response data: {responseContent}");
            }
            else
            {
                var errorContent = await response.Content.ReadAsStringAsync();
                Console.WriteLine($"Error: {errorContent}");
            }
        }
    }
}

Source: GitHub (Note: This example has been modified to focus on resizing all pages)

Breaking Down the Code for Resizing All Pages

The code starts by importing the necessary namespaces for file operations, HTTP requests, and JSON serialization.

using System;
using System.IO;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text.Json;
using System.Threading.Tasks;

This section defines the API key, input PDF file path, desired output file name, and the API endpoint URL. Remember to replace "YOUR_API_KEY" with your actual pdfRest API key and "/path/to/your/file.pdf" with the correct path to your PDF file.

string apiKey = "YOUR_API_KEY";
string pdfFilePath = "/path/to/your/file.pdf";
string outputName = "resized_all_to_a4_out.pdf";
string pdfWithPageBoxesEndpointUrl = "https://api.pdfrest.com/pdf-with-page-boxes-set";

This section sets the API endpoint URL.

// Define the MediaBox adjustments to resize all pages from Letter to A4
// Letter: 612 x 792 points
// A4:    595 x 842 points
double deltaWidthInward = (612 - 595) / 2;   // Positive margin to shrink width inward
double deltaHeightOutward = (792 - 842) / 2;  // Negative margin to expand height outward

var resizeBoxOptions = new
{
    boxes = new[]
    {
        new
        {
            box = "media",
            pages = new[]
            {
                new
                {
                    range = "all",
                    left = deltaWidthInward,
                    top = deltaHeightOutward,
                    bottom = deltaHeightOutward,
                    right = deltaWidthInward
                }
            }
        }
    }
};

The resizeBoxOptions object is configured to resize all PDF pages by adjusting the MediaBox. The box property is set to "media". Setting range to "all" ensures these MediaBox adjustments are applied to every page. Positive deltaWidthInward values shrink the width, and positive deltaHeightOutward values expand the height relative to the top and bottom.

using (var httpClient = new HttpClient())
using (var formData = new MultipartFormDataContent())
using (var fileStream = File.OpenRead(pdfFilePath))
{
    httpClient.DefaultRequestHeaders.Add("Api-Key", apiKey);

    formData.Add(new StreamContent(fileStream), "file", Path.GetFileName(pdfFilePath));
    formData.Add(new StringContent(JsonSerializer.Serialize(resizeBoxOptions)), "boxes");
    formData.Add(new StringContent(Path.GetFileNameWithoutExtension(outputName)), "output");

    Console.WriteLine("Sending POST request to pdf-with-page-boxes-set endpoint to resize all PDF pages to A4...");
    var response = await httpClient.PostAsync(pdfWithPageBoxesEndpointUrl, formData);

    Console.WriteLine($"Response status code: {(int)response.StatusCode}");

    if (response.IsSuccessStatusCode)
    {
        var responseContent = await response.Content.ReadAsStringAsync();
        Console.WriteLine($"Response data: {responseContent}");
    }
    else
    {
        var errorContent = await response.Content.ReadAsStringAsync();
        Console.WriteLine($"Error: {errorContent}");
    }
}

This section creates an HttpClient and a MultipartFormDataContent object to send the PDF file and the JSON-serialized resizeBoxOptions. It sets the Api-Key in the request headers and adds the file and other parameters to the form data. Finally, it sends a POST request to the pdfRest API endpoint to resize all PDF pages and handles the response.

Next Steps for Resizing All PDF Pages

This tutorial demonstrated how to use C# (.NET) and the pdfRest Set Page Boxes API Tool to resize all pages of a PDF from US Letter to A4 by setting the MediaBox with the range = "all" option. You can adapt the deltaWidthInward and deltaHeightOutward calculations to resize to other dimensions. This approach efficiently applies the same resizing to every page in your document.

To learn more about the Set Page Boxes API Tool and its capabilities, including setting other page boxes and using different page ranges, you can demo all of the pdfRest API Tools in the API Lab and refer to the API Reference Guide for detailed documentation.

Note: This example uses a multipart API call. JSON payload examples for setting page boxes, including the MediaBox, 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.