Passwords can ensure that only the people who need to review a document can open and make changes to it if you need to adhere to a strict process. Locking documents can also prevent form edits in PDFs.
By password-protecting a Word or PDF document, you can keep private and sensitive information safe. This encrypts the file’s contents, making it inaccessible to anyone without entering the password.
Step 1 : First, let’s open Visual Studio and create a new project
Step 2 : Install Nuget package iTextSharp
Step 3 : Copy and Paste below code in view to create a button
<div class="text-center"> @Html.ActionLink("Oepn PDF", "OpenPDF", "Home", null, new { @class = "btn btn-primary btn-large" }) </div>
Step 4 : Define the path of PDF in the appsetting.json file and read the in controller
In appsetting.json
"File": { "Path": "C:\\Users\\pc3\\Desktop\\PasswordProtectedPDF\\PDF\\Funday.pdf" }
Read path from appsetting.json
using Microsoft.Extensions.Configuration; public static IConfiguration _configuration; public HomeController(IConfiguration configuration) { _configuration = configuration; }
Step 5 : Copy and paste the below code into your controller
using Microsoft.Extensions.Configuration; public static IConfiguration _configuration; public HomeController(IConfiguration configuration) { _configuration = configuration; } public ActionResult OpenPDF() { var pathToFile = _configuration.GetSection("File").GetSection("Path").Value; byte[] bytes = System.IO.File.ReadAllBytes(pathToFile); using (MemoryStream inputData = new MemoryStream(bytes)) { using (MemoryStream outputData = new MemoryStream()) { string PDFFilepassword = "niki@123"; PdfReader reader = new PdfReader(inputData); PdfReader.unethicalreading = true; PdfEncryptor.Encrypt(reader, outputData, true, PDFFilepassword, PDFFilepassword, PdfWriter.ALLOW_SCREENREADERS); bytes = outputData.ToArray(); return File(bytes, "application/pdf"); } } }
OUTPUT