Cropping PDF Pages with C# (A Comprehensive Guide)

Alice Yang
10 min readApr 19, 2024

--

Cropping pages in PDF is an important technique that allows us to selectively adjust the visible area of the pages in PDF documents. By cropping pages, we can remove unnecessary content, resize the pages, or extract specific sections. This technique is crucial for various purposes. For example, when creating reports, we can crop pages to highlight key content and make it easier for readers to understand. When editing books or magazines, we can crop pages to adjust the page size to accommodate different reading devices and formatting requirements. In this article, we will explore how to crop pages in PDF using C#.

We will discuss the following topics:

C# Library to Crop PDF Pages

To crop pages in a PDF with C#, we can use the Spire.PDF for .NET library.

Spire.PDF for .NET is a feature-rich and user-friendly library that supports creating, reading, editing, converting, and printing PDF files within .NET (C#, VB.NET, ASP.NET) applications. With this library, you can perform a wide range of manipulations on PDFs, including adding, extracting and replacing text or images, adding digital signatures, adding or deleting pages, adding or extracting tables, merging or splitting PDFs, creating bookmarks, adding watermarks, inserting or extracting fillable forms and many more. In addition, you are also able to convert PDF files to various file formats, such as PDF to Word, PDF to Excel, PDF to images, PDF to HTML, PDF to SVG, PDF to XPS, PDF to OFD, PDF to PCL, and PDF to PostScript.

You can install Spire.PDF for .NET from NuGet by running the following command in the NuGet Package Manager Console:

PM> Install-Package Spire.PDF

If you already have Spire.PDF for .NET installed and would like to upgrade to the latest version, run the following command:

PM> Update-Package Spire.PDF

Crop a PDF Page with C#

Cropping a page in a PDF document using Spire.PDF for .NET is a straightforward process. Simply load the PDF document and get the desired page you want to crop. After that, create a Rectangle object to define the page area that needs to be cropped, and then assign it to the page’s CropBox property. Finally, save the modified document to preserve the changes made.

The code snippet below demonstrates how to crop a specific page in a PDF using C# and Spire.PDF for .NET:

using Spire.Pdf;
using System.Drawing;

namespace CropPdfPages
{
internal class Program
{
static void Main(string[] args)
{
// Create an instance of the PdfDocument class
PdfDocument pdf = new PdfDocument();

// Load an existing PDF document
pdf.LoadFromFile("test.pdf");

// Get a specific page from the loaded document based on its index (0-based)
PdfPageBase page = pdf.Pages[0];

// Define a rectangle to specify the area to be cropped
Rectangle rectangle = new Rectangle(30, 280, 552, 220);

// Crop the page by setting its CropBox property to the defined rectangle
page.CropBox = rectangle;

// Save the modified document to a new PDF file
pdf.SaveToFile("CropPage.pdf");

// Close the document
pdf.Close();
}
}
}

The image below shows the PDF page before and after cropping:

Crop PDF Pages in C#

Please note that you might need to adjust the values of the Rectangle object to specify the desired cropping area for your specific use case.

Crop All PDF Pages with C#

To crop all pages in a PDF using C#, you can iterate through all pages in the document and apply the cropping operation for each page.

The code snippet below demonstrates how to crop all pages in a PDF document using C# and Spire.PDF for .NET:

using Spire.Pdf;
using System.Drawing;

namespace CropPdfPages
{
internal class Program
{
static void Main(string[] args)
{
// Create an instance of the PdfDocument class
PdfDocument pdf = new PdfDocument();

// Load an existing PDF document
pdf.LoadFromFile("test.pdf");

// Iterate through all pages in the loaded document
for (int pageIndex = 0; pageIndex < pdf.Pages.Count; pageIndex++)
{
// Get the current page
PdfPageBase page = pdf.Pages[pageIndex];

// Define a rectangle to specify the area to be cropped
Rectangle rectangle = new Rectangle(30, 280, 552, 220);

// Crop the page by setting its CropBox property to the defined rectangle
page.CropBox = rectangle;
}

// Save the modified document to a new PDF file
pdf.SaveToFile("CropAllPages.pdf");

// Close the document
pdf.Close();
}
}
}

Crop a PDF Page and Save It as Image, HTML, Word or Excel with C#

After cropping a PDF page, you may want to save it in different formats such as an image, HTML file, Word or Excel document.

The code snippet below demonstrates how to crop a PDF page and save it as an image using C# and Spire.PDF for .NET:

using Spire.Pdf;
using Spire.Pdf.Graphics;
using System.Drawing;
using System.Drawing.Imaging;

namespace CropPdfPages
{
internal class Program
{
static void Main(string[] args)
{
// Create an instance of the PdfDocument class
PdfDocument pdf = new PdfDocument();

// Load an existing PDF document
pdf.LoadFromFile("test.pdf");

// Get the first page from the loaded document based on its index (0-based)
PdfPageBase page = pdf.Pages[0];

// Define a rectangle to specify the area to be cropped
Rectangle rectangle = new Rectangle(30, 280, 552, 220);

// Crop the page by setting its CropBox property to the defined rectangle
page.CropBox = rectangle;

// Save the first page to an Image object
Image image = pdf.SaveAsImage(0, PdfImageType.Bitmap);
// Save the Image object as a PNG file
image.Save("CropPageToImage.png", ImageFormat.Png);

// Close the document
pdf.Close();
}
}
}

The code snippet below shows how to crop a PDF page and save it as HTML, Word or Excel using C# and Spire.PDF for .NET:

using Spire.Pdf;
using Spire.Pdf.Conversion;
using Spire.Pdf.Graphics;
using System.Drawing;
using System.Drawing.Imaging;

namespace CropPdfPages
{
internal class Program
{
static void Main(string[] args)
{
// Create an instance of the PdfDocument class
PdfDocument pdf = new PdfDocument();

// Load an existing PDF document
pdf.LoadFromFile("test.pdf");

// Get a specific page from the loaded document based on its index (0-based)
PdfPageBase page = pdf.Pages[0];

// Define a rectangle to specify the area to be cropped
Rectangle rectangle = new Rectangle(30, 280, 552, 220);

// Crop the page by setting its CropBox property to the defined rectangle
page.CropBox = rectangle;

// Create a new PDF document
PdfDocument newPdf = new PdfDocument();
// Insert the cropped page into the new PDF document
newPdf.InsertPage(pdf, page);

//Save the new PDF document to an HTML, Word or Excel file
newPdf.SaveToFile("CropPageToHtml.html", FileFormat.HTML);
newPdf.SaveToFile("CropPageToWord.docx", FileFormat.DOCX);
newPdf.SaveToFile("CropPageToExcel.xlsx", FileFormat.XLSX);

// Close the documents
pdf.Close();
newPdf.Close();
}
}
}

In addition to image, HTML, Word, or Excel, you can adjust the code snippet to crop PDF pages and save them to many other formats such as XPS, PowerPoint, SVG, PDF/A, and PostScript.

Visually Select an Area and Apply Cropping on a PDF Page with C#

Sometimes, defining the appropriate cropping area by code alone can be challenging, because the content of PDF files may vary. By visually selecting a crop area, you can precisely define the portion of the PDF page you want to keep.

To achieve this task, you can use Spire.PDFViewer for .NET in conjunction with Spire.PDF for .NET. Spire.PDFViewer for .NET is a library mainly designed for viewing PDF files within .NET applications.

Here are the detailed steps:

Step 1. Install Spire.PDFViewer using the following command:

PM> Install-Package Spire.PDFViewer

Step 2: Add Spire.PdfViewer to the tool box.

Step 3. Drag the PdfDocumentViewer, buttons, textboxes and labels from the tool box to the form.

Add Tools
Add Tools

Step 4. Adding the code.

Here is the code of Form1.Designer.cs:

namespace CropPDF
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;

/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}

