<?php
class Pdf2Txt
{
    public $jar = 'pdfbox/pdfbox-app-2.0.21.jar';
    private $pdfPath;
    private $txtPath;
    private $options = [];
    public $error = '';

    /**
     * Pdf2Txt constructor.
     * @param $pdfPath
     */
    public function __construct($pdfPath)
    {
		//soul 新增路径 2020/9/5
		$this->jar = dirname(__FILE__). '/'.$this->jar;
        $this->pdfPath = $pdfPath;
        $this->txtPath = mvc::$cfg['PATH_CACHE'].md5(rand(1000, 9999).$pdfPath.microtime().rand(1000, 9999)) . '.temp.txt';
    }

    /**
     * @return bool|string
     */
    public function toTxt()
    {
        $command = [];
        $command[] = "java -jar";
        $command[] = $this->jar;
        $command[] = "ExtractText";
        $command[] = $this->pdfPath;
        $command[] = $this->txtPath;
        $cmd = implode(' ', $command);
        if (!$this->checkFile($this->pdfPath))
            return false;
        list($code, $stdErr) = $this->pipeExec($cmd);
        if ($code === 0 && $this->checkFile($this->txtPath)) {
            $text = file_get_contents($this->txtPath);
            unlink($this->txtPath);
            return $text;
        } else {
            $this->error .= $stdErr;
            return false;
        }
    }

    public function checkFile($file)
    {
        if (!file_exists($this->pdfPath)) {
            $this->error .= "the file $file not found.";
            return false;
        }
        return true;
    }

    private function pipeExec($cmd)
    {
        $process = proc_open($cmd, [
            ['pipe', 'r'],
            ['pipe', 'w'],
            ['pipe', 'w'],
        ], $pipes);
        $stdErr = stream_get_contents($pipes[2]);
        fclose($pipes[2]);
        $code = (int)proc_close($process);
        return [$code, $stdErr];
    }
}