Answered by:
checking if pdf file is password protected

Question
-
User-153404742 posted
Is there a free nuget package or an easy way to check if pdf file is password protected? I can check microsoft document files but not sure of checking pdf with c# code.
Thursday, March 4, 2021 4:59 PM
Answers
-
User-153404742 posted
thank you. PDFSharp works.
- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Tuesday, March 9, 2021 12:44 AM
All replies
-
User-1330468790 posted
Hi inkaln,
You could use iTextSharp with the PdfReader as a workaround.
Here is a solution from stackoverflow.
The problem with using the
PdfReader.IsEncrypted
method is that if you attempt to instantiate aPdfReader
on a PDF that requires a password - and you don't supply that password - you'll get aBadPasswordException
.Keeping this in mind you can write a method like this:
public static bool IsPasswordProtected(string pdfFullname) { try { PdfReader pdfReader = new PdfReader(pdfFullname); return false; } catch (BadPasswordException) { return true; } }
Note that if you supply an invalid password you'll get the same
BadPasswordException
when attempting to construct aPdfReader
object. You can use this to create a method that validates a PDF's password:public static bool IsPasswordValid(string pdfFullname, byte[] password) { try { PdfReader pdfReader = new PdfReader(pdfFullname, password); return false; } catch (BadPasswordException) { return true; } }
Sure it's ugly but as far as I know this is the only way to check if a PDF is password protected. Hopefully someone will suggest a better solution.
Reference:
https://stackoverflow.com/a/11300144/12871232
Hope helps.
Best regards,
Sean
Friday, March 5, 2021 2:53 AM -
User-153404742 posted
Is iTextSharp free to use for commercial software?
Friday, March 5, 2021 9:24 PM -
User-1330468790 posted
Hi inkaln,
I am afraid that iTextSharp is not free for commercial usage.
iText is free software released under the AGPL. This means that it can be used for free on condition that you also release the source code of your project for free under the same license. As soon as you start offering the code or the project (e.g. in the context of a SaaS offering) under a different license, then you should purchase a commercial license.
The explanation for AGPL could be found below:
https://www.gnu.org/licenses/agpl-3.0.html
Rarely can you find a free pdf library as good as iTextSharp, especially for commercial use.
Best regards,
Sean
Monday, March 8, 2021 10:33 AM -
User753101303 posted
Hi,
Check perhaps the license for other other librairies such as https://csharp-source.net/open-source/pdf-libraries
The last resorrt could be to find a PDF specification that should describe what in the PDF file header, allows to tell if the file is encrypted or not.
Monday, March 8, 2021 2:45 PM -
User-153404742 posted
thank you. PDFSharp works.
- Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
Tuesday, March 9, 2021 12:44 AM