18
votes

We are using iTextSharp with a C# WinForms application to parse a PDF file. Using iTextSharp, I can easily extract the text data from the PDF file. Suppose a PDF file contains an image surrounded by two lines of text. In this case, I could not extract the information about the image.

My requirement is:

  1. Get structural elements of the PDF file
  2. Process whether each is of type text, image, table or other

For example, the structural elements are similar to the following:

text :paragraph1
text :paragraph2
Image:Image
text :paragraph3
Table:table info
text :Paragraph4

If I can obtain information in a format like this, I can easily understand the text, image, table, header or footer information.

So, is it possible to get this kind of information using iTextSharp? If yes, please enlighten me on this. Otherwise, could you please suggest some other tools capable of meeting this requirement?

Thanks to all,

Saravanan

1
possible duplicate of stackoverflow.com/questions/5945244/…emd
Is this specific to c# 4.0?Ryan Gates
@ Ryan Gates : Yes...It's for C#4.0Saravanan
@emd, that question is about how to resolve an image-extraction-related runtime error, whereas this is about how to get all of the elements in a PDF file in vertical order.Sam

1 Answers

5
votes

I used to have this kind of need a while ago. I used this function (from Extract images using iTextSharp) :

private static PdfObject FindImageInPDFDictionary(PdfDictionary pg)
{
    PdfDictionary res =
        (PdfDictionary)PdfReader.GetPdfObject(pg.Get(PdfName.RESOURCES));


    PdfDictionary xobj =
      (PdfDictionary)PdfReader.GetPdfObject(res.Get(PdfName.XOBJECT));
    if (xobj != null)
    {
        foreach (PdfName name in xobj.Keys)
        {

            PdfObject obj = xobj.Get(name);
            if (obj.IsIndirect())
            {
                PdfDictionary tg = (PdfDictionary)PdfReader.GetPdfObject(obj);

                PdfName type =
                  (PdfName)PdfReader.GetPdfObject(tg.Get(PdfName.SUBTYPE));

                //image at the root of the pdf
                if (PdfName.IMAGE.Equals(type))
                {
                    return obj;
                }// image inside a form
                else if (PdfName.FORM.Equals(type))
                {
                    return FindImageInPDFDictionary(tg);
                } //image inside a group
                else if (PdfName.GROUP.Equals(type))
                {
                    return FindImageInPDFDictionary(tg);
                }

            }
        }
    }

    return null;
}

As you can see in the foreach (PdfName name in xobj.Keys) statement, I think you can easily parse a whole PDF and treat every kind of data from it. But I'm not sure about the "verticality" part of your need.

Hope it could help you.