Extracting Tables from PDFs in Javascript with PDF.js

A common and difficult problem acquiring data is extracting tables from a PDF. Previously, I described how to extract the text from a PDF with PDF.js, a PDF rendering library made by Mozilla Labs.

churches

The rendering process requires an HTML canvas object, and then draws each object (character, line, rectangle, etc) on it. The easiest way to get a list of these is to to intercept all the calls PDF.js makes to drawing functions on the canvas object. (see “Self Modifying Javascripts” for a similar technique). The “set” method below adds a wrapper closure to each function, which logs the call.

function replace(ctx, key) {
  var val = ctx[key];
   if (typeof(val) == "function") {
     ctx[key] = function() {
      var args = Array.prototype.slice.call(arguments);
      console.log("Called " + key + "(" + args.join(",") + ")");
      return val.apply(ctx, args);
    } 
  }
}

for (var k in context) {
  replace(context, k);
} 

var renderContext = {
  canvasContext: context,
  viewport: viewport
};

page.render(renderContext);

This lets us see a series of calls:

Called transform(1,0,0,1,150.42,539.67)
Called translate(0,0)
Called scale(1,-1)
Called scale(0.752625,0.752625)
Called measureText(C)
Called save()
Called scale(0.9701818181818181,1)
Called fillText(C,0,0)
Called restore()
Called restore()
Called save()
Called transform(1,0,0,1,150.42,539.6

We can easily retrieve the text by noting the first argument to each “fillText” call:

"Congregations Ranked by Growth and Decline in Membership and Worship Attendance, 2006 to 2011Philadelphia Presbytery - Table 16Net 
Membership ChangeNet Worship ChangePercent ChangePercent ChangeWorship
 2006Worship 2011Membership 2006Membership 2011Abington, Abington-
143(74)-13.18%(57)0(15)0.00%(22)NumberRank3003001,085942Anchor, 
Wrightstown0(23)0.00%(27)-12(25)-21.43%(52)NumberRank56449797Arch 
Street, Philadelphia-117(71)-68.42%(117)27(5)90.00%
(2)NumberRank305717154Aston, Aston3(21)3.53%(22)-5(19)-9.43%
(31)NumberRank53488588BeaconNo reportboth yearsNo reportboth 
yearsNumberRankBensalem, Bensalem-23(39)-13.94%(62)-28(36)-28.57%
(64)NumberRank9870165142Berean, Philadelphia106(4)44.92%(4)No 
reportboth yearsNumberRank00236342Bethany Collegiate, Havertown-
188(76)-42.44%(110)43(3)21.29%(7)NumberRank202245443255Bethel, 
Philadelphia-13(33)-13.68%(60)-27(35)-35.06%
(71)NumberRank77509582Bethesda, Philadelphia9(18)5.56%(18)No reportboth 
yearsNumberRank1150162171Beverly Hills, Upper Darby-3(26)-3.03%
(32)-11(24)-20.00%(48)NumberRank55449996Bridesburg, 
Philadelphia0(23)0.00%(27)No reportboth yearsNumberRank004444Bristol, 
BristolNo reportboth yearsNo reportboth yearsNumberRankPage 1 of 
10Report prepared by Research Services, Presbyterian Church (U.S.A.)1-
800-728-7228, ext #204006-Oct-12"

Notably, this doesn’t track line endings, and not all the characters are recorded in the expected order (the first line is rendered after the second).

The calls to transform, translate, and scale control where text is placed. The fillText method also takes an (x, y) parameter set that moves the individual letters between words. The exact position is a combination of successive operations, which are modeled as a stack of matrix operations.

Thankfully, PDF.js tracks the output of these operations as it renders, so we don’t have to recalculate it.

Thus, we can make a method that records the letters and their real positions. This method takes the internal context object, the type of state transition, and the arguments to the transition. This method is then called from the ‘record’ function listed above.

var chars = [];
var cur = {};

function record(ctx, state, args) {
  if (state === 'fillText') {
    var c = args[0];
    cur.c = c;
    cur.x = ctx._transformMatrix[4] + args[1];
    cur.y = ctx._transformMatrix[5] + args[2];

    chars[chars.length] = cur;
    cur = {};
  } 
}

These results can be sorted by position (x and y). The sort method arranges letters by position – if they are shifted up or down a small amount, they are considered to be on one line.

chars.sort(
  function(a, b) {
    var dx = b.x - a.x;
    var dy = b.y - a.y;

    if (Math.abs(dy) < 0.5) {
      return dx * -1;
    } else {
      return dy * -1;
    }
  }
);

This presents several difficulties: this doesn’t detect right-to-left text, and it’s becoming clear that we’re going to have a hard time knowing when you’re in a table and when we aren’t.

To do this, we define a function which can transform the array of letters and positions into a CSV style output. This tracks from letter to letter – if it sees a “large” change in y, it makes a new line. If it sees a “large” change in x, it treats it as a new column.

The real challenge is defining “large” which for my test PDF were around 15 and 20, for dx and dy.

function getText(marks, ex, ey, v) {
  var x = marks[0].x;
  var y = marks[0].y;

  var txt = '';
  for (var i = 0; i < marks.length; i++) {
    var c = marks[i];
    var dx = c.x - x;
    var dy = c.y - y;

    if (Math.abs(dy) > ey) {
      txt += "\"\n\"";
      if (marks[i+1]) {
        // line feed - start from position of next line
        x = marks[i+1].x;
      }
    }

    if (Math.abs(dx) > ex) {
      txt += "\",\"";
    }

    if (v) {
      console.log(dx + ", " + dy);
    }
   
    txt += c.c;

    x = c.x;
    y = c.y;  
  }
 
  return txt;
}

This algorithm doesn’t handle newlines in rows, and oddly, the columns don’t come out in the right order, but they appear to be consistently out of order. Line with large spaces (e.g. an em-dash) are detected as having multiple columns, but this can be cleaned up later – here is some sample output.

You can see an example below, and the final source is available on github.

Congregations Ranked by Growth and Decline in M","embership and W","orship Attendance, 2006 to 2011"
"","Philadelphia Presbytery"," - Table 16"
"","Net ","Membership ","Change"
"","Net Worship ","Change","Percent ","Change","Percent ","Change","Worship"," 2006","Worship"," 2011","Membership"," 2006","Membership"," 2011"
"","Abington, Abington","-143","(74)","-13.18%(57)","0","(15)","0.00%(22)","Number","Rank","300","300","1,085","942"
"","Anchor, Wrightstown","0","(23)","0.00%(27)","-12","(25)","-21.43%(52)","Number","Rank","56","44","97","97"
"","Arch Street, Philadelphia","-117","(71)","-68.42%","(117)","27(5)","90.00%(2)","Number","Rank","30","57","171","54"
"","Aston, Aston","3","(21)","3.53%(22)","-5","(19)","-9.43%(31)","Number","Rank","53","48","85","88"
"","Beacon","No report","both years","No report","both years","Number","Rank"
"","Bensalem, Bensalem","-23","(39)","-13.94%(62)","-28","(36)","-28.57%(64)","Number","Rank","98","70","165","142"
"","Berean, Philadelphia","106(4)","44.92%(4)","No report","both years","Number","Rank","0","0","236","342"
"","Bethany Collegiate, Havertown","-188","(76)","-42.44%","(110)","43(3)","21.29%(7)","Number","Rank","202","245","443","255"
"","Bethel, Philadelphia","-13","(33)","-13.68%(60)","-27","(35)","-35.06%(71)","Number","Rank","77","50","95","82"
"","Bethesda, Philadelphia","9","(18)","5.56%(18)","No report","both years","Number","Rank","115","0","162","171"
"","Beverly Hills, Upper Darby","-3","(26)","-3.03%(32)","-11","(24)","-20.00%(48)","Number","Rank","55","44","99","96"
"","Bridesburg, Philadelphia","0","(23)","0.00%(27)","No report","both years","Number","Rank","0","0","44","44"
"","Bristol, Bristol","No report","both years","No report","both years","Number","Rank"
"","Page 1 of 10","Report prepared by Research Services, Presbyterian Church (U.S.A.)","1-800-728-7228, ext #2040","06-Oct-12"