Search code examples
c#.netpdfextractabcpdf

How to use the ABCPdf.NET to extract texts from all pages of a PDF file?


How to use the ABCPdf.NET tool to extract the content texts from a PDF file?

I tried the GetText method but doesn't extract the contents:

var doc = new Doc();    

        var url = @".../FileName.pdf";

        doc.Read(url);

        string xmlContents = doc.GetText("Text");
        Response.Write(xmlContents);
        doc.Clear();
        doc.Dispose();

My pdf has almost 1000 words but the GetText only returns 4-5 words. I realized it returns only the texts of the first page.

So the question should be "how to extract the text from all pages of a pdf file?" -(changed the Title to make it clearer).

Thanks,


Solution

  • For your benefit, yes you!

     public string ExtractTextsFromAllPages(string pdfFileName)
        {
            var sb = new StringBuilder();
    
            using (var doc = new Doc())
            {
                doc.Read(pdfFileName);
    
                for (var currentPageNumber = 1; currentPageNumber <= doc.PageCount; currentPageNumber++)
                {
                    doc.PageNumber = currentPageNumber;
                    sb.Append(doc.GetText("Text"));
                }
            }
    
            return sb.ToString();
        }
    

    if you don't have the url but have the bytes, then:

    public string ExtractTextsFromAllPages(Byte[] pdfBytes)
        {
            var sb = new StringBuilder();
    
            using (var doc = new Doc())
            {
                doc.Read(pdfBytes);
    
                for (var currentPageNumber = 1; currentPageNumber <= doc.PageCount; currentPageNumber++)
                {
                    doc.PageNumber = currentPageNumber;
                    sb.Append(doc.GetText("Text"));
                }
            }
    
            return sb.ToString();
        }