Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Password protected PDF using C#

I am creating a pdf document using C# code in my process. I need to protect the docuemnt with some standard password like "123456" or some account number. I need to do this without any reference dlls like pdf writer.

I am generating the PDF file using SQL Reporting services reports.

Is there are easiest way.

like image 889
balaweblog Avatar asked Dec 16 '08 06:12

balaweblog


People also ask

Can I password protect a PDF file?

Open the PDF and choose Tools > Protection > Encrypt > Encrypt with Password 6. If you receive a prompt, click Yes to change the security. 7. Select Require A Password To Open The Document, then type the password in the corresponding field.


2 Answers

I am creating a pdf document using C# code in my process

Are you using some library to create this document? The pdf specification (8.6MB) is quite big and all tasks involving pdf manipulation could be difficult without using a third party library. Password protecting and encrypting your pdf files with the free and open source itextsharp library is quite easy:

using (Stream input = new FileStream("test.pdf", FileMode.Open, FileAccess.Read, FileShare.Read))
using (Stream output = new FileStream("test_encrypted.pdf", FileMode.Create, FileAccess.Write, FileShare.None))
{
    PdfReader reader = new PdfReader(input);
    PdfEncryptor.Encrypt(reader, output, true, "secret", "secret", PdfWriter.ALLOW_PRINTING);
}
like image 85
Darin Dimitrov Avatar answered Sep 30 '22 13:09

Darin Dimitrov


It would be very difficult to do this without using a PDF library. Basically, you'll need to develop such library yourselves.

With help of a PDF library everything is much simpler. Here is a sample that shows how a document can easily be protected using Docotic.Pdf library:

public static void protectWithPassword(string input, string output)
{
    using (PdfDocument doc = new PdfDocument(input))
    {
        // set owner password (a password required to change permissions)
        doc.OwnerPassword = "pass";

        // set empty user password (this will allow anyone to
        // view document without need to enter password)
        doc.UserPassword = "";

        // setup encryption algorithm
        doc.Encryption = PdfEncryptionAlgorithm.Aes128Bit;

        // [optionally] setup permissions
        doc.Permissions.CopyContents = false;
        doc.Permissions.ExtractContents = false;

        doc.Save(output);
    }
}

Disclaimer: I work for the vendor of the library.

like image 45
Bobrovsky Avatar answered Sep 30 '22 13:09

Bobrovsky