|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace Spatie\PdfToText; |
|
4
|
|
|
|
|
5
|
|
|
use Spatie\PdfToText\Exceptions\CouldNotExtractText; |
|
6
|
|
|
use Spatie\PdfToText\Exceptions\MalformedOption; |
|
7
|
|
|
use Spatie\PdfToText\Exceptions\PdfNotFound; |
|
8
|
|
|
use Symfony\Component\Process\Process; |
|
9
|
|
|
|
|
10
|
|
|
class Pdf |
|
11
|
|
|
{ |
|
12
|
|
|
protected $pdf; |
|
13
|
|
|
|
|
14
|
|
|
protected $binPath; |
|
15
|
|
|
|
|
16
|
|
|
protected $options = []; |
|
17
|
|
|
|
|
18
|
|
|
public function __construct(string $binPath = null) |
|
19
|
|
|
{ |
|
20
|
|
|
$this->binPath = $binPath ?? '/usr/bin/pdftotext'; |
|
21
|
|
|
} |
|
22
|
|
|
|
|
23
|
|
|
public function setPdf(string $pdf) : self |
|
24
|
|
|
{ |
|
25
|
|
|
if (!is_readable($pdf)) { |
|
26
|
|
|
throw new PdfNotFound(sprintf('could not find or read pdf `%s`', $pdf)); |
|
27
|
|
|
} |
|
28
|
|
|
|
|
29
|
|
|
$this->pdf = $pdf; |
|
30
|
|
|
|
|
31
|
|
|
return $this; |
|
32
|
|
|
} |
|
33
|
|
|
|
|
34
|
|
|
public function setOptions(array $options) : self |
|
35
|
|
|
{ |
|
36
|
|
|
$this->options = array_map([$this, 'formatOption'], $options); |
|
37
|
|
|
|
|
38
|
|
|
return $this; |
|
39
|
|
|
} |
|
40
|
|
|
|
|
41
|
|
|
protected function formatOption(string $content) : string |
|
42
|
|
|
{ |
|
43
|
|
|
$content = trim($content); |
|
44
|
|
|
if ('-' === $content[0] ?? '') { |
|
45
|
|
|
return $content; |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
return '-'.$content; |
|
49
|
|
|
} |
|
50
|
|
|
|
|
51
|
|
|
public function text() : string |
|
52
|
|
|
{ |
|
53
|
|
|
$arguments = $this->options; |
|
54
|
|
|
$arguments[] = escapeshellarg($this->pdf); |
|
55
|
|
|
$arguments[] = '-'; |
|
56
|
|
|
|
|
57
|
|
|
$commandline = $this->binPath.' '.implode(' ', $arguments); |
|
58
|
|
|
$process = new Process($commandline); |
|
59
|
|
|
$process->run(); |
|
60
|
|
|
if (!$process->isSuccessful()) { |
|
61
|
|
|
throw new CouldNotExtractText($process); |
|
62
|
|
|
} |
|
63
|
|
|
|
|
64
|
|
|
return trim($process->getOutput(), " \t\n\r\0\x0B\x0C"); |
|
65
|
|
|
} |
|
66
|
|
|
|
|
67
|
|
|
public static function getText(string $pdf, string $binPath = null, array $options = []) : string |
|
68
|
|
|
{ |
|
69
|
|
|
return (new static($binPath)) |
|
70
|
|
|
->setOptions($options) |
|
71
|
|
|
->setPdf($pdf) |
|
72
|
|
|
->text() |
|
73
|
|
|
; |
|
74
|
|
|
} |
|
75
|
|
|
} |
|
76
|
|
|
|