10

I have a big number pdf documents with xml files attached to them. I would like to extract those attached xml files and read them. How can I do this programatically using .net?

1
  • Great question, it is very help full but , can i extract the attachments from pdf file using javascript or jquery Jun 29, 2016 at 6:50

5 Answers 5

9

iTextSharp is also quite capable of extracting attachments... Though you might have to use the low level objects to do so.

There are two ways to embed files in a PDF:

  1. In a File Annotation
  2. At the document level "EmbeddedFiles".

Once you have a file specification dictionary from either source, the file itself will be a stream within the dictionary labeled "EF" (embedded file).

So to list all the files at the document level, one would write code (in Java) as such:

Map<String, byte[]> files = new HashMap<String,byte[]>();

PdfReader reader = new PdfReader(pdfPath);
PdfDictionary root = reader.getCatalog();
PdfDictionary names = root.getAsDict(PdfName.NAMES); // may be null
PdfDictionary embeddedFilesDict = names.getAsDict(PdfName.EMBEDDEDFILES); //may be null
PdfArray embeddedFiles = embeddedFilesDict.getAsArray(PdfName.NAMES); // may be null

int len = embeddedFiles.size();
for (int i = 0; i < len; i += 2) {
  PdfString name = embeddedFiles.getAsString(i); // should always be present
  PdfDictionary fileSpec = embeddedFiles.getAsDict(i+1); // ditto

  PdfDictionary streams = fileSpec.getAsDict(PdfName.EF);
  PRStream stream = null;

  if (streams.contains(PdfName.UF))
    stream = (PRStream)streams.getAsStream(PdfName.UF);
  else
    stream = (PRStream)streams.getAsStream(PdfName.F); // Default stream for backwards compatibility

  if (stream != null) {
    files.put( name.toUnicodeString(), PdfReader.getStreamBytes((PRStream)stream));
  }
}
5
  • thanks for the suggestion. I will try this out. +1 for the code sample.
    – gyurisc
    Jun 14, 2011 at 9:36
  • I have trouble with this line PdfArray embeddedFiles = names.getAsDictionary(PdfName.EMBEDDEDFILES); The compiler says that it cannot convert a PdfDictionary to PdfArray
    – gyurisc
    Jun 15, 2011 at 9:08
  • Oops. That's what happens when you write code in a browser. It should be calling getAsArray(). Jun 15, 2011 at 15:56
  • 1
    I'm not so sure of this solution, at least as of the time of my comment. EF cannot be accessed directly as a PdfStream. Rather it should be accessed as a dictionary, then accessing one of the streams within that as seen in the solution at the end of my comment. Also note the use of PdfReader.getStreamBytes(PRStream) (all credit for this to @Robert Lane). A simple call of getBytes() on the returned stream will return null. Please see the following solution. PdfReader.getStreamBytes((PRStream) fileSpec.getAsDict(PdfName.EF).getAsStream(PdfName.F)) [or PdfName.UF]. Jul 25, 2018 at 9:26
  • Also, the first item of every pair is a PdfString, not a PdfName which is used to indicate a type of pairing in a PdfDictionary. I'm just being thorough because posts on iText are few and far between and I'm hoping to help whomever pops through from having to go through my same troubles haha Jul 25, 2018 at 9:37
6

This is an old question, nonetheless I think my alternative solution (using PDF Clown) may be of some interest as it's way much cleaner (and more complete, as it iterates both at document and page level) than the code fragments previously proposed:

using org.pdfclown.bytes;
using org.pdfclown.documents;
using org.pdfclown.documents.files;
using org.pdfclown.documents.interaction.annotations;
using org.pdfclown.objects;

using System;
using System.Collections.Generic;

void ExtractAttachments(string pdfPath)
{
  Dictionary<string, byte[]> attachments = new Dictionary<string, byte[]>();

  using(org.pdfclown.files.File file = new org.pdfclown.files.File(pdfPath))
  {
    Document document = file.Document;

    // 1. Embedded files (document level).
    foreach(KeyValuePair<PdfString,FileSpecification> entry in document.Names.EmbeddedFiles)
    {EvaluateDataFile(attachments, entry.Value);}

    // 2. File attachments (page level).
    foreach(Page page in document.Pages)
    {
      foreach(Annotation annotation in page.Annotations)
      {
        if(annotation is FileAttachment)
        {EvaluateDataFile(attachments, ((FileAttachment)annotation).DataFile);}
      }
    }
  }
}

