How to Crop PDF File in C#

Cropping and trimming PDF pages is always a challenging task for developers in C#. Drawing a crop box around your desired area in a PDF document and then saving only that portion is not straightforward. Fortunately, a solution exists in the IronPDF Library for .NET in C#.

The IronPDF .NET Library

IronPDF is a C# .NET library that allows developers to create, edit, and manipulate PDF files. It is very popular among C# developers because of its PDF generation capability, which allows them to work with PDF files without Adobe Acrobat installed. IronPDF for .NET also allows conversion between different formats like HTML to PDF, URL to PDF, and image to PDF.

It also supports adding custom headers and footers, digital signatures, annotations and attachments, user and owner passwords, and other security options. IronPDF has a fast Chromium Engine for a superior rendering experience. It also provides full multithreading and async support.

Prerequisites

Before beginning, Visual Studio 2022 (the latest version) needs to be downloaded and installed. Visual Studio is necessary for building C# apps. The installation will setup the .NET environment, after which we will be ready to make a PDF to JPG converter. You can download Visual Studio at this link.

IronPDF Installation

There are multiple ways to install IronPDF:

  1. You can download IronPDF from the NuGet Package Manager solution in your C# project, which is created using Visual Studio. Access the NuGet Package Manager via Tools or by right-clicking on Solution Explorer. Browse for the IronPDF package and install it.
  2. Another way to install IronPDF is by directly downloading it from the NuGet website. You can download it from here.

Crop PDF File using IronPDF in C#

The following step-by-step process will help you crop a PDF page. It is not straightforward, but we can make use of some methods to achieve this task. Let's get started!

Step 1: Load PDF Document

To load a PDF file from a local location into our project, IronPDF provides a FromFile method present in the PdfDocument class. The following code example demonstrates how to open an existing PDF file:

PdfDocument pdf = PdfDocument.FromFile("Input.pdf");
PdfDocument pdf = PdfDocument.FromFile("Input.pdf");
Dim pdf As PdfDocument = PdfDocument.FromFile("Input.pdf")
VB   C#

The loaded document is as follows:

How to Crop PDF File in C#: Figure 2

Step 2: Load a Specific Page from a PDF Document

Now that the file is opened for editing, we will create a separate PdfDocument object and store the specific page that we want to crop using the CopyPage method. Simply pass the index of the page that needs to be cropped. Here, we are going to crop the first page of the PDF document.

PdfDocument LoadedPage = pdfDocument.CopyPage(0);
PdfDocument LoadedPage = pdfDocument.CopyPage(0);
Dim LoadedPage As PdfDocument = pdfDocument.CopyPage(0)
VB   C#

Step 3: Convert the Loaded PDF Page to an Image

The RasterizeToImageFiles method provides the facility to save the PDF page to a high-resolution image file. The following code helps to convert our selected page to an image for cropping.

LoadedPage.RasterizeToImageFiles(@"C:\Image\Page_to_be_Cropped.png");
LoadedPage.RasterizeToImageFiles(@"C:\Image\Page_to_be_Cropped.png");
LoadedPage.RasterizeToImageFiles("C:\Image\Page_to_be_Cropped.png")
VB   C#

Now the page will be converted to an image file. The output is a high-quality PNG image.

How to Crop PDF File in C#: Figure 3

Now, the specific page is separate from the original document and ready to be cropped.

Step 4: Retrieve the Dimensions of the Loaded Page

To crop the PDF, we need to create a crop box with a certain width and height. For this purpose, we will create a new document using the ChromePdfRenderer class. It provides the option to customize the PDF page size according to our needs, and data is split evenly across pages.

Before creating a ChromePdfRenderer, first we will get the dimensions of our loaded page in step 2. We will use these dimensions while setting the custom page size for creating a crop box. The following code sample will help you to get the width and height of the page:

PdfPagesCollection pages = LoadedPage.Pages;
PdfPage pdfPage = pages[0];
// Dimensions retrieved in mm
float width = pdfPage.Width;
float height = pdfPage.Height;
PdfPagesCollection pages = LoadedPage.Pages;
PdfPage pdfPage = pages[0];
// Dimensions retrieved in mm
float width = pdfPage.Width;
float height = pdfPage.Height;
Dim pages As PdfPagesCollection = LoadedPage.Pages
Dim pdfPage As PdfPage = pages(0)
' Dimensions retrieved in mm
Dim width As Single = pdfPage.Width
Dim height As Single = pdfPage.Height
VB   C#

