You are here

public function LocalServerPdfBackend::parseStream in FillPDF 5.0.x

Same name and namespace in other branches
  1. 8.4 src/Plugin/PdfBackend/LocalServerPdfBackend.php \Drupal\fillpdf\Plugin\PdfBackend\LocalServerPdfBackend::parseStream()

Parse a PDF and return a list of its fields.

@todo Replace output array by a value object.

Parameters

string $pdf_content: The PDF template whose fields are to be parsed. This should be the contents of a PDF loaded with something like file_get_contents() or equivalent.

Return value

string[][] An array of associative arrays. Each sub-array contains a 'name' key with the name of the field and a 'type' key with the type. These can be iterated over and saved by the caller.

Overrides PdfBackendInterface::parseStream

See also

\Drupal\fillpdf\Plugin\PdfBackendInterface::parseFile()

1 call to LocalServerPdfBackend::parseStream()
LocalServerPdfBackend::parseFile in src/Plugin/PdfBackend/LocalServerPdfBackend.php
Parse a PDF and return a list of its fields.

File

src/Plugin/PdfBackend/LocalServerPdfBackend.php, line 85

Class

LocalServerPdfBackend
LocalServer PdfBackend plugin.

Namespace

Drupal\fillpdf\Plugin\PdfBackend

Code

public function parseStream($pdf_content) {
  $request = [
    'pdf' => base64_encode($pdf_content),
  ];
  $json = json_encode($request);
  $fields = [];
  try {
    $fields_response = $this->httpClient
      ->post($this->configuration['local_service_endpoint'] . '/api/v1/parse', [
      'body' => $json,
      'headers' => [
        'Content-Type' => 'application/json',
      ],
    ]);
  } catch (RequestException $request_exception) {
    if ($response = $request_exception
      ->getResponse()) {
      \Drupal::messenger()
        ->addError($this
        ->t('Error %code. Reason: %reason.', [
        '%code' => $response
          ->getStatusCode(),
        '%reason' => $response
          ->getReasonPhrase(),
      ]));
    }
    else {
      \Drupal::messenger()
        ->addError($this
        ->t('Unknown error occurred parsing PDF.'));
    }
  }
  $fields = json_decode((string) $fields_response
    ->getBody(), TRUE);
  return $fields;
}