How to Crop PDF in .NET with C#

Learn how to use pdfRest's Set Page Boxes API to crop PDF files by setting the CropBox with C#.
Share this page

Why Crop PDF Files with C#?

The pdfRest Set Page Boxes API Tool allows you to modify the page boxes of a PDF file, including the CropBox, which defines the visible content area. This tutorial will guide you through the process of sending an API call to set the CropBox using C# to crop PDF files.

Imagine you need to process a batch of PDF documents and remove the outer margins to focus on the main content. By using the Set Page Boxes API to programmatically adjust the CropBox, you can automate this PDF cropping task efficiently and consistently across all your files.

Crop PDF with C# Code Example

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

using (var httpClient = new HttpClient { BaseAddress = new Uri("https://api.pdfrest.com") })
{
    using (var request = new HttpRequestMessage(HttpMethod.Post, "pdf-with-page-boxes-set"))
    {
        request.Headers.TryAddWithoutValidation("Api-Key", "YOUR_API_KEY"); // Replace with your actual API key
        request.Headers.Accept.Add(new("application/json"));
        var multipartContent = new MultipartFormDataContent();

        var byteArray = File.ReadAllBytes("/path/to/your/file.pdf"); // Replace with the actual path to your PDF file
        var byteAryContent = new ByteArrayContent(byteArray);
        multipartContent.Add(byteAryContent, "file", "filename.pdf");
        byteAryContent.Headers.TryAddWithoutValidation("Content-Type", "application/pdf");

        // Define the CropBox settings to crop the first page
        var cropBoxOptions = new JObject
        {
            ["boxes"] = new JArray
            {
                new JObject
                {
                    ["box"] = "crop",
                    ["pages"] = new JArray
                    {
                        new JObject
                        {
                            ["range"] = "1",
                            ["left"] = 50,  // Adjust these values to your desired crop
                            ["top"] = 50,
                            ["bottom"] = 50,
                            ["right"] = 50
                        }
                    }
                }
            }
        };


        var byteArrayOption = new ByteArrayContent(Encoding.UTF8.GetBytes(cropBoxOptions.ToString(Formatting.None)));
        multipartContent.Add(byteArrayOption, "boxes");


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

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

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

Source: GitHub (Note: This example has been modified to focus on cropping)

Breaking Down the Code for Cropping

The code initializes an HttpClient to interact with the pdfRest API.

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

It then creates an HttpRequestMessage for a POST request to the pdf-with-page-boxes-set endpoint.

using (var request = new HttpRequestMessage(HttpMethod.Post, "pdf-with-page-boxes-set"))

Your API key is added to the request headers for authentication. Replace "YOUR_API_KEY" with your actual pdfRest API key.

request.Headers.TryAddWithoutValidation("Api-Key", "YOUR_API_KEY");

A MultipartFormDataContent is created to handle sending both the PDF file and the cropping instructions.

var multipartContent = new MultipartFormDataContent();

The PDF file is read as bytes and added to the multipart content. Ensure you replace "/path/to/your/file.pdf" with the correct path to your PDF file.

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

The cropBoxOptions JSON object is constructed to specifically crop the PDF. The "box" is set to "crop", and the "pages" array targets the first page ("range": "1"). The "left", "top", "bottom", and "right" values define the new visible boundaries of the page in points. Adjust these values to achieve your desired cropping.

var cropBoxOptions = new JObject
{
    ["boxes"] = new JArray
    {
        new JObject
        {
            ["box"] = "crop",
            ["pages"] = new JArray
            {
                new JObject
                {
                    ["range"] = "1",
                    ["left"] = 50,  // Adjust these values to your desired crop
                    ["top"] = 50,
                    ["bottom"] = 50,
                    ["right"] = 50
                }
            }
        }
    }
};

The cropBoxOptions are added to the multipart content as a byte array.

var byteArrayOption = new ByteArrayContent(Encoding.UTF8.GetBytes(cropBoxOptions.ToString(Formatting.None)));
multipartContent.Add(byteArrayOption, "boxes");

The API request is sent, and the response is read and printed to the console.

request.Content = multipartContent;
var response = await httpClient.SendAsync(request);
var apiResult = await response.Content.ReadAsStringAsync();
Console.WriteLine("API response received.");
Console.WriteLine(apiResult);

Further Exploration for PDF Cropping

This tutorial showed you how to use C# and the pdfRest Set Page Boxes API to crop PDF files by manipulating the CropBox. You can modify the cropBoxOptions to apply different cropping settings to various pages or page ranges within your PDF documents. Experiment with different margin values to achieve the precise visual outcome you need.

To discover more about the capabilities of the Set Page Boxes API and other pdfRest tools, explore the API Lab and consult the comprehensive API Reference Guide.

Note: This example uses a multipart API call. JSON payload examples for setting page boxes, including the CropBox, can be found here.

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