Site icon Ryadel

ASP.NET C# – How to check if a PDF file is password protected

ASP.NET C# - How to convert Office files to PDF using SyncFusion File Formats & Essential Studio

If you found this post it most likely means that you're looking for a way to determine if a PDF file is password protected or not using ASP.NET C#. This is a typical requirement of any website accepting user-uploaded files, because those files will probably need to be opened by other users and/or administrators that don't know that password.

Luckily enough I've found a quick and effective way to do that using SyncFusion's PDF libraries, which I've already introduced in this blog a couple years ago. In this post we'll see how we can do that.

DISCLAIMER: This website is not affiliated with SyncFusion; this article represents the free opinion of the author and has not been commissioned or sponsored in any way.

The workaround I've used relies upon the PdfLoadedDocument class in the Syncfusion.Pdf.Parsing namespace, which is the standard way used by SyncFusion libraries to read a PDF file in memory. Such class is able to load even password-protected PDF files, as long as we pass the correct password in the constructor; however, if we do instantiate the PDF using the standard "passwordless" overload, it won't be able to do that - thus throwing a Syncfusion.Pdf.PdfDocumentException.

This is precisely what we want! All we need to do is to trap that exception and we're done.

Here's a quick code sample demonstrating such technique:

If you need to check for additional layers of protections, such as printing password, you can easily do that using the pdfDoc.Security.Permissions property,  which can be checked against the following flags:

  • Syncfusion.Pdf.Security.PdfPermissionsFlags.Default : no protection (no passwords)
  •  Syncfusion.Pdf.Security.PdfPermissionsFlags.AccessibilityCopyContent: copy accessibility content
  • Syncfusion.Pdf.Security.PdfPermissionsFlags.AssembleDocument: assemble document permission (only for 128 bits key)
  • Syncfusion.Pdf.Security.PdfPermissionsFlags.CopyContent: copy content
  • Syncfusion.Pdf.Security.PdfPermissionsFlags.EditAnnotations: add or modify text annotations, fill in interactive form field
  • Syncfusion.Pdf.Security.PdfPermissionsFlags.EditContent: edit content
  • Syncfusion.Pdf.Security.PdfPermissionsFlags.FillFields: fill form fields (only for 128 bits key)
  • Syncfusion.Pdf.Security.PdfPermissionsFlags.FullQualityPrint: full quality print
  • Syncfusion.Pdf.Security.PdfPermissionsFlags.Print: print the document

Here's an example of how the above sample can be extended to also check for print-based permissons:

That's it!

Conclusion

I hope that this simple yet effective method will help other ASP.NET developers who are looking for a way to determine if a PDF file is password protected or not.

Exit mobile version