2010-06-09 84 views
1

我有一些PDF全部包含兩個帶有靜態名稱的附加文件。我想使用iTextSharp將這些文件提取到臨時目錄,以便我可以進一步處理它們。我試着按照教程here,但當iTextSharp.text.pdf.PdfReader沒有getCatalog()方法時,我遇到了問題,如下面的示例所示。iTextSharp - 如何打開/讀取/提取文件附件?

有關如何提取附件的任何建議?讓我們簡單地說PDF文檔在「C:\ test.pdf」,兩個附件存儲爲「attach1.xml」和「attach2.xml」。

回答

0

我最終找到了一種方法來做到這一點 - 雖然不完全是編程方式。我包含一個名爲「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文件添加到項目後,需要將其屬性設置爲「始終複製」或「如果新建複製」。

0

我找到了這個解決方案。我不知道這是否是最好的方式,但它工作!

protected void btnTransfer_Click(object sender, EventArgs e) 
{ 
    PdfReader reader = new PdfReader(FileUpload1.FileContent); 
    List<FileContent> lstAtt = GetAttachments(reader); 
    reader.Close(); 
} 

private class FileContent 
{ 
    public string Name { get; set; } 

    public byte[] Content { get; set; } 
} 

private List<FileContent> 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<FileContent> lstAtt = null; 

    #endregion 

    // Obtengo el conjunto de Diccionarios del PDF. 
    catalog = reader.Catalog; 

    // Variable que contiene la lista de archivos adjuntos. 
    lstAtt = new List<FileContent>(); 

    // 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; 
} 
+0

你可以把JavaScript的代碼放在同一個功能嗎? – 2016-06-30 11:34:21