Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Password protecting a PDF file

Tags:

c#

I have the following:

  • routine X that creates a PDF file on a daily basis.
  • routine Y that attaches this file to an Outlook e-mail and sends it to recipients.

Both the above are in VBA. They are called from a C# console application.

Once the PDF has been created I need to password protect it. To do this via VBA without purchasing third party software is quite involved.

What is the simplest solution using C#?

(I'm suspecting there will be an inverse relationship between amount we spend and complexity of answer!)

like image 522
whytheq Avatar asked Sep 12 '12 07:09

whytheq


People also ask

How do I password protect a PDF file for free?

Click the Select a file button above or drag and drop a PDF into the drop zone. Enter a password, then retype it to confirm the password. Click Set password. Download the password protected PDF document or sign in to share it.

Why can't I password protect my PDF?

1 Correct answer. Go to File - Properties - Security and select "Password Security" under "Security Method". Select your settings, enter your password, and you're done.

Can you password protect PDF from PDF?

To convert password protected PDF to normal PDF need to use a robust document management tool, which is Wondershare PDFelement - PDF Editor. It is a reliable and user-friendly document management tool that can be used to edit, annotate, print, perform OCR, create and even convert PDF files without any hassle.


1 Answers

PDFSharp should be able to protect a PDF file with a password:

// Open an existing document. Providing an unrequired password is ignored.
PdfDocument document = PdfReader.Open(filename, "some text");

PdfSecuritySettings securitySettings = document.SecuritySettings;

// Setting one of the passwords automatically sets the security level to 
// PdfDocumentSecurityLevel.Encrypted128Bit.
securitySettings.UserPassword  = "user";
securitySettings.OwnerPassword = "owner";

// Don't use 40 bit encryption unless needed for compatibility reasons
//securitySettings.DocumentSecurityLevel = PdfDocumentSecurityLevel.Encrypted40Bit;

// Restrict some rights.
securitySettings.PermitAccessibilityExtractContent = false;
securitySettings.PermitAnnotations = false;
securitySettings.PermitAssembleDocument = false;
securitySettings.PermitExtractContent = false;
securitySettings.PermitFormsFill = true;
securitySettings.PermitFullQualityPrint = false;
securitySettings.PermitModifyDocument = true;
securitySettings.PermitPrint = false;

// Save the document...
document.Save(filename);

Reference:
http://www.pdfsharp.net/wiki/ProtectDocument-sample.ashx

like image 72
Daniel Hilgarth Avatar answered Sep 26 '22 14:09

Daniel Hilgarth