#region Windows Form Designer generated code

/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.LoadFile = new System.Windows.Forms.Button();
this.label2 = new System.Windows.Forms.Label();
this.textBox1 = new System.Windows.Forms.TextBox();
this.textBox2 = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.textBox3 = new System.Windows.Forms.TextBox();
this.pdfDocumentViewer1 = new Spire.PdfViewer.Forms.PdfDocumentViewer();
this.CreateSignature = new System.Windows.Forms.Button();
this.SuspendLayout();
//
// LoadFile
//
this.LoadFile.Location = new System.Drawing.Point(12, 30);
this.LoadFile.Name = "LoadFile";
this.LoadFile.Size = new System.Drawing.Size(124, 39);
this.LoadFile.TabIndex = 0;
this.LoadFile.Text = "Load File";
this.LoadFile.UseVisualStyleBackColor = true;
this.LoadFile.Click += new System.EventHandler(this.LoadFile_Click);
//
// textBox1
//
this.textBox1.Location = new System.Drawing.Point(14, 125);
this.textBox1.Multiline = true;
this.textBox1.Name = "textBox1";
this.textBox1.Size = new System.Drawing.Size(122, 38);
this.textBox1.TabIndex = 3;
//
// textBox2
//
this.textBox2.Location = new System.Drawing.Point(14, 218);
this.textBox2.Multiline = true;
this.textBox2.Name = "textBox2";
this.textBox2.Size = new System.Drawing.Size(122, 42);
this.textBox2.TabIndex = 7;
//
// textBox3
//
this.textBox3.Location = new System.Drawing.Point(16, 330);
this.textBox3.Multiline = true;
this.textBox3.Name = "textBox3";
this.textBox3.Size = new System.Drawing.Size(117, 40);
this.textBox3.TabIndex = 10;

