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
|
|
|
$formatter = function (string $content) : array { |
37
|
|
|
$content = trim($content); |
38
|
|
|
if ('-' !== ($content[0] ?? '')) { |
39
|
|
|
$content = '-'.$content; |
40
|
|
|
} |
41
|
|
|
|
42
|
|
|
return explode(' ', $content); |
43
|
|
|
}; |
44
|
|
|
|
45
|
|
|
$reducer = function (array $carry, array $option) : array { |
46
|
|
|
return array_merge($carry, $option); |
47
|
|
|
}; |
48
|
|
|
|
49
|
|
|
$this->options = array_reduce(array_map($formatter, $options), $reducer, []); |
|
|
|
|
50
|
|
|
|
51
|
|
|
return $this; |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
public function text() : string |
55
|
|
|
{ |
56
|
|
|
$process = new Process(array_merge([$this->binPath], $this->options, [$this->pdf, '-'])); |
57
|
|
|
$process->run(); |
58
|
|
|
if (!$process->isSuccessful()) { |
59
|
|
|
throw new CouldNotExtractText($process); |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
return trim($process->getOutput(), " \t\n\r\0\x0B\x0C"); |
63
|
|
|
} |
64
|
|
|
|
65
|
|
|
public static function getText(string $pdf, string $binPath = null, array $options = []) : string |
66
|
|
|
{ |
67
|
|
|
return (new static($binPath)) |
68
|
|
|
->setOptions($options) |
69
|
|
|
->setPdf($pdf) |
70
|
|
|
->text() |
71
|
|
|
; |
72
|
|
|
} |
73
|
|
|
} |
74
|
|
|
|
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..