Monday, 12 March 2012

Protecting a PDF file with Password

using System.IO;
using iTextSharp.text.pdf;
using System.Diagnostics;

//---- for this itextsharp.dll is required.
protected void Page_Load(object sender, EventArgs e)
    {
        string PDFPath = @"c:\>.netProjects\AllParticipantList.pdf";
        string Password = "abc123";

        EncryptPDFwithPassword(PDFPath, Password); //Password Protecting the pdf
        DecryptPasswordprotectedPDF(PDFPath, Password);
       
    }

private void EncryptPDFwithPassword(string strPDFPath, string strPassword)
    {
        try
       {
           Stream input = new FileStream(strPDFPath, FileMode.Open, FileAccess.Read, FileShare.Read);
            byte[] btSourceFile = StreamToByteArray(input);
            input.Close();
           

            using (Stream output = new FileStream(strPDFPath, FileMode.Create, FileAccess.Write, FileShare.None))
            {
                PdfReader reader = new PdfReader(btSourceFile);
                reader.Close();
                PdfEncryptor.Encrypt(reader, output, true, strPassword, strPassword, PdfWriter.ALLOW_PRINTING);
            }
        }
        catch(Exception ex)
        {

        }
    }

static byte[] StreamToByteArray(Stream inputStream)
    {
        if (!inputStream.CanRead)
        {
            throw new ArgumentException();
        }

        // This is optional
        if (inputStream.CanSeek)
        {
            inputStream.Seek(0, SeekOrigin.Begin);
        }

        byte[] output = new byte[inputStream.Length];
        int bytesRead = inputStream.Read(output, 0, output.Length);
        Debug.Assert(bytesRead == output.Length, "Bytes read from stream matches stream length");
        return output;
    }


private void DecryptPasswordprotectedPDF(string strPDFPath, string strPassword)
    {
        try
        {
            byte[] btPassword;
            btPassword = StrToByteArray(strPassword);


            Stream input = new FileStream(strPDFPath, FileMode.Open, FileAccess.Read, FileShare.Read);
            byte[] btSourceFile = StreamToByteArray(input);
            input.Close();

            PdfReader reader = new PdfReader(btSourceFile, btPassword);

            ////@+ decryption routine
            if (reader.IsOpenedWithFullPermissions)
            {
                PdfStamper pdfstmpr = new PdfStamper(reader, new FileStream(strPDFPath, FileMode.Create, FileAccess.Write, FileShare.None));
                pdfstmpr.Close();
            }

        }
        catch
        {
        }
    }


    public static byte[] StrToByteArray(string str)
    {
        System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
        return encoding.GetBytes(str);
    }


No comments:

Post a Comment