C# using iTextSharptext;using iTextSharptextpdf;解密PDF文件
要解密PDF文件,可以使用iTextSharp库中的PdfReader类和PdfStamper类来实现。以下是一个示例代码,演示了如何解密PDF文件:
using System;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
public class PdfDecryptionExample
{
public static void Main(string[] args)
{
string inputFile = "encrypted.pdf";
string outputFile = "decrypted.pdf";
string password = "password";
using (FileStream fs = new FileStream(inputFile, FileMode.Open, FileAccess.Read))
{
PdfReader reader = new PdfReader(fs, Encoding.ASCII.GetBytes(password));
// Check if the PDF is encrypted
if (!reader.IsEncrypted())
{
Console.WriteLine("PDF is not encrypted.");
return;
}
// Create an empty output PDF file
using (FileStream output = new FileStream(outputFile, FileMode.Create, FileAccess.Write))
{
PdfStamper stamper = new PdfStamper(reader, output);
// Clear the encryption
stamper.SetEncryption(null, null, 0, false);
stamper.Close();
}
reader.Close();
}
Console.WriteLine("PDF decryption completed.");
}
}
在上述代码中,需要将inputFile变量设置为要解密的PDF文件的路径,outputFile变量设置为解密后的PDF文件的路径,password变量设置为加密PDF文件时使用的密码。
代码首先打开加密的PDF文件,并使用密码初始化PdfReader对象。然后,使用PdfStamper对象将解密后的PDF写入输出文件中。在设置PdfStamper的时候,使用stamper.SetEncryption(null, null, 0, false);来清除加密。
最后,关闭PdfStamper和PdfReader对象,并输出解密完成的消息。
请注意,为了运行此代码,需要将iTextSharp库添加到项目中,并在代码中添加对iTextSharp的命名空间的引用。
原文地址: https://www.cveoy.top/t/topic/i9zY 著作权归作者所有。请勿转载和采集!