Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read table from PDF using itextsharp?

Tags:

pdf

itext

I am having an problem with reading a table from pdf file. It's a very simple pdf file with some text and a table. The tool i am using is itextsharp. I know there is no table concept in PDF. After some googling, someone said it might be possible to achieve that using itextsharp + custom ITextExtractionStrategy. But I have no idea how to start it. Can someone please give me some hints? or a small piece of sample code?

Cheers

like image 452
Victor Avatar asked Mar 28 '13 10:03

Victor


People also ask

What is Itextsharp used for?

Itextsharp is an advanced tool library which is used for creating complex pdf repors. itext is used by different techonologies -- Android , . NET, Java and GAE developer use it to enhance their applications with PDF functionality.

Is Itextsharp free?

This program is free software; you can redistribute it and/or modify it under the terms of the GNU Affero General Public License version 3 as published by the Free Software Foundation with the addition of the following permission added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK IN ...


1 Answers

This code is for reading a table content. all the values are enclosed by ()Tj, so we look for all the values, you can do anything then with the string resulst.

    string _filePath = @"~\MyPDF.pdf";
    public List<String> Read()
    {
        var pdfReader = new PdfReader(_filePath);
        var pages = new List<String>();

        for (int i = 0; i < pdfReader.NumberOfPages; i++)
        {
            string textFromPage = Encoding.UTF8.GetString(Encoding.Convert(Encoding.Default, Encoding.UTF8, pdfReader.GetPageContent(i + 1)));

            pages.Add(GetDataConvertedData(textFromPage));
        }

        return pages;
    }

    string GetDataConvertedData(string textFromPage)
    {
        var texts = textFromPage.Split(new[] { "\n" }, StringSplitOptions.None)
                                .Where(text => text.Contains("Tj")).ToList();

        return texts.Aggregate(string.Empty, (current, t) => current + 
                   t.TrimStart('(')
                    .TrimEnd('j')
                    .TrimEnd('T')
                    .TrimEnd(')'));
    }
like image 169
gustavo.a.hansen Avatar answered Sep 28 '22 08:09

gustavo.a.hansen