Introduction
In this article we will show you how to create PDF Page Removal Tool based on iText7 using Windows Application in Visual Studio using C#.
Prerequisites
Visual Studio 2010/2012/2013/15/17.
Project used version
VS2017, SQL SERVER 2012
Requirements: Microsoft .NET Framework 4.6.2 or higher.Download.
Step 1: Go to -> File -> New -> Project
Step 2: Select "Visual C#" as programming language, Select "Windows Forms Application", Project Name as "PDFPageRemoval" and Click OK Button.
Step 3: Rename form name "Form1" as "frmRemovalPDFPages".
Step 4: Goto Form (frmRemovePDFPages) form Solution Explorer, and design form as shown below:
Control | Text | Design Name |
Text Box | txtPDFSource | |
Text Box | txtTotalPages | |
Text Box | txtPDFDestination | |
Text Box | txtRemovePages | |
Label | lblSourceFileName | Source file name |
Label | lblTotalPages | Total pages |
Label | lblDestinationFileName | Destination file name |
Label | lblPageRemoved | Pages to be removed |
Button | btnSelectPDF | |
Button | btnOk | Apply |
Button | btnClose | Exit |
OpenFileDialog | ofdPDFSource |
First of all declared a variable and List at top after constructor.
string egPages = "eg. 2,4-7,50";
List listPages = new List();
and add iText 7 libaray to your created project.
To download iText7 libaray Click here (Github)
or
from Nuget Click here (Nuget)
Create a Method GetRemovedPage() to remove pages from pdf file.
Source:
private bool GetRemovedPages()
{
listPages.Clear();
int total = Convert.ToInt32(txtTotalPages.Text);
char[] sep = new char[] { ',' };
string[] pages = txtRemovePages.Text.Split(sep, StringSplitOptions.RemoveEmptyEntries);
try
{
for (int i = 0; i < pages.Length; i++)
{
int n1 = Convert.ToInt32(pages[i].Split('-')[0]);
int n2 = pages[i].Contains("-")
? Convert.ToInt32(pages[i].Split('-')[1])
: n1;
if (0 < n1 && n1 <= n2 && n2 <= total)
{
for (int j = n1; j <= n2; j++)
{
listPages.Add(j);
}
}
else
{
return false;
}
}
}
catch (Exception)
{
return false;
}
listPages = listPages
.Distinct()
.OrderBy(p => p)
.ToList();
return true;
}
Now click on the Open PDF File Button (btnSelectPDF) and write following code
private void pbSelectFile_Click(object sender, EventArgs e)
{
if (ofdPDFSource.ShowDialog() == DialogResult.OK)
{
try
{
PdfDocument pdfSrc = new PdfDocument(new PdfReader(ofdPDFSource.FileName));
txtPDFSource.Text = ofdPDFSource.FileName;
txtTotalPages.Text = pdfSrc.GetNumberOfPages().ToString();
}
catch (Exception)
{
MessageBox.Show("Invalid pdf file.",
"Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
}
After Click on Apply Button (btnOk) and write the following code.
private void btnOk_Click(object sender, EventArgs e)
{
string src = txtPDFSource.Text;
string dest = txtPDFDestination.Text.Trim();
if (src == "")
{
MessageBox.Show("Please select the source file.",
"Tip", MessageBoxButtons.OK, MessageBoxIcon.Stop);
txtPDFSource.Focus();
}
else if (dest == "")
{
MessageBox.Show("Please input the destination file name, without its path and extension.",
"Tip", MessageBoxButtons.OK, MessageBoxIcon.Stop);
txtPDFDestination.Focus();
}
else if (txtRemovePages.Text == egPages || txtRemovePages.Text == "")
{
MessageBox.Show("Please input the pages to be removed.",
"Tip", MessageBoxButtons.OK, MessageBoxIcon.Stop);
txtRemovePages.Focus();
}
else
{
PdfDocument pdfSrc = new PdfDocument(new PdfReader(src));
PdfDocument pdfDest;
try
{
string path = System.IO.Path.GetDirectoryName(txtPDFSource.Text);
dest = System.IO.Path.Combine(path, txtPDFDestination.Text + ".pdf");
pdfDest = new PdfDocument(new PdfWriter(dest));
}
catch (Exception)
{
MessageBox.Show("Invalid destination file name or file already exists.",
"Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtPDFDestination.Focus();
return;
}
if (!GetRemovedPages())
{
MessageBox.Show("Invalid input.",
"Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtRemovePages.Focus();
return;
}
try
{
for (int i = 0; i < listPages.Count(); i++)
{
int start = i == 0 ? 1 : listPages[i - 1] + 1;
int end = listPages[i] - 1;
if (start <= end)
pdfSrc.CopyPagesTo(start, end, pdfDest);
}
int total = Convert.ToInt32(txtTotalPages.Text);
if ((listPages.Last() + 1) <= total)
pdfSrc.CopyPagesTo((listPages.Last() + 1), total, pdfDest);
pdfSrc.Close();
pdfDest.Close();
txtPDFDestination.Text = "";
txtRemovePages.Text = "";
var ask = MessageBox.Show(dest + " is created successfully.\n\nOpen it?",
"Infomation", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Information);
if (ask == DialogResult.Yes)
Process.Start(dest);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
}
On Form Load event write the code
private void Remove_Load(object sender, EventArgs e)
{
txtRemovePages.Text = egPages;
txtRemovePages.ForeColor = Color.Gray;
}
and last write a code on close button (btnClose)
private void btClose_Click(object sender, EventArgs e)
{
Application.Exit();
}
Complete Source Code:
using iText.Kernel.Pdf;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
namespace PDFPageRemoval
{
public partial class Remove : Form
{
public Remove()
{
InitializeComponent();
}
string egPages = "eg. 2,4-7,50";
List listPages = new List();
private void Remove_Load(object sender, EventArgs e)
{
txtRemovePages.Text = egPages;
txtRemovePages.ForeColor = Color.Gray;
}
private void pbSelectFile_Click(object sender, EventArgs e)
{
if (ofdPDFSource.ShowDialog() == DialogResult.OK)
{
try
{
PdfDocument pdfSrc = new PdfDocument(new PdfReader(ofdPDFSource.FileName));
txtPDFSource.Text = ofdPDFSource.FileName;
txtTotalPages.Text = pdfSrc.GetNumberOfPages().ToString();
}
catch (Exception)
{
MessageBox.Show("Invalid pdf file.",
"Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
}
private void btnOk_Click(object sender, EventArgs e)
{
string src = txtPDFSource.Text;
string dest = txtPDFDestination.Text.Trim();
if (src == "")
{
MessageBox.Show("Please select the source file.",
"Tip", MessageBoxButtons.OK, MessageBoxIcon.Stop);
txtPDFSource.Focus();
}
else if (dest == "")
{
MessageBox.Show("Please input the destination file name, without its path and extension.",
"Tip", MessageBoxButtons.OK, MessageBoxIcon.Stop);
txtPDFDestination.Focus();
}
else if (txtRemovePages.Text == egPages || txtRemovePages.Text == "")
{
MessageBox.Show("Please input the pages to be removed.",
"Tip", MessageBoxButtons.OK, MessageBoxIcon.Stop);
txtRemovePages.Focus();
}
else
{
PdfDocument pdfSrc = new PdfDocument(new PdfReader(src));
PdfDocument pdfDest;
try
{
string path = System.IO.Path.GetDirectoryName(txtPDFSource.Text);
dest = System.IO.Path.Combine(path, txtPDFDestination.Text + ".pdf");
pdfDest = new PdfDocument(new PdfWriter(dest));
}
catch (Exception)
{
MessageBox.Show("Invalid destination file name or file already exists.",
"Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtPDFDestination.Focus();
return;
}
if (!GetRemovedPages())
{
MessageBox.Show("Invalid input.",
"Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
txtRemovePages.Focus();
return;
}
try
{
for (int i = 0; i < listPages.Count(); i++)
{
int start = i == 0 ? 1 : listPages[i - 1] + 1;
int end = listPages[i] - 1;
if (start <= end)
pdfSrc.CopyPagesTo(start, end, pdfDest);
}
int total = Convert.ToInt32(txtTotalPages.Text);
if ((listPages.Last() + 1) <= total)
pdfSrc.CopyPagesTo((listPages.Last() + 1), total, pdfDest);
pdfSrc.Close();
pdfDest.Close();
txtPDFDestination.Text = "";
txtRemovePages.Text = "";
var ask = MessageBox.Show(dest + " is created successfully.\n\nOpen it?",
"Infomation", MessageBoxButtons.YesNoCancel, MessageBoxIcon.Information);
if (ask == DialogResult.Yes)
Process.Start(dest);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
}
}
private bool GetRemovedPages()
{
listPages.Clear();
int total = Convert.ToInt32(txtTotalPages.Text);
char[] sep = new char[] { ',' };
string[] pages = txtRemovePages.Text.Split(sep, StringSplitOptions.RemoveEmptyEntries);
try
{
for (int i = 0; i < pages.Length; i++)
{
int n1 = Convert.ToInt32(pages[i].Split('-')[0]);
int n2 = pages[i].Contains("-")
? Convert.ToInt32(pages[i].Split('-')[1])
: n1;
if (0 < n1 && n1 <= n2 && n2 <= total)
{
for (int j = n1; j <= n2; j++)
{
listPages.Add(j);
}
}
else
{
return false;
}
}
}
catch (Exception)
{
return false;
}
listPages = listPages
.Distinct()
.OrderBy(p => p)
.ToList();
return true;
}
private void btClose_Click(object sender, EventArgs e)
{
Application.Exit();
}
#region input pages to be removed
private void tbPage_Enter(object sender, EventArgs e)
{
if (txtRemovePages.ForeColor == Color.Gray)
{
txtRemovePages.Text = "";
txtRemovePages.ForeColor = SystemColors.WindowText;
}
}
private void tbPage_MouseDown(object sender, MouseEventArgs e)
{
if (txtRemovePages.ForeColor == Color.Gray)
{
txtRemovePages.Text = "";
txtRemovePages.ForeColor = SystemColors.WindowText;
}
}
private void tbPage_Leave(object sender, EventArgs e)
{
if (txtRemovePages.Text == "")
{
txtRemovePages.Text = egPages;
txtRemovePages.ForeColor = Color.Gray;
}
}
private void tbPage_KeyPress(object sender, KeyPressEventArgs e)
{
//
if (!(char.IsNumber(e.KeyChar))
&& e.KeyChar != (char)Keys.Back
&& e.KeyChar != '-'
&& e.KeyChar != ',')
e.Handled = true;
else
e.Handled = false;
}
#endregion input pages to be removed
}
}