问题
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