Firstly, we retrieved the total number of pages in the loaded PDF file using PdfPagesCollection. Then, we passed that page to a PdfPage instance to get the page dimension values from the Width and Height properties of the page. All done! Now let's move to the next step to create a custom crop box.

Step 5: Set the Custom PDF Page Size

The following code will help create a custom PDF paper size that will work as a crop box, to crop the content in different page segments.

ChromePdfRenderer pdfRenderer = new ChromePdfRenderer();
pdfRenderer.RenderingOptions.PaperSize = IronPdf.Rendering.PdfPaperSize.Custom;
pdfRenderer.RenderingOptions.SetCustomPaperSizeinMilimeters(width, height/4);

pdfRenderer.RenderingOptions.ForcePaperSize = true;
ChromePdfRenderer pdfRenderer = new ChromePdfRenderer();
pdfRenderer.RenderingOptions.PaperSize = IronPdf.Rendering.PdfPaperSize.Custom;
pdfRenderer.RenderingOptions.SetCustomPaperSizeinMilimeters(width, height/4);

pdfRenderer.RenderingOptions.ForcePaperSize = true;
Dim pdfRenderer As New ChromePdfRenderer()
pdfRenderer.RenderingOptions.PaperSize = IronPdf.Rendering.PdfPaperSize.Custom
'INSTANT VB WARNING: Instant VB cannot determine whether both operands of this division are integer types - if they are then you should use the VB integer division operator:
pdfRenderer.RenderingOptions.SetCustomPaperSizeinMilimeters(width, height/4)

pdfRenderer.RenderingOptions.ForcePaperSize = True
VB   C#

In the above code, first I created a ChromePdfRenderer, which is used to create a new PDF document. Then, I used rendering options to set the PdfPaperSize property value to Custom. Lastly, I set the custom page margins in millimeters using the dimensions retrieved in step 4.

We set the width to the original page width and decreased the height by 1/4th of the original page length. This makes the page work as a rectangle-shaped media box for the content.

Note: You can use ForcePaperSize = true to make sure the custom size is applied. For setting custom margins, please visit this code example.

Step 6: Create a New Document using HTML

Now in this final step, we are going to create a new document using the custom page size PDF and the image which we saved from the loaded page.

var croppedPdf = pdfRenderer.RenderHtmlAsPdf("< src='Page_to_be_Cropped.png'/>", @"C:\Image\");
var croppedPdf = pdfRenderer.RenderHtmlAsPdf("< src='Page_to_be_Cropped.png'/>", @"C:\Image\");
Dim croppedPdf = pdfRenderer.RenderHtmlAsPdf("< src='Page_to_be_Cropped.png'/>", "C:\Image\")
VB   C#

Now let's save the document using the SaveAs method.

croppedPdf.SaveAs("Cropped.pdf");
croppedPdf.SaveAs("Cropped.pdf");
croppedPdf.SaveAs("Cropped.pdf")
VB   C#

Output

How to Crop PDF File in C#: Figure 4

From the output, you can see that a single image is now split into five pages with the custom trim box created. You can copy a specific page you need using the following code:

croppedPdf.CopyPage(1).SaveAs("Cropped.pdf");
croppedPdf.CopyPage(1).SaveAs("Cropped.pdf");
croppedPdf.CopyPage(1).SaveAs("Cropped.pdf")
VB   C#

Conclusion

In this article, we learnt how to crop PDF documents by creating a virtual rectangle crop box in terms of pages using IronPDF for .NET Framework. The RasterizeToImageFiles method helps to convert the page into image which is then used to create a pixel perfect PDF document.

IronPDF also provides other PDF tools that can rotate PDF pages, change PDF text, set margins, format PDFs, convert them, and more. To learn more about IronPDF for .NET and to access additional features to manipulate PDF files, please refer to the following link. For more information on how to set a custom PDF page size, visit this link.

IronPDF .NET Library is free for development but needs to be licensed for commercial use. Download the powerful IronPDF library for .NET from this link and give it a try!