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