iTextSharp – 如何打开/读取/提取文件附件?

我有一些PDF都带有两个带有静态名称的附加文件。 我想使用iTextSharp将这些文件解压缩到临时目录,以便我可以进一步使用它们。 我尝试按照本教程进行操作,但是当iTextSharp.text.pdf.PdfReader没有getCatalog()方法时,我遇到了问题,如下面的示例所示。

关于如何提取附件的任何建议? 让我们简单地说PDF文档位于“C:\ test.pdf”,两个附件存储为“attach1.xml”和“attach2.xml”。

我最终找到了一种方法 – 虽然不是完全以编程方式。 我包含了一个名为“pdftk.exe”的二进制文件,它是PDF ToolKit,它具有提取附件的命令行选项。

为了澄清,我添加了pdftk.exe,然后通过Process.Start("./pdftk", "contains_attachments.pdf unpack_files output \"C:\\output_directory\"")调用它。 请注意,pdftk不会输出到带有反斜杠的文件夹。 你可以在这里找到pdftk: http ://www.accesspdf.com/pdftk/

将.exe文件添加到项目后,需要将其属性设置为“始终复制”或“如果更新则复制”。

我找到了这个解决方案 我不知道这是不是最好的方式,但是,它有效!

 protected void btnTransfer_Click(object sender, EventArgs e) { PdfReader reader = new PdfReader(FileUpload1.FileContent); List lstAtt = GetAttachments(reader); reader.Close(); } private class FileContent { public string Name { get; set; } public byte[] Content { get; set; } } private List GetAttachments(PdfReader reader) { #region Variables PdfDictionary catalog = null; PdfDictionary documentNames = null; PdfDictionary embeddedFiles = null; PdfDictionary fileArray = null; PdfDictionary file = null; PRStream stream = null; FileContent fContent = null; List lstAtt = null; #endregion // Obtengo el conjunto de Diccionarios del PDF. catalog = reader.Catalog; // Variable que contiene la lista de archivos adjuntos. lstAtt = new List(); // Obtengo documento documentNames = (PdfDictionary)PdfReader.GetPdfObject(catalog.Get(PdfName.NAMES)); if (documentNames != null) { // Obtengo diccionario de objetos embebidos embeddedFiles = (PdfDictionary)PdfReader.GetPdfObject(documentNames.Get(PdfName.EMBEDDEDFILES)); if (embeddedFiles != null) { // Obtengo lista de documentos del Diccionario de objetos embebidos PdfArray filespecs = embeddedFiles.GetAsArray(PdfName.NAMES); // Cada archivo posee 2 posiciones en el array for (int i = 0; i < filespecs.Size; i++) { // Como posee 2 posiciones por archivo, hago "i++" i++; fileArray = filespecs.GetAsDict(i); // Obtengo diccionario del adjunto file = fileArray.GetAsDict(PdfName.EF); foreach (PdfName key in file.Keys) { stream = (PRStream)PdfReader.GetPdfObject(file.GetAsIndirectObject(key)); fContent = new FileContent(); // Nombre del Archivo. fContent.Name = fileArray.GetAsString(key).ToString(); // Array de bytes del Contenido del Archivo. fContent.Content = PdfReader.GetStreamBytes(stream); lstAtt.Add(fContent); } } } } // Y al fin, devuelvo una lista de adjuntos del PDF - podrían haberlo echo un poco mas facil :@ return lstAtt; }