//
// label1
//
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(12, 92);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(180, 13);
this.label1.TabIndex = 2;
this.label1.Text = "The Coordinates of the Start Position:";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(12, 183);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(166, 13);
this.label2.TabIndex = 8;
this.label2.Text = "The Coordinates of the End Position:";
//
// label3
//
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(14, 293);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(153, 13);
this.label3.TabIndex = 9;
this.label3.Text = "The Selected Rectangular size:";
//
// pdfDocumentViewer1
//
this.pdfDocumentViewer1.AutoScroll = true;
this.pdfDocumentViewer1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(229)))), ((int)(((byte)(229)))), ((int)(((byte)(229)))));
this.pdfDocumentViewer1.FormFillEnabled = false;
this.pdfDocumentViewer1.Location = new System.Drawing.Point(317, 30);
this.pdfDocumentViewer1.MultiPagesThreshold = 60;
this.pdfDocumentViewer1.Name = "pdfDocumentViewer1";
this.pdfDocumentViewer1.OnRenderPageExceptionEvent = null;
this.pdfDocumentViewer1.PageLayoutMode = Spire.PdfViewer.Forms.PageLayoutMode.SinglePageContinuous;
this.pdfDocumentViewer1.Size = new System.Drawing.Size(775, 707);
this.pdfDocumentViewer1.TabIndex = 11;
this.pdfDocumentViewer1.Text = "pdfDocumentViewer1";
this.pdfDocumentViewer1.Threshold = 60;
this.pdfDocumentViewer1.ViewerMode = Spire.PdfViewer.Forms.PdfViewerMode.PdfViewerMode.MultiPage;
this.pdfDocumentViewer1.ZoomFactor = 1F;
this.pdfDocumentViewer1.ZoomMode = Spire.PdfViewer.Forms.ZoomMode.Default;
this.pdfDocumentViewer1.MouseDown += new System.Windows.Forms.MouseEventHandler(this.PdfDocumentView_MouseDown);
this.pdfDocumentViewer1.MouseUp += new System.Windows.Forms.MouseEventHandler(this.PdfDocumentView_MouseUp);
//
// CreateSignature
//
this.CreateSignature.Location = new System.Drawing.Point(14, 391);
this.CreateSignature.Name = "CreateSignature";
this.CreateSignature.Size = new System.Drawing.Size(124, 37);
this.CreateSignature.TabIndex = 4;
this.CreateSignature.Text = "Crop Page";
this.CreateSignature.UseVisualStyleBackColor = true;
this.CreateSignature.Click += new System.EventHandler(this.Crop_Click);
//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1162, 939);
this.Controls.Add(this.pdfDocumentViewer1);
this.Controls.Add(this.textBox3);
this.Controls.Add(this.label3);
this.Controls.Add(this.label1);
this.Controls.Add(this.textBox2);
this.Controls.Add(this.CreateSignature);
this.Controls.Add(this.textBox1);
this.Controls.Add(this.label2);
this.Controls.Add(this.LoadFile);
this.Name = "Form1";
this.Text = "Form1";
this.ResumeLayout(false);
this.PerformLayout();

}

