我使用iText创建和加密pdf
本文关键字:加密 pdf 创建 iText | 更新日期: 2023-09-27 18:14:20
string inputfile = "input file path";
string outfile = "outfile file path";
using (Stream output = new FileStream(outfile, FileMode.Create, FileAccess.Write, FileShare.None))
{
PdfReader reader = new PdfReader(inputfile);
Dictionary<string, string> newInfo = new Dictionary<string, string>();
newInfo.Add("Title", "Title");
newInfo.Add("Subject", "Subject");
newInfo.Add("Keywords", "Keywords");
newInfo.Add("Creator", "Creator");
newInfo.Add("Author", "Author");
newInfo.Add("CustomInfo", "CustomeInformationCanStoreHere");
PdfEncryptor.Encrypt(reader,output,true,"*****","*****",PdfWriter.DO_NOT_ENCRYPT_METADATA, newInfo);
}
我已经加密PDF文件使用上述代码(密码和设置选项为PdfWriter.DO_NOT_ENCRYPT_METADATA)
作为选项建议(DO_NOT_ENCRYPT_METADATA)我不希望元数据被加密,但它仍然加密元数据,如标题,主题,作者,关键词信息..
上面的代码有什么遗漏吗?
public void manipulatePdf(string source, string destination) {
PdfReader reader = new PdfReader(source);
Stream output = new FileStream(destination, FileMode.Create, FileAccess.Write, FileShare.None);
PdfStamper stamper = new PdfStamper(reader, output);
Dictionary<string, string> newInfo = new Dictionary<string, string>();
newInfo.Add("Title", "Title");
newInfo.Add("Subject", "Subject");
newInfo.Add("Keywords", "Keywords");
newInfo.Add("Creator", "Creator");
newInfo.Add("Author", "Author");
newInfo.Add("CustomInfo", "CustomeInformationCanStoreHere");
stamper.MoreInfo = newInfo;
MemoryStream outStream = new MemoryStream();
XmpWriter xmpw = new XmpWriter(outStream,newInfo);
stamper.XmpMetadata = outStream.ToArray();
byte[] password = Encoding.ASCII.GetBytes("password");
stamper.SetEncryption(password, password, PdfWriter.ALLOW_PRINTING, PdfWriter.ENCRYPTION_AES_128 | PdfWriter.DO_NOT_ENCRYPT_METADATA);
xmpw.Close();
stamper.Close();
reader.Close();
}
你对DO_NOT_ENCRYPT_METADATA
的解释是错误的。您认为此设置不会加密信息字典。这不是那个设定的目的。这个设置是关于XMP流的。XMP代表XML元数据平台,它是作为XML流存储在PDF(或图像等其他文件)中的元数据。当我查看您的代码时,我发现您没有创建XMP流。参见ChangeMetadata示例。
此外,您应该知道并非每种类型的加密都支持DO_NOT_ENCRYPT_METADATA
。例如,40位标准加密应该忽略该设置(但我看到您正在使用128位标准加密,因此应该没问题)。