In this article I will explain with an example, how to create
Password Protected (Secured)
PDF using
iTextSharp library in ASP.Net Core (.Net Core) MVC.
Download iTextSharp and XmlWorkerHelper Libraries
In order to install
iTextSharp and
XmlWorkerHelper library from
Nuget, please refer the following articles.
Database Context
Once the
Entity Framework is configured and connected to the database table, the Database Context will look as shown below.
using Microsoft.EntityFrameworkCore;
namespace PasswordProtected_PDF_Core
{
public class DBCtx : DbContext
{
public DBCtx(DbContextOptions<DBCtx> options) : base(options)
{
}
public DbSet<Customer> Customers { get;set; }
}
}
Model
You will need to import the following namespaces.
public class Customer
{
public string? CustomerID { get; set; }
public string? ContactName { get; set; }
public string? City { get; set; }
public string? Country { get; set; }
}
Namespaces
You will need to import the following namespaces.
using System.Data;
using System.Text;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.tool.xml;
Controller
Inside the Controller, first the private property DbContext class is created.
Then, the interface is injected into the Constructor (HomeController) using Dependency Injection method and the injected object is assigned to private property (created earlier).
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
{
private DBCtx Context { get; }
public HomeController(DBCtx _context)
{
this.Context = _context;
}
public IActionResult Index()
{
List<Customer> customers = (from customer in this.Context.Customers.Take(10)
select customer).ToList();
return View(customers);
}
[HttpPost]
public FileResult ExportToPDF()
{
List<object> customers = (from customer in this.Context.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, the Generic List collection of Customer Model class is declared as Model for the Views.
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 following TagHelpers attributes.
asp-action – Name of the Action. In this case the name is ExportToPDF.
asp-controller – Name of the Controller. In this case the name is Home.
method – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
The View also consists of a Submit Button which when clicked, the Form is submitted.
@using PasswordProtected_PDF_Core.Models;
@model IEnumerable<Customer>
@addTagHelper*,Microsoft.AspNetCore.Mvc.TagHelpers
@{
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 />
<form method="post" asp-action="ExportToPDF" asp-controller="Home">
<input id="btnSubmit" type="submit" value="Export To PDF" />
</form>
</body>
</html>
Screenshots
The Form
Exported PDF
Downloads