我正在使用iText进行pdf创建和加密

时间:2016-10-21 18:38:20

标签: c# itext

                    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)我不希望加密元数据,但它仍然加密元素,如标题,主题,Auther,关键字信息..

以上代码中缺少任何内容。

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

1 个答案:

答案 0 :(得分:0)

您对DO_NOT_ENCRYPT_METADATA的解释是错误的。您认为此设置不会加密信息字典。这不是那个设置的意思。该设置与XMP流有关。 XMP代表XML元数据平台,它是作为XML流存储在PDF(或其他文件,如图像)内的元数据。当我查看您的代码时,我发现您没有创建XMP流。请参阅ChangeMetadata示例。

此外,您应该知道并非所有类型的加密都支持DO_NOT_ENCRYPT_METADATA。例如,40位标准加密应忽略该设置(但我发现您使用的是128位标准加密,因此应该没问题。)