如何通过使用c#提供文件的密码作为参数来解密pdf文件?

时间:2012-06-13 11:44:38

标签: c# itextsharp

我使用以下代码生成了一个带密码保护的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, strDob, "secret", PdfWriter.ALLOW_SCREENREADERS);
    }
}

我想删除使用上述代码根据我的某些条件通过代码生成的PDF文件的密码。

1 个答案:

答案 0 :(得分:2)

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);
    }
}