iTextSharp - how to open/read/extract a file attac

2020-07-31 04:36发布

问题:

I have some PDF's all with two attached files with static names. I would like to use iTextSharp to extract these files to a temp directory so that I can work with them further. I tried following the tutorial here but I ran into problems when the iTextSharp.text.pdf.PdfReader didn't have a getCatalog() method as shown in the bottom example.

Any advice on how I can extract the attachments? Let's just say for ease that the PDF document is at "C:\test.pdf" and the two attachments are stored as "attach1.xml" and "attach2.xml".

回答1:

I found this solution. I don't know if it's the best way, but, it work!!

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


回答2:

I ended up finding a way to do this - although not exactly programmatically. I included a binary called "pdftk.exe" which is PDF ToolKit, which has command-line options to extract the attachments.

To clarify, I added pdftk.exe, then called it via Process.Start("./pdftk", "contains_attachments.pdf unpack_files output \"C:\\output_directory\""). Note that pdftk will not output to a folder with a trailing backslash. You can find pdftk here: http://www.accesspdf.com/pdftk/

After adding the .exe file to the project, you need to set its properties to "Copy always" or "Copy if newer".