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 8) Razor Pages.
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_Razor
{
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;
Index PageModel (Code-Behind)
Inside the PageModel, first the private property DbContext class is created.
Then, the interface is injected into the Constructor (IndexModel) using Dependency Injection method and the injected object is assigned to private property (created earlier) and the public property of Generic List collection of Customer Model class is created.
The PageModel consists of following Handler methods.
Handler method for handling GET operation
Inside this Handler method, the records from the
Customers Table are fetched using
Entity Framework and set into public property of Generic List collection of
Customer Model class.
Handler method for handling POST operation
This Handler 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 Handler 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 IndexModel : PageModel
{
private DBCtx Context { get; }
public IndexModel(DBCtx _context)
{
this.Context = _context;
}
public List<Customer> Customers { get; set; }
public void OnGet()
{
this.Customers = (from customer in this.Context.Customers.Take(10)
select customer).ToList();
}
public FileResult OnPostExportToPDF()
{
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");
}
}
}
Razor Page (HTML)
HTML Markup
Inside the Razor Page, the ASP.Net TagHelpers is inherited.
Inside the Razor Page an HTML Table is populated with customer records using FOR EACH loop executed over the Model.
The Razor Page consist of an HTML Form which consists of a Submit Button.
The Submit Button has been set with the POST Handler method using the asp-page-handler attribute.
Note: In the Razor PageModel, the Handler method name is OnPostExportToPDF but here it will be specified as ExportToPDF when calling from the Razor HTML Page.
@page
@using PasswordProtected_PDF_Core_Razor.Models
@model PasswordProtected_PDF_Core_Razor.Pages.IndexModel
@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.Customers)
{
<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" >
<input id="btnSubmit" type="submit" value="ExportTo PDF" asp-page-handler="ExportToPDF" />
</form>
</body>
</html>
Screenshots
The Form
Exported PDF
Downloads