Click here to Skip to main content
15,880,037 members
Articles / Programming Languages / C++
Article

Code to extract plain text from a PDF file

Rate me:
Please Sign up or sign in to vote.
4.87/5 (74 votes)
21 Jun 20044 min read 830.2K   36.7K   175   152
Source code that shows how to decompress and extract text from PDF documents.

Introduction

PDF documents are commonly used and their content is usually compressed. This article shows a simple C code that can be used to extract plain text from the PDF file.

Why?

Adobe does allows you to submit PDF files and will extract the text or HTML and mail it back to you. But there are times when you need to extract the text yourself or do it inside an application. You may also want to apply special formatting (e.g., add tabs) so that the text can be easily imported into Excel for example (when your PDF document mostly contains tables that you need to port to Excel, which is how this code got developed).

There are several projects on "The Code Project" that show how to create PDF documents, but none that provide free code that shows how to extract text without using a commercial library. In the reader comments, a need was expressed for code just like what is being supplied here.

There are several libraries out there that read or create PDF file, but you have to register them for commercial use or sign various agreements. The code supplied here is very simple and basic, but it is entirely free. It only use the ZLIB library which is also free.

Basics

You can download documents such as PDFReference15_v5.pdf from here that explains some of the inners of PDF files. In short, each PDF file contains a number of objects. Each object may require one or more filters to decompress it and may also provide a stream of data. Text streams are usually compressed using the FlateDecode filter and may be uncompressed using code from the ZLIB (http://www.zlib.org/) library.

The data for each object can be found between "stream" and "endstream" sections. Once inflated, the data needs to be processed to extract the text. The data usually contains one or more text objects (starting with BT and ending with ET) with formatting instructions inside. You can learn a lot from the structure of PDF file by stepping through this application.

About Code

This single source code file contains very simple, very basic C code. It initially reads in the entire PDF file into one buffer and then repeatedly scans for "stream" and "endstream" sections. It does not check which filter should be applied and always assumes FlateDecode. (If it gets it wrong, usually no output is generated for that section of the file, so it is not a big issue). Once the data stream is inflated (uncompressed), it is processed. During the processing, the code searches for the BT and ET tokens that signify text objects. The contents of each is processed to extract the text and a guess is made as to whether tabs or new line characters are needed.

The code is far from complete or being any sort of general utility class, but it does demonstrate how you can extract the text yourself. It is enough to show you how and get you going.

The code is however fully functional, so when it is applied to a PDF document, it generally does a fair job of extracting the text. It has been tested on several PDF files.

This code is supplied as is, no warranties. Use at your own risk.

Using The Code

The download contains one C file. To use it, create a simple Windows 32 Console project and add the pdf.c file to the project. You also need to go here (bless them!) and download the free "zlib compiled DLL" zip file. Extract zdll.lib to your project directory and add it as a project dependency (link against it). Also put zlib1.dll in your project directory. Also put zconf.h and zlib.h in your project directory and add them to the project.

Now, step through the application and note that the input PDF and output text file names are hardwired at the start of the main method.

Future Enhancements

If there is enough interest, the author may consider uploading a release version with a Windows interface. The code is quite good for extracting data from tables in a form that can be readily imported into Excel, with the column preserved (because of the tabs that get added).

Code Snippets

Stream sections are located using initially:

C#
size_t streamstart = FindStringInBuffer (buffer, "stream", filelen);
size_t streamend = FindStringInBuffer (buffer, "endstream", filelen);

And then once the data portion is identified, it is inflated as follows:

C#
z_stream zstrm; ZeroMemory(&zstrm, sizeof(zstrm));
zstrm.avail_in = streamend - streamstart + 1;
zstrm.avail_out = outsize;
zstrm.next_in = (Bytef*)(buffer + streamstart);
zstrm.next_out = (Bytef*)output;
int rsti = inflateInit(&zstrm);
if (rsti == Z_OK)
{
  int rst2 = inflate (&zstrm, Z_FINISH);
  if (rst2 >= 0)
  {
    //Ok, got something, extract the text:
    size_t totout = zstrm.total_out;
    ProcessOutput(fileo, output, totout);
  }
}

The main work gets done in the ProcessOutput method which processes the uncompressed stream to extract text portion of any text object. It looks as follows:

C#
void ProcessOutput(FILE* file, char* output, size_t len)
{
  //Are we currently inside a text object?
  bool intextobject = false;
  //Is the next character literal 
  //(e.g. \\ to get a \ character or \( to get ( ):
  bool nextliteral = false;

  //() Bracket nesting level. Text appears inside ()
  int rbdepth = 0;

  //Keep previous chars to extract numbers etc.:
  char oc[oldchar];
  int j=0;
  for (j=0; j<oldchar; j++) oc[j]=' ';

  for (size_t i=0; i<len; i++)
  {
    char c = output[i];
    if (intextobject)
    {
      if (rbdepth==0 && seen2("TD", oc))
      {
        //Positioning.
        //See if a new line has to start or just a tab:
        float num = ExtractNumber(oc,oldchar-5);
        if (num>1.0)
        {
          fputc(0x0d, file);
          fputc(0x0a, file);
        }
        if (num<1.0)
        {
          fputc('\t', file);
        }
      }
      if (rbdepth==0 && seen2("ET", oc))
      {
        //End of a text object, also go to a new line.
        intextobject = false;
        fputc(0x0d, file);
        fputc(0x0a, file);
      }
      else if (c=='(' && rbdepth==0 && !nextliteral) 
      {
        //Start outputting text!
        rbdepth=1;
        //See if a space or tab (>1000) is called for by looking
        //at the number in front of (
        int num = ExtractNumber(oc,oldchar-1);
        if (num>0)
        {
          if (num>1000.0)
          {
            fputc('\t', file);
          }
          else if (num>100.0)
          {
            fputc(' ', file);
          }
        }
      }
      else if (c==')' && rbdepth==1 && !nextliteral) 
      {
        //Stop outputting text
        rbdepth=0;
      }
      else if (rbdepth==1) 
      {
        //Just a normal text character:
        if (c=='\\' && !nextliteral)
        {
          //Only print out next character 
          //no matter what. Do not interpret.
          nextliteral = true;
        }
        else
        {
          nextliteral = false;
          if ( ((c>=' ') && (c<='~')) || ((c>=128) && (c<255)) )
          {
            fputc(c, file);
          }
        }
      }
    }
    //Store the recent characters for 
    //when we have to go back for a number:
    for (j=0; j<oldchar-1; j++) oc[j]=oc[j+1];
      oc[oldchar-1]=c;
    if (!intextobject)
    {
      if (seen2("BT", oc))
      {
        //Start of a text object:
        intextobject = true;
      }
    }
  }
}

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
Canada Canada
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralRe: Trouble extracting newer docs Pin
ofoto28-Jan-05 21:20
ofoto28-Jan-05 21:20 
GeneralRe: Trouble extracting newer docs Pin
jdlw-200030-Jan-05 11:17
jdlw-200030-Jan-05 11:17 
GeneralRe: Trouble extracting newer docs Pin
Xiong Shijie27-Apr-05 3:26
Xiong Shijie27-Apr-05 3:26 
GeneralRe: Trouble extracting newer docs Pin
the_grip21-Jun-05 6:26
the_grip21-Jun-05 6:26 
GeneralRe: Trouble extracting newer docs Pin
brentoids22-Jun-05 7:23
brentoids22-Jun-05 7:23 
GeneralRe: Trouble extracting newer docs Pin
ykara8-Aug-05 12:29
ykara8-Aug-05 12:29 
GeneralRe: Trouble extracting newer docs Pin
Member 22369648-Oct-05 20:57
Member 22369648-Oct-05 20:57 
GeneralRe: Trouble extracting newer docs Pin
KongHL31-Jan-06 19:17
KongHL31-Jan-06 19:17 
Could you pls send the updated version to me also? Currently your code doesn't display accurately for all documents. Thank you very much!
My email is HL8476@hotmail.com I am really in need up the code...

-- modified at 1:20 Wednesday 1st February, 2006
Generalc# version of the pdf extractor Pin
Jagruti26-Dec-04 18:30
Jagruti26-Dec-04 18:30 
GeneralDo very well in English character, but change Chinese or Japanese character into blank Pin
kesmellon12-Dec-04 21:06
kesmellon12-Dec-04 21:06 
GeneralRe: Do very well in English character, but change Chinese or Japanese character into blank Pin
mfkzbq21-Dec-04 16:11
mfkzbq21-Dec-04 16:11 
Questionhow can i convert hindi pdf file to text file Pin
devendra kumar kushwaha25-Oct-04 1:16
devendra kumar kushwaha25-Oct-04 1:16 
AnswerRe: how can i convert hindi pdf file to text file Pin
Jagruti26-Dec-04 18:32
Jagruti26-Dec-04 18:32 
GeneralThis code don't work with some PDF Files Pin
Cheickna30-Aug-04 22:01
Cheickna30-Aug-04 22:01 
GeneralRe: This code don't work with some PDF Files Pin
SandeepBassi10-Sep-04 17:28
SandeepBassi10-Sep-04 17:28 
GeneralRe: This code don't work with some PDF Files Pin
Member 223696413-Sep-05 17:08
Member 223696413-Sep-05 17:08 
Generalautomate graph Pin
Oriocat6-Aug-04 7:13
Oriocat6-Aug-04 7:13 
GeneralManaged Version of PDF Text Extraction Pin
SandeepBassi2-Aug-04 20:43
SandeepBassi2-Aug-04 20:43 
GeneralRe: Managed Version of PDF Text Extraction Pin
Anonymous22-Dec-04 4:30
Anonymous22-Dec-04 4:30 
GeneralRe: Managed Version of PDF Text Extraction Pin
Jagruti26-Dec-04 18:25
Jagruti26-Dec-04 18:25 
GeneralRe: Managed Version of PDF Text Extraction Pin
Anonymous12-Jan-05 17:36
Anonymous12-Jan-05 17:36 
GeneralRe: Managed Version of PDF Text Extraction Pin
jmza11-Aug-05 11:15
jmza11-Aug-05 11:15 
GeneralRe: Managed Version of PDF Text Extraction Pin
nerdfarm5-Oct-05 13:41
nerdfarm5-Oct-05 13:41 
GeneralRe: Managed Version of PDF Text Extraction Pin
KongHL1-Feb-06 22:31
KongHL1-Feb-06 22:31 
GeneralManaged Version of PDF Text Extraction Pin
seeed19779-Feb-11 5:23
seeed19779-Feb-11 5:23 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.