void EvaluateDataFile(Dictionary<string, byte[]> attachments, FileSpecification dataFile)
{
  if(dataFile is FullFileSpecification)
  {
    EmbeddedFile embeddedFile = ((FullFileSpecification)dataFile).EmbeddedFile;
    if(embeddedFile != null)
    {attachments[dataFile.Path] = embeddedFile.Data.ToByteArray();}
  }
}

Note that you don't have to bother with null pointer exceptions as PDF Clown provides all the necessary abstraction and automation to ensure smooth model traversal.

PDF Clown is an LGPL 3 library, implemented both in Java and .NET platforms (I'm its lead developer): if you want to get it a try, I suggest you to check out its SVN repository on sourceforge.net as it keeps evolving.

2
  • Thanks for adding your solution. It is very usefull!
    – gyurisc
    Jan 4, 2013 at 8:27
  • even that is a very old querstion and answer this helped me today very much, thank u Dec 29, 2018 at 20:45
2

Look for ABCpdf-Library, very easy and fast in my opinion.

0
2

What I got working is slightly different then anything else I have seen online.

So, just in case, I thought I would post this here to help someone else. I had to go through many different iterations to figure out - the hard way - what I needed to get it to work.

I am merging two PDFs into a third PDF, where one of the first two PDFs may have file attachments that need to be carried over into the third PDF. I am working completely in streams with ASP.NET, C# 4.0, ITextSharp 5.1.2.0.

        // Extract Files from Submit PDF
        Dictionary<string, byte[]> files = new Dictionary<string, byte[]>();

        PdfDictionary names;
        PdfDictionary embeddedFiles;
        PdfArray fileSpecs;
        int eFLength = 0;


        names = writeReader.Catalog.GetAsDict(PdfName.NAMES); // may be null, writeReader is the PdfReader for a PDF input stream
        if (names != null)
        {
            embeddedFiles = names.GetAsDict(PdfName.EMBEDDEDFILES); //may be null
            if (embeddedFiles != null)
            {
                fileSpecs = embeddedFiles.GetAsArray(PdfName.NAMES); //may be null
                if (fileSpecs != null)
                {
                    eFLength = fileSpecs.Size;

                    for (int i = 0; i < eFLength; i++)
                    {
                        i++; //objects are in pairs and only want odd objects (1,3,5...)
                        PdfDictionary fileSpec = fileSpecs.GetAsDict(i); // may be null
                        if (fileSpec != null)
                        {
                            PdfDictionary refs = fileSpec.GetAsDict(PdfName.EF);
                            foreach (PdfName key in refs.Keys)
                            {
                                PRStream stream = (PRStream)PdfReader.GetPdfObject(refs.GetAsIndirectObject(key));

                                if (stream != null)
                                {
                                    files.Add(fileSpec.GetAsString(key).ToString(), PdfReader.GetStreamBytes(stream));
                                }
                            }
                        }
                    }
                }
            }
        }
1
  • This solution worked for me! Mark Storer's solution is incorrect, at least as of the time of this posting. EF cannot be accessed directly as a PdfStream. That much I knew. However, when attempting to access the data using fileSpec.getAsDict(PdfName.EF).getAsStream(PdfName.F).getBytes(), all I would get is null. The key to your solution, at least for me, was PdfReader.getStreamBytes(PRStream), which yielded PdfReader.getStreamBytes(fileSpec.getAsDict(PdfName.EF).getAsStream(PdfName.F)), something I never would have guessed myself by experimenting. Jul 25, 2018 at 9:29
1

You may try Aspose.Pdf.Kit for .NET. The PdfExtractor class allows you to extract attachments with the help of two methods: ExtractAttachment and GetAttachment. Please see an example of attachment extraction.

Disclosure: I work as developer evangelist at Aspose.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.