scratchpad
ateague
<p>At $WORK I use <b>pdftohtml</b> with the following command line: <code>pdftohtml.exe -xml -stdout -zoom 1.4 [PDF FILE]</code></p>
<p>This will rip out all the text elements into an XML file with attributes for the font, x/y position on the page and text length.
(<code>-zoom 1.4</code> makes the positioning units 100 dpi, <code>-stdout</code> streams the output to STDOUT instead of writing it to a file).<p>
<p>Here is an example of what I typically work with:</p>
<code><?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE pdf2xml SYSTEM "pdf2xml.dtd">
<pdf2xml>
<page number="1" position="absolute" top="0" left="0" height="1100" width="850">
<fontspec id="0" size="17" family="Times" color="#000000"/>
<text top="103" left="115" width="602" height="18" font="0">XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX</text>
<text top="120" left="115" width="602" height="18" font="0">XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX</text>
<text top="186" left="115" width="103" height="18" font="0">ROUTE TO:</text>
<text top="186" left="265" width="107" height="17" font="0">Audit Billing</text>
<text top="220" left="115" width="128" height="18" font="0">SORT GROUP:</text>
<text top="220" left="265" width="152" height="18" font="0">Invoice Sort Group</text>
<text top="286" left="115" width="260" height="18" font="0">OH_GOD_IT_BURNS 2013-12-20</text>
<text top="286" left="415" width="71" height="18" font="0">23:53:04</text>
<text top="286" left="545" width="108" height="18" font="0">FOOBAR</text>
<text top="320" left="115" width="602" height="18" font="0">XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX</text>
<text top="336" left="115" width="602" height="18" font="0">XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX</text>
</page>
/<pdf2html></code>
<p>I can then use XML::Twig with XPath expressions to pull the exact xml nodes I want:</p>
<code>open (my $XML, "-|", "pdftohtml.exe -xml -zoom 1.4 -stdout $PDF_FILE") or die "$!\n$^E";
# We are only interested in the text for the "ROUTE TO:" and "SORT GROUP:" sections
# Set the twig_handlers to extract the <text> nodes of interest; all other nodes will be ignored
# XPath queries provide an extra 1/20 inch padding on all sides to take font and rendering variations into account
my $t = XML::Twig->new(
twig_handlers => {
'//text[(@top >= 180 and @top <= 190) and (@left >= 100 and @left <= 111)]' => \&RouteTo,
'//text[(@top >= 215 and @top <= 225) and (@left >= 260 and @left <= 270)]' => \&InvoiceSort,
},
comments => 'drop', # remove any comments
empty_tags => 'normal',# empty tags = <tag/>
);
$t->parse($XML);
$t->purge;
close $XML;</code>