In this article I will explain with an example, how to create
Password Protected (Secured)
PDF using
iTextSharp library in ASP.Net MVC.
Download iTextSharp and XmlWorkerHelper Libraries
In order to install
iTextSharp and
XmlWorkerHelper library from
Nuget, please refer the following articles.
Entity Framework Model
Once the
Entity Framework is configured and connected to the database table, the Model will look as shown below.
Namespaces
You will need to import the following namespaces.
using System.IO;
using System.Data;
using System.Text;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.tool.xml;
Controller
The Controller consists of following Action methods.
Action method for handling GET operation
Inside this Action method, the records from the
Customers Table are fetched using
Entity Framework and returned to the View.
Action method for handling POST operation
This Action method gets called, when Export Button is clicked.
Note: The following Action method performs File Download and hence the return type is set to FileResult.
Inside this Action Method, Top 10 Customer records are fetched from the
Customers Table using
Entity Framework and then using the
StringBuilder class, a string consisting of an HTML Table is generated.
Then, the HTML string is read using an object of
StringReader class which is then supplied to the
ParseXHtml method of the
XMLWorkerHelper class which converts it to
PDF document and saves it to the
MemoryStream class object.
The MemoryStream class object is converted into BYTE Array which is passed as parameter to PdfReader class.
Another
MemoryStream object is created which is used for making
PDF Password Protected using the
Encrypt method of
PdfEncrypter class and the result is saved in the output
MemoryStream object.
Note: The Encrypt method accepts the password as parameter.
Finally, the
MemoryStream class object is converted to BYTE Array and exported as
PDF file using the
File function.
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
NorthwindEntities entities = new NorthwindEntities();
return View(from customer in entities.Customers.Take(10)
select customer);
}
[HttpPost]
public FileResult ExportToPDF()
{
NorthwindEntities entities = new NorthwindEntities();
List<object> customers = (from customer in entities.Customers.ToList().Take(10)
select new[] {
customer.ContactName,
customer.City,
customer.Country
}).ToList<object>();
//Building an HTML string.
StringBuilder sb = new StringBuilder();
//Table start.
sb.Append("<table border='1' cellpadding='5' cellspacing='0' style='border: 1px solid #ccc;font-family: Arial;'>");
//Building the Header row.
sb.Append("<tr>");
sb.Append("<th style='background-color: #B8DBFD;border: 1px solid #ccc'>Contact Name</th>");
sb.Append("<th style='background-color: #B8DBFD;border: 1px solid #ccc'>City</th>");
sb.Append("<th style='background-color: #B8DBFD;border: 1px solid #ccc'>Country</th>");
sb.Append("</tr>");
//Building the Data rows.
for (int i = 0; i <customers.Count;i++)
{
string[] customer = (string[])customers[i];
sb.Append("<tr>");
for (int j = 0; j < customer.Length; j++)
{
//Append data.
sb.Append("<td style='border: 1px solid #ccc'>");
sb.Append(customer[j]);
sb.Append("</td>");
}
sb.Append("</tr>");
}
//Table end.
sb.Append("</table>");
byte[] bytes = null;
using (MemoryStream memoryStream = new MemoryStream())
{
StringReader sr = new StringReader(sb.ToString());
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 100f, 0f);
PdfWriter writer = PdfWriter.GetInstance(pdfDoc, memoryStream);
pdfDoc.Open();
XMLWorkerHelper.GetInstance().ParseXHtml(writer, pdfDoc, sr);
pdfDoc.Close();
bytes = memoryStream.ToArray();
}
// Adding password to PDF.
using (MemoryStream output = new MemoryStream())
{
string password = "pass@123";
PdfReader reader = new PdfReader(bytes);
PdfEncryptor.Encrypt(reader, output, true, password, password, PdfWriter.ALLOW_SCREENREADERS);
return File(output.ToArray(), "application/pdf", "GridViewExport.pdf");
}
}
}
View
HTML Markup
Inside the View an HTML Table is populated with customer records using FOR EACH loop executed over the Model.
The View consists of an HTML Form which has been created using the Html.BeginForm method with the following parameters.
ActionName – Name of the Action. In this case the name is Save.
ControllerName – Name of the Controller. In this case the name is Home.
FormMethod – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
The HTML Form consists of a Submit Button which when clicked, the Form is submitted.
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div id="Grid">
<table cellpadding="5" cellspacing="0" style="border:1px solid #ccc;">
<tr>
<th style="background-color:#B8DBFD;border:1px solid #ccc">Contact Name</th>
<th style="background-color:#B8DBFD;border:1px solid #ccc">City</th>
<th style="background-color:#B8DBFD;border:1px solid #ccc">Country</th>
</tr>
@foreach (Customer customer in Model)
{
<tr>
<td style="border:1px solid #ccc">@customer.ContactName</td>
<td style="border:1px solid #ccc">@customer.City</td>
<td style="border:1px solid #ccc">@customer.Country</td>
</tr>
}
</table>
</div>
<br />
@using (Html.BeginForm("ExportToPDF", "Home", FormMethod.Post))
{
<input id="btnSubmit" type="submit" value="ExportTo PDF" />
}
</body>
</html>
Screenshots
The Form
Exported PDF
Downloads