Create A Password Protected PDF In MVC

Sometimes, we need to create a PDF file that opens only when the users put in a password when prompted. Let us see how to create a password-protected PDF file in MVC.
 
First, let's open Visual Studio and create a new project.
We need to select the ASP.NET Web application type.
 
Create Password Protected PDF In MVC 
 
Select Web API as the template and in the "Add folders and core references" section, we need to select MVC and Web API.
 
Click on "Change Authentication" on the right side pane and select "No Authentication".
 
Create Password Protected PDF In MVC 
 
In the web.config file, let us define one key named Filepath and use it in our code. The PDF file must be present there. 
 
It is good to change the key's value when it's placed in web.config.
  1. <appSettings>  
  2.      <add key="FilePath" value="Anil\PDF\LDEPRD9.pdf"/>  
  3.  </appSettings>  

Add the below code to the Home Controller.

  1. string FilePath = ConfigurationManager.AppSettings["FilePath"].ToString();  
  2. public ActionResult DownloadFile()  
  3. {  
  4.     try  
  5.     {  
  6.         byte[] bytes = System.IO.File.ReadAllBytes(FilePath);  
  7.         using (MemoryStream inputData = new MemoryStream(bytes))  
  8.         {  
  9.         using (MemoryStream outputData = new MemoryStream())  
  10.         {  
  11.         string PDFFilepassword = "123456";  
  12.         PdfReader reader = new PdfReader(inputData);  
  13.         PdfReader.unethicalreading = true;  
  14. PdfEncryptor.Encrypt(reader, outputData, true, PDFFilepassword, PDFFilepassword, PdfWriter.ALLOW_SCREENREADERS);
  15.         bytes = outputData.ToArray();  
  16.         Response.AddHeader("content-length", bytes.Length.ToString());  
  17.         Response.BinaryWrite(bytes);  
  18.         return File(bytes, "application/pdf");  
  19.        }  
  20.       }  
  21.     }  
  22.     catch (Exception ex)  
  23.     {  
  24.         throw ex;  
  25.     }  
  26. }  
  1. string PDFFilepassword = "123456";    
  2. PdfReader reader = new PdfReader(inputData);    
  3. PdfReader.unethicalreading = true;    
  4. PdfEncryptor.Encrypt(reader, outputData, true, PDFFilepassword, PDFFilepassword, PdfWriter.ALLOW_SCREENREADERS);  
In the PDFFilepassword variable, you can set anything as password - the file name, PAN card number, or you can validate the entered value against the values stored in the database.
 
In Route.config, we can define the default route with the Controller And ActionName.
 
Create Password Protected PDF In MVC 
 
Run the website and enter http://localhost:49744/Home/DownloadFile. 
 
Here, Home is the controller name and DownloadFile is the action name. 
 
It shows the following Password prompt.
 
Create Password Protected PDF In MVC 
 
After entering the right password and successful authentication, the PDF file will get opened.