#endregion

private System.Windows.Forms.Button LoadFile;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.TextBox textBox1;
private System.Windows.Forms.TextBox textBox2;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.TextBox textBox3;
private Spire.PdfViewer.Forms.PdfDocumentViewer pdfDocumentViewer1;
private System.Windows.Forms.Button CreateSignature;
}
}

Here is the code of Form1.cs:

using Spire.Pdf;
using Spire.Pdf.Graphics;
using Spire.PdfViewer.Forms;
using System;
using System.Drawing;
using System.Windows.Forms;

namespace CropPDF
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private float currentX1 = 0;
private float currentY1 = 0;

private float currentX2 = 0;
private float currentY2 = 0;
int scrollValue = 0;
int currentPage = 1;
string pdfFile;

private void LoadFile_Click(object sender, EventArgs e)//Load file
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "PDF document (*.pdf)|*.pdf";
DialogResult result = dialog.ShowDialog();
if (result == DialogResult.OK)
{
try
{
pdfFile = dialog.FileName;
PdfDocument doc = new PdfDocument();
doc.LoadFromFile(pdfFile);

PdfPageBase page = doc.Pages[0];

pdfDocumentViewer1.EastAsianFont = true;
pdfDocumentViewer1.LoadFromFile(pdfFile);
pdfDocumentViewer1.PageLayoutMode = PageLayoutMode.SinglePageContinuous;
PdfUnitConvertor unitconvertor = new PdfUnitConvertor();
pdfDocumentViewer1.Height = (int)unitconvertor.ConvertToPixels(page.Size.Height, PdfGraphicsUnit.Point);
pdfDocumentViewer1.Width = (int)unitconvertor.ConvertToPixels(page.Size.Width, PdfGraphicsUnit.Point);

pdfDocumentViewer1.ZoomMode = ZoomMode.FitPage;
}
catch (Exception exe)
{
MessageBox.Show(exe.Message, "Crop PDF Page Demo", MessageBoxButtons.OK, MessageBoxIcon.Error);
}

}

}
private void PdfDocumentView_MouseUp(object sender, MouseEventArgs e)//mouse up
{
scrollValue = pdfDocumentViewer1.VerticalScroll.Value;
float zoomF = pdfDocumentViewer1.ZoomFactor;
PdfUnitConvertor unitconvertor = new PdfUnitConvertor();
PdfDocument pdf = new PdfDocument();
pdf.LoadFromFile(pdfFile);
PdfPageBase page;
int pageHeight = 0;
if (pdfDocumentViewer1.CurrentPageNumber < 1)
{
currentPage = 1;
}
else
{
currentPage = pdfDocumentViewer1.CurrentPageNumber;
if (currentPage > 1)
{
for (int i = currentPage; i > 1; i--)
{
page = pdf.Pages[i - 2];
pageHeight += (int)(unitconvertor.ConvertToPixels(page.Size.Height, PdfGraphicsUnit.Point) * zoomF) + 8;
}
}
else
{
page = pdf.Pages[0];
pageHeight = (int)(unitconvertor.ConvertToPixels(page.Size.Height, PdfGraphicsUnit.Point) * zoomF);
if (pdfDocumentViewer1.VerticalScroll.Value < pageHeight)
{
pageHeight = 0;
}
}
}

int x = e.X;
int y = e.Y + pdfDocumentViewer1.VerticalScroll.Value - 4 - pageHeight;
float newX = x / zoomF;
float newY = y / zoomF;
currentX2 = unitconvertor.ConvertFromPixels(newX, PdfGraphicsUnit.Point);
currentY2 = unitconvertor.ConvertFromPixels(newY, PdfGraphicsUnit.Point);

textBox2.Text = "X: " + currentX2.ToString() + " Y: " + currentY2.ToString();
}
private void PdfDocumentView_MouseDown(object sender, MouseEventArgs e)//mouse down
{
scrollValue = pdfDocumentViewer1.VerticalScroll.Value;
float zoomF = pdfDocumentViewer1.ZoomFactor;
PdfUnitConvertor unitconvertor = new PdfUnitConvertor();
PdfDocument pdf = new PdfDocument();
pdf.LoadFromFile(pdfFile);
PdfPageBase page;
int pageHeight = 0;
if (pdfDocumentViewer1.CurrentPageNumber < 1)
{
currentPage = 1;
}
else
{
currentPage = pdfDocumentViewer1.CurrentPageNumber;
if (currentPage > 1)
{
for (int i = currentPage; i > 1; i--)
{
page = pdf.Pages[i - 2];
pageHeight += (int)(unitconvertor.ConvertToPixels(page.Size.Height, PdfGraphicsUnit.Point) * zoomF) + 8;
}
}
else
{
page = pdf.Pages[0];
pageHeight = (int)(unitconvertor.ConvertToPixels(page.Size.Height, PdfGraphicsUnit.Point) * zoomF);
if (pdfDocumentViewer1.VerticalScroll.Value < pageHeight)
{
pageHeight = 0;
}
}
}

int x = e.X;
int y = e.Y + pdfDocumentViewer1.VerticalScroll.Value - 4 - pageHeight;
float newX = x / zoomF;
float newY = y / zoomF;
currentX1 = unitconvertor.ConvertFromPixels(newX, PdfGraphicsUnit.Point);
currentY1 = unitconvertor.ConvertFromPixels(newY, PdfGraphicsUnit.Point);
textBox1.Text = "X: " + currentX1.ToString() + " Y: " + currentY1.ToString();

}
private void Crop_Click(object sender, EventArgs e)
{
PdfDocument doc = new PdfDocument(pdfFile);

if (currentX2 > currentX1 && currentY2 > currentY1)
{
PointF point = new PointF(currentX1, currentY1);

float width = currentX2 - currentX1;
float height = currentY2 - currentY1;

textBox3.Text = "Width: " + width.ToString() + " Height: " + height.ToString();

SizeF size = new SizeF(width, height);

RectangleF rect = new RectangleF(point, size);

doc.Pages[pdfDocumentViewer1.CurrentPageNumber - 1].CropBox = rect;


doc.SaveToFile("CropPage.pdf");
//doc.SaveToFile("CropPageToSvg.svg", FileFormat.SVG);
//doc.SaveToFile("CropPageToHtml.html", FileFormat.HTML);

MessageBox.Show("The Page is croped successfully!");
//MessageBox.Show("SVG and HTML are generated successfully!");
System.Diagnostics.Process.Start("CropPage.pdf");
}

else
{
MessageBox.Show("The location you set do not conform to the requirements, please re-specify the location");
textBox1.Text = "";
textBox2.Text = "";
}
}
}
}

Step 5. Select the crop area by dragging your mouse, then click the crop button to apply cropping.

Visually Select an Area and Apply Cropping on a PDF Page with C#
Visually Select an Area and Apply Cropping on a PDF Page with C#

The full example can be downloaded from this link.

Conclusion

This article explains various scenarios for cropping PDF pages using C#. We hope you find it helpful.

Related Topics

--

--

Alice Yang

Skilled senior software developers with five years of experience in all phases of software development life cycle using .NET, Java and C++ languages.