/ app / Http / Services / PdfFormReaderService.php
PdfFormReaderService.php
 1  <?php
 2  
 3  namespace App\Http\Services;
 4  
 5  use Exception;
 6  use Illuminate\Support\Facades\Storage;
 7  use mikehaertl\pdftk\Pdf;
 8  
 9  class PdfFormReaderService
10  {
11      public static function getDataFields(string $path)
12      {
13          if (!Storage::exists($path)) {
14              throw new Exception('File not found');
15          }
16  
17          $pdf = new Pdf(Storage::path($path), [
18              'command' => '/usr/bin/pdftk.pdftk-java',
19          ]);
20  
21          $data = $pdf->getDataFields();
22  
23          if ($data === false) {
24              throw new Exception($pdf->getError());
25          }
26  
27          return $data->__toArray();
28      }
29  
30      public static function read(string $path)
31      {
32          $data = PdfFormReaderService::getDataFields($path);
33          $response = [];
34  
35          foreach ($data as $PdfForm) {
36              $name = trim($PdfForm['FieldName']);
37              $value = $PdfForm['FieldValue'] ?? null;
38  
39              if (is_array($value)) {
40                  $value = implode(', ', $value);
41              }
42  
43              $response[$name] = trim($value);
44          }
45  
46          return $response;
47      }
48  }