使用iTextsharp从现有Pdf中删除元数据

时间:2012-02-01 14:06:08

标签: c# pdf metadata itextsharp

我创建了一个pdf并在其中添加了元数据,并且还使用了iTextsharp库对其进行了加密。 现在我想从pdf中删除加密。我使用iTextSharp成功完成了此操作,但无法删除我添加的元数据。 任何人都可以请我如何删除元数据。迫切需要。

感谢。

1 个答案:

答案 0 :(得分:0)

删除元数据时,最简单的方法是直接使用PdfReader对象。完成后,您可以将其写回磁盘。下面的代码是一个完整的C#2010 WinForms应用程序,目标是iTextSharp 5.1.2.0。它首先使用一些元数据创建PDF,然后使用PdfReader修改PDF的内存中版本,最后将更改写入磁盘。请参阅代码以获取其他评论。

using System;
using System.Collections.Generic;
using System.IO;
using System.Windows.Forms;
using iTextSharp.text;
using iTextSharp.text.pdf;

namespace WindowsFormsApplication1 {
    public partial class Form1 : Form {
        public Form1() {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e) {
            //File with meta data added
            string InputFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Test.pdf");
            //File with meta data removed
            string OutputFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Output.pdf");

            //Create a file with meta data, nothing special here
            using (FileStream FS = new FileStream(InputFile, FileMode.Create, FileAccess.Write, FileShare.None)) {
                using (Document Doc = new Document(PageSize.LETTER)) {
                    using (PdfWriter writer = PdfWriter.GetInstance(Doc, FS)) {
                        Doc.Open();
                        Doc.Add(new Paragraph("Test"));
                        //Add a standard header
                        Doc.AddTitle("This is a test");
                        //Add a custom header
                        Doc.AddHeader("Test Header", "This is also a test");
                        Doc.Close();
                    }
                }
            }

            //Read our newly created file
            PdfReader R = new PdfReader(InputFile);
            //Loop through each piece of meta data and remove it
            foreach (KeyValuePair<string, string> KV in R.Info) {
                R.Info.Remove(KV.Key);
            }

            //The code above modifies an in-memory representation of the PDF, we need to write these changes to disk now
            using (FileStream FS = new FileStream(OutputFile, FileMode.Create, FileAccess.Write, FileShare.None)) {
                using (Document Doc = new Document()) {
                    //Use the PdfCopy object to copy each page
                    using (PdfCopy writer = new PdfCopy(Doc, FS)) {
                        Doc.Open();
                        //Loop through each page
                        for (int i = 1; i <= R.NumberOfPages; i++) {
                            //Add it to the new document
                            writer.AddPage(writer.GetImportedPage(R, i));
                        }
                        Doc.Close();
                    }
                }
            }

            this.Close();
        }
    }
}