Harikasai
Harikasai

Reputation: 1307

How to add password protection to a PDF File

I use the following code :

string WorkingFolder = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string InputFile = Path.Combine(WorkingFolder, "PSNOs.pdf");
string OutputFile = Path.Combine(WorkingFolder, "PSNOs_enc.pdf");
using (Stream input = new FileStream(InputFile, FileMode.Open, FileAccess.Read, FileShare.Read))
{
    using (Stream output = new FileStream(OutputFile, FileMode.Create, FileAccess.Write, FileShare.None))
    {
        PdfReader reader = new PdfReader(input);
        PdfEncryptor.Encrypt(reader, output, true, null, "secret", PdfWriter.ALLOW_SCREENREADERS);
    }
} 

But it is creating another file and adding password to the output file. But I don't want to create two files like the above. I want to give the password for the input file PSNOs.pdf with out creating the other file.

Upvotes: 1

Views: 6904

Answers (3)

Anil Rathod
Anil Rathod

Reputation: 35

Create Password protected PDF using the iTextSharp

   string sourcePdf = @"D:\unsecuredfolder\unsecuredPage.pdf";
        using (Stream input = new FileStream(sourcePdf , FileMode.Open, FileAccess.Read, FileShare.Read))
               //Passowrd the pwd for PDF security                 

   string destPdf = @"D:\securedfolder\securedPage.pdf";

         /sourcePdf  unsecured PDF file
       //destPdf secured PDF file

        {
            using (Stream output = new FileStream(destPdf , FileMode.Create, FileAccess.Write, FileShare.None))
            {
                PdfReader reader = new PdfReader(input);

                string Password="abc@123";
                PdfEncryptor.Encrypt(reader, output, true, Password, Password, PdfWriter.ALLOW_PRINTING);
            }
        }

Upvotes: 1

Md Kamruzzaman Sarker
Md Kamruzzaman Sarker

Reputation: 2407

According to itextsharp documentation it can set password in newly created pdf. It can not give password to existing pdf file.

So your wishing to make password protected without creating new file is not possible by using itextsharp. to make password protected pdf you have to use output file(which is created password protected by PdfEncryptor.Encrypt() method) and delete the input pdf.

You can see this link also

Upvotes: 1

Ross
Ross

Reputation: 4578

It must be done this way unfortunately.

I would suggest you:

  1. Create the unsigned PDF in the system TEMP folder
  2. Sign it, outputting to the location and file name you want
  3. Clean up - delete the temp file.

Upvotes: 1

Related Questions