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
|
|
|
$options = array_map([$this, 'formatOption'], $options); |
37
|
|
|
|
38
|
|
|
$this->options = array_reduce($options, function (array $carry, array $option): array { |
|
|
|
|
39
|
|
|
return array_merge($carry, $option); |
40
|
|
|
}, []); |
41
|
|
|
|
42
|
|
|
return $this; |
43
|
|
|
} |
44
|
|
|
|
45
|
|
|
protected function formatOption(string $content) : array |
46
|
|
|
{ |
47
|
|
|
$content = trim($content); |
48
|
|
|
if ('-' !== ($content[0] ?? '')) { |
49
|
|
|
$content = '-'.$content; |
50
|
|
|
} |
51
|
|
|
|
52
|
|
|
return explode(' ', $content); |
53
|
|
|
} |
54
|
|
|
|
55
|
|
|
public function text() : string |
56
|
|
|
{ |
57
|
|
|
$arguments = $this->options; |
58
|
|
|
$arguments[] = escapeshellarg($this->pdf); |
59
|
|
|
$arguments[] = '-'; |
60
|
|
|
|
61
|
|
|
$process = new Process($this->binPath.' '.implode(' ', $arguments)); |
62
|
|
|
$process->run(); |
63
|
|
|
if (!$process->isSuccessful()) { |
64
|
|
|
throw new CouldNotExtractText($process); |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
return trim($process->getOutput(), " \t\n\r\0\x0B\x0C"); |
68
|
|
|
} |
69
|
|
|
|
70
|
|
|
public static function getText(string $pdf, string $binPath = null, array $options = []) : string |
71
|
|
|
{ |
72
|
|
|
return (new static($binPath)) |
73
|
|
|
->setOptions($options) |
74
|
|
|
->setPdf($pdf) |
75
|
|
|
->text() |
76
|
|
|
; |
77
|
|
|
} |
78
|
|
|
} |
79
|
|
|
|
Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.
Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..