Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php pdfparser is not working for pdf version 1.7

Tags:

php

pdf

I'm using pdfparser to parse text from a pdf file. for old version pdf files it is working but for new version pdf files this parser is not working. my pdf version is 1.7

<?php
  include 'vendor/autoload.php'; 
  // Parse pdf file and build necessary objects.
  $parser = new Smalot\PdfParser\Parser();
  $pdf    = $parser->parseFile('sample.pdf'); 
  // Retrieve all pages from the pdf file.
  $pages  = $pdf->getPages(); 
  // Loop over each page to extract text.
  $content=array();
  foreach ($pages as $page) {
      $content[]= $page->getTextArray();  
    echo"<pre>";
    print_r($content);

  }
like image 512
vijay kumar Avatar asked Oct 16 '25 23:10

vijay kumar


1 Answers

I experienced the same behaviour!

Now I use a tool to check the pdf version before I try to parse it. If it is not 1.4 I convert it to 1.4 and parse it then. Here is a php library for that if needed: https://github.com/xthiago/pdf-version-converter

Code example:

function searchablePdfParser($systemPath) {
    //we save the file to a temporay file because we might need to convert it.
    $tempPath = getPathWithIdAndTimestamp($systemPath) . 'tmp.pdf';
    copy($systemPath, $tempPath);
    //check whether it needs to be converted and convert it if required
    $guesser = new RegexGuesser();
    $pdfVersion = $guesser->guess($tempPath); // will print something like '1.4'
    if ( $pdfVersion != '1.4' ) {
        $command = new GhostscriptConverterCommand();
        $filesystem = new Filesystem();
        $converter = new GhostscriptConverter($command, $filesystem);
        $converter->convert($tempPath, '1.4');
    }
    //parse the original file or the converted file if it hadn't been a pdf 1.4 version
    $parser = new \Smalot\PdfParser\Parser();
    $pdf = $parser->parseFile($tempPath);
    $text = $pdf->getText();  
    unlink($tempPath);
    if ( strlen($text) < 30 ) {
        return '';
    }
    return $text;
}
like image 63
rf1234 Avatar answered Oct 19 '25 11:10

rf1234



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!