1. <?php
  2. /*
  3. This program is free software; you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation; either version 2 of the License, or
  6. (at your option) any later version.
  7.  
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; if not, write to the Free Software
  14. Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  15.  
  16. This code is an improved version of what can be found at:
  17. http://www.webcheatsheet.com/php/reading_clean_text_from_pdf.php
  18.  
  19. AUTHOR:
  20. - Webcheatsheet.com (Original code)
  21. - Joeri Stegeman (joeri210 [at] yahoo [dot] com) (Class conversion and fixes/adjustments)
  22.  
  23. DESCRIPTION:
  24. This is a class to convert PDF files into ASCII text or so called PDF text extraction.
  25. It will ignore anything that is not addressed as text within the PDF and any layout.
  26. Currently supported filters are: ASCIIHexDecode, ASCII85Decode, FlateDecode
  27.  
  28. PURPOSE(S):
  29. Most likely for people that want their PDF to be searchable.
  30.  
  31. SYNTAX:
  32. include('class.pdf2text.php');
  33. $a = new PDF2Text();
  34. $a->setFilename('test.pdf');
  35. $a->decodePDF();
  36. echo $a->output();
  37.  
  38. ALTERNATIVES:
  39. Other excellent options to search within a PDF:
  40. - Apache PDFbox (http://pdfbox.apache.org/). An open source Java solution
  41. - pdflib TET (http://www.pdflib.com/products/tet/)
  42. - Online converter: http://snowtide.com/PDFTextStream
  43. */
  44.  
  45.  
  46. class PDF2Text {
  47.     // Some settings
  48.     var $multibyte = 2; // Use setUnicode(TRUE|FALSE)
  49.     var $convertquotes = ENT_QUOTES; // ENT_COMPAT (double-quotes), ENT_QUOTES (Both), ENT_NOQUOTES (None)
  50.    
  51.     // Variables
  52.     var $filename = '';
  53.     var $decodedtext = '';
  54.    
  55.     function setFilename($filename) {
  56.         // Reset
  57.         $this->decodedtext = '';
  58.         $this->filename = $filename;
  59.     }
  60.  
  61.     function output($echo = false) {
  62.         if($echo) echo $this->decodedtext;
  63.         else return $this->decodedtext;
  64.     }
  65.  
  66.     function setUnicode($input) {
  67.         // 4 for unicode. But 2 should work in most cases just fine
  68.         if($input == true) $this->multibyte = 4;
  69.         else $this->multibyte = 2;
  70.     }
  71.  
  72.     function decodePDF() {
  73.         // Read the data from pdf file
  74.         $infile = @file_get_contents($this->filename, FILE_BINARY);
  75.         if (empty($infile))
  76.             return "";
  77.    
  78.         // Get all text data.
  79.         $transformations = array();
  80.         $texts = array();
  81.    
  82.         // Get the list of all objects.
  83.         preg_match_all("#obj[\n|\r](.*)endobj[\n|\r]#ismU", $infile, $objects);
  84.         $objects = @$objects[1];
  85.    
  86.         // Select objects with streams.
  87.         for ($i = 0; $i < count($objects); $i++) {
  88.             $currentObject = $objects[$i];
  89.    
  90.             // Check if an object includes data stream.
  91.             if (preg_match("#stream[\n|\r](.*)endstream[\n|\r]#ismU", $currentObject, $stream)) {
  92.                 $stream = ltrim($stream[1]);
  93.    
  94.                 // Check object parameters and look for text data.
  95.                 $options = $this->getObjectOptions($currentObject);
  96.    
  97.                 if (!(empty($options["Length1"]) && empty($options["Type"]) && empty($options["Subtype"])))
  98.                     continue;
  99.    
  100.                 // Hack, length doesnt always seem to be correct
  101.                 unset($options["Length"]);
  102.    
  103.                 // So, we have text data. Decode it.
  104.                 $data = $this->getDecodedStream($stream, $options);  
  105.    
  106.                 if (strlen($data)) {
  107.                     if (preg_match_all("#BT[\n|\r](.*)ET[\n|\r]#ismU", $data, $textContainers)) {
  108.                         $textContainers = @$textContainers[1];
  109.                         $this->getDirtyTexts($texts, $textContainers);
  110.                     } else
  111.                         $this->getCharTransformations($transformations, $data);
  112.                 }
  113.             }
  114.         }
  115.    
  116.         // Analyze text blocks taking into account character transformations and return results.
  117.         $this->decodedtext = $this->getTextUsingTransformations($texts, $transformations);
  118.     }
  119.  
  120.  
  121.     function decodeAsciiHex($input) {
  122.         $output = "";
  123.    
  124.         $isOdd = true;
  125.         $isComment = false;
  126.    
  127.         for($i = 0, $codeHigh = -1; $i < strlen($input) && $input[$i] != '>'; $i++) {
  128.             $c = $input[$i];
  129.    
  130.             if($isComment) {
  131.                 if ($c == '\r' || $c == '\n')
  132.                     $isComment = false;
  133.                 continue;
  134.             }
  135.    
  136.             switch($c) {
  137.                 case '\0': case '\t': case '\r': case '\f': case '\n': case ' ': break;
  138.                 case '%':
  139.                     $isComment = true;
  140.                 break;
  141.    
  142.                 default:
  143.                     $code = hexdec($c);
  144.                     if($code === 0 && $c != '0')
  145.                         return "";
  146.    
  147.                     if($isOdd)
  148.                         $codeHigh = $code;
  149.                     else
  150.                         $output .= chr($codeHigh * 16 + $code);
  151.    
  152.                     $isOdd = !$isOdd;
  153.                 break;
  154.             }
  155.         }
  156.    
  157.         if($input[$i] != '>')
  158.             return "";
  159.    
  160.         if($isOdd)
  161.             $output .= chr($codeHigh * 16);
  162.    
  163.         return $output;
  164.     }
  165.    
  166.     function decodeAscii85($input) {
  167.         $output = "";
  168.    
  169.         $isComment = false;
  170.         $ords = array();
  171.        
  172.         for($i = 0, $state = 0; $i < strlen($input) && $input[$i] != '~'; $i++) {
  173.             $c = $input[$i];
  174.    
  175.             if($isComment) {
  176.                 if ($c == '\r' || $c == '\n')
  177.                     $isComment = false;
  178.                 continue;
  179.             }
  180.    
  181.             if ($c == '\0' || $c == '\t' || $c == '\r' || $c == '\f' || $c == '\n' || $c == ' ')
  182.                 continue;
  183.             if ($c == '%') {
  184.                 $isComment = true;
  185.                 continue;
  186.             }
  187.             if ($c == 'z' && $state === 0) {
  188.                 $output .= str_repeat(chr(0), 4);
  189.                 continue;
  190.             }
  191.             if ($c < '!' || $c > 'u')
  192.                 return "";
  193.    
  194.             $code = ord($input[$i]) & 0xff;
  195.             $ords[$state++] = $code - ord('!');
  196.    
  197.             if ($state == 5) {
  198.                 $state = 0;
  199.                 for ($sum = 0, $j = 0; $j < 5; $j++)
  200.                     $sum = $sum * 85 + $ords[$j];
  201.                 for ($j = 3; $j >= 0; $j--)
  202.                     $output .= chr($sum >> ($j * 8));
  203.             }
  204.         }
  205.         if ($state === 1)
  206.             return "";
  207.         elseif ($state > 1) {
  208.             for ($i = 0, $sum = 0; $i < $state; $i++)
  209.                 $sum += ($ords[$i] + ($i == $state - 1)) * pow(85, 4 - $i);
  210.             for ($i = 0; $i < $state - 1; $i++)
  211.                 $ouput .= chr($sum >> ((3 - $i) * 8));
  212.         }
  213.    
  214.         return $output;
  215.     }
  216.    
  217.     function decodeFlate($input) {
  218.         return gzuncompress($input);
  219.     }
  220.    
  221.     function getObjectOptions($object) {
  222.         $options = array();
  223.  
  224.         if (preg_match("#<<(.*)>>#ismU", $object, $options)) {
  225.             $options = explode("/", $options[1]);
  226.             @array_shift($options);
  227.    
  228.             $o = array();
  229.             for ($j = 0; $j < @count($options); $j++) {
  230.                 $options[$j] = preg_replace("#\s+#", " ", trim($options[$j]));
  231.                 if (strpos($options[$j], " ") !== false) {
  232.                     $parts = explode(" ", $options[$j]);
  233.                     $o[$parts[0]] = $parts[1];
  234.                 } else
  235.                     $o[$options[$j]] = true;
  236.             }
  237.             $options = $o;
  238.             unset($o);
  239.         }
  240.    
  241.         return $options;
  242.     }
  243.    
  244.     function getDecodedStream($stream, $options) {
  245.         $data = "";
  246.         if (empty($options["Filter"]))
  247.             $data = $stream;
  248.         else {
  249.             $length = !empty($options["Length"]) ? $options["Length"] : strlen($stream);
  250.             $_stream = substr($stream, 0, $length);
  251.    
  252.             foreach ($options as $key => $value) {
  253.                 if ($key == "ASCIIHexDecode")
  254.                     $_stream = $this->decodeAsciiHex($_stream);
  255.                 if ($key == "ASCII85Decode")
  256.                     $_stream = $this->decodeAscii85($_stream);
  257.                 if ($key == "FlateDecode")
  258.                     $_stream = $this->decodeFlate($_stream);
  259.                 if ($key == "Crypt") { // TO DO
  260.                 }
  261.             }
  262.             $data = $_stream;
  263.         }
  264.         return $data;
  265.     }
  266.     function getDirtyTexts(&$texts, $textContainers) {
  267.        
  268.         for ($j = 0; $j < count($textContainers); $j++) {
  269.             if (preg_match_all("#\[(.*)\]\s*TJ[\n|\r]#ismU", $textContainers[$j], $parts))
  270.                 $texts = array_merge($texts, @$parts[1]);
  271.             elseif(preg_match_all("#T[d|w|m|f]\s*(\(.*\))\s*Tj[\n|\r]#ismU", $textContainers[$j], $parts))
  272.                 $texts = array_merge($texts, @$parts[1]);
  273.             elseif(preg_match_all("#T[d|w|m|f]\s*(\[.*\])\s*Tj[\n|\r]#ismU", $textContainers[$j], $parts))
  274.                 $texts = array_merge($texts, @$parts[1]);
  275.         }
  276.     }
  277.     function getCharTransformations(&$transformations, $stream) {
  278.         preg_match_all("#([0-9]+)\s+beginbfchar(.*)endbfchar#ismU", $stream, $chars, PREG_SET_ORDER);
  279.         preg_match_all("#([0-9]+)\s+beginbfrange(.*)endbfrange#ismU", $stream, $ranges, PREG_SET_ORDER);
  280.    
  281.         for ($j = 0; $j < count($chars); $j++) {
  282.             $count = $chars[$j][1];
  283.             $current = explode("\n", trim($chars[$j][2]));
  284.             for ($k = 0; $k < $count && $k < count($current); $k++) {
  285.                 if (preg_match("#<([0-9a-f]{2,4})>\s+<([0-9a-f]{4,512})>#is", trim($current[$k]), $map))
  286.                     $transformations[str_pad($map[1], 4, "0")] = $map[2];
  287.             }
  288.         }
  289.         for ($j = 0; $j < count($ranges); $j++) {
  290.             $count = $ranges[$j][1];
  291.             $current = explode("\n", trim($ranges[$j][2]));
  292.             for ($k = 0; $k < $count && $k < count($current); $k++) {
  293.                 if (preg_match("#<([0-9a-f]{4})>\s+<([0-9a-f]{4})>\s+<([0-9a-f]{4})>#is", trim($current[$k]), $map)) {
  294.                     $from = hexdec($map[1]);
  295.                     $to = hexdec($map[2]);
  296.                     $_from = hexdec($map[3]);
  297.    
  298.                     for ($m = $from, $n = 0; $m <= $to; $m++, $n++)
  299.                         $transformations[sprintf("%04X", $m)] = sprintf("%04X", $_from + $n);
  300.                 } elseif (preg_match("#<([0-9a-f]{4})>\s+<([0-9a-f]{4})>\s+\[(.*)\]#ismU", trim($current[$k]), $map)) {
  301.                     $from = hexdec($map[1]);
  302.                     $to = hexdec($map[2]);
  303.                     $parts = preg_split("#\s+#", trim($map[3]));
  304.                    
  305.                     for ($m = $from, $n = 0; $m <= $to && $n < count($parts); $m++, $n++)
  306.                         $transformations[sprintf("%04X", $m)] = sprintf("%04X", hexdec($parts[$n]));
  307.                 }
  308.             }
  309.         }
  310.     }
  311.     function getTextUsingTransformations($texts, $transformations) {
  312.         $document = "";
  313.         for ($i = 0; $i < count($texts); $i++) {
  314.             $isHex = false;
  315.             $isPlain = false;
  316.    
  317.             $hex = "";
  318.             $plain = "";
  319.             for ($j = 0; $j < strlen($texts[$i]); $j++) {
  320.                 $c = $texts[$i][$j];
  321.                 switch($c) {
  322.                     case "<":
  323.                         $hex = "";
  324.                         $isHex = true;
  325.                     break;
  326.                     case ">":
  327.                         $hexs = str_split($hex, $this->multibyte); // 2 or 4 (UTF8 or ISO)
  328.                         for ($k = 0; $k < count($hexs); $k++) {
  329.                             $chex = str_pad($hexs[$k], 4, "0"); // Add tailing zero
  330.                             if (isset($transformations[$chex]))
  331.                                 $chex = $transformations[$chex];
  332.                             $document .= html_entity_decode("&#x".$chex.";");
  333.                         }
  334.                         $isHex = false;
  335.                     break;
  336.                     case "(":
  337.                         $plain = "";
  338.                         $isPlain = true;
  339.                     break;
  340.                     case ")":
  341.                         $document .= $plain;
  342.                         $isPlain = false;
  343.                     break;
  344.                     case "\\":
  345.                         $c2 = $texts[$i][$j + 1];
  346.                         if (in_array($c2, array("\\", "(", ")"))) $plain .= $c2;
  347.                         elseif ($c2 == "n") $plain .= '\n';
  348.                         elseif ($c2 == "r") $plain .= '\r';
  349.                         elseif ($c2 == "t") $plain .= '\t';
  350.                         elseif ($c2 == "b") $plain .= '\b';
  351.                         elseif ($c2 == "f") $plain .= '\f';
  352.                         elseif ($c2 >= '0' && $c2 <= '9') {
  353.                             $oct = preg_replace("#[^0-9]#", "", substr($texts[$i], $j + 1, 3));
  354.                             $j += strlen($oct) - 1;
  355.                             $plain .= html_entity_decode("&#".octdec($oct).";", $this->convertquotes);
  356.                         }
  357.                         $j++;
  358.                     break;
  359.    
  360.                     default:
  361.                         if ($isHex)
  362.                             $hex .= $c;
  363.                         if ($isPlain)
  364.                             $plain .= $c;
  365.                     break;
  366.                 }
  367.             }
  368.             $document .= "\n";
  369.         }
  370.    
  371.         return $document;
  372.     }
  373. }
  374. ?>