Background
Nowadays, data theft has become more and more popular. Thus, the security of our confidential information has vaulted to the top of our concerns. For example, we will automatically think to secure an important file before we send it to recipients to prevent its content from an unauthorized access. And this is the main purpose of writing this article.
Introduction
- Setting security to PDF document.
- Changing security settings of PDF document.
- Removing security from PDF document.
- Detecting if the PDF document is encrypted.
Part 1 - Setting security to PDF document
Adding passwords
We can add two kinds of passwords to protect PDF documents, i.e. we can add a user password (also referred to as document open password), so that only users who have the password can open the document and we can add an owner password (also referred to as permissions password), so that only users, who have the password can change the permissions of the document.
User password
- //Create a PDF document
- PdfDocument pdf = new PdfDocument();
- //Add a page
- PdfPageBase page = pdf.Pages.Add();
- //Insert text
- page.Canvas.DrawString("This document is protected with user password ", new PdfFont(PdfFontFamily.Helvetica, 13f), PdfBrushes.Black, PointF.Empty);
- //Specify encryption level (algorithm)
- pdf.Security.KeySize = PdfEncryptionKeySize.Key40Bit;
- //Add user password
- pdf.Security.UserPassword = "userpassword";
- //Save the document
- pdf.SaveToFile("Userpassword.pdf");
Result

Owner password
- //Create a PDF document
- PdfDocument pdf = new PdfDocument();
- //Add a page
- PdfPageBase page = pdf.Pages.Add();
- //Insert text
- page.Canvas.DrawString("This document is protected with owner password", new PdfFont(PdfFontFamily.Helvetica, 13f), PdfBrushes.Black, new RectangleF(0, 0, 480, 300));
- //Specify encryption level (algorithm)
- pdf.Security.KeySize = PdfEncryptionKeySize.Key128Bit;
- //Add owner password
- pdf.Security.OwnerPassword = "ownerpassword";
- //Save the document
- pdf.SaveToFile("Ownerpassword.pdf");
Result

Setting Permissions
Permissions can increase the flexibility of document security. By customizing the permission settings, we can easily allow or prevent users from editing and copying information or limit other activities like printing and form filling.

ayush tripathiPosted May 26, 2019, 11:06 AM
Could u please let me know how to use these classes without using third party library
Nithish ReddyPosted May 22, 2018, 7:54 AM
How to restrict a pdf file from print and download ? i need help !
Nithish ReddyPosted Apr 30, 2018, 5:39 AM
How to do it in asp.net mvc ?
Himanshu MangePosted Sep 12, 2017, 12:54 PM
Hi, nice article but in part 4 while detecting encrypted files, pdf.Loadfromfile method throws error what i discovered that we cannot determine whether file is encrypted or not without reading, may be I m wrong but did you checked it ?