Monday, June 20, 2011

PDF Password Protect & Unprocted in C#

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 = @"D:\Project\screen_mock_up.pdf";
        string Password = "abc123";

        PasswordProtectPDF(PDFPath, Password);
        DecryptPassword(PDFPath, Password);
       
    }


private void PasswordProtectPDF(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 DecryptPassword(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);
    }


1 comment: