How to decrypt a pdf file by supplying password of the file as argument using c#?

荒凉一梦 提交于 2019-12-06 15:11:52

问题


I have generated a pdf file with password protection by using the following code:

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, strDob, "secret", PdfWriter.ALLOW_SCREENREADERS);
    }
}

I want to remove the password for the PDF file generated using the above code based on my certain condtions through code.


回答1:


string WorkingFolder = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string InputFile = Path.Combine(WorkingFolder, "test.pdf");
string OutputFile = Path.Combine(WorkingFolder, "test_dec.pdf");//will be created automatically
//You must provide owner password but not the user password .
private void DecryptFile(string inputFile, string outputFile)
{

    string password = @"secret"; // Your Key Here           
    try
    {
        PdfReader reader = new PdfReader(inputFile, new System.Text.ASCIIEncoding().GetBytes(password));

            using (MemoryStream memoryStream = new MemoryStream())
            {
                PdfStamper stamper = new PdfStamper(reader, memoryStream);
                stamper.Close();
                reader.Close();
                File.WriteAllBytes(outputFile, memoryStream.ToArray());
            }

    }
    catch (Exception err)
    {
        Console.WriteLine(err.Message);
    }
}


来源:https://stackoverflow.com/questions/11014148/how-to-decrypt-a-pdf-file-by-supplying-password-of-the-file-as-argument-using-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!