You are here

public function LocalServerPdfBackend::mergeStream 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::mergeStream()

Populate a PDF file with field data.

Parameters

string $pdf_content: The PDF template the field values specified in the mapping should be merged into.

\Drupal\fillpdf\FieldMapping[] $field_mappings: An array of FieldMapping objects mapping PDF field keys to the values they should be replaced with. Example:

[
  'Foo' => new TextFieldMapping('bar'),
  'Foo2' => new TextFieldMapping('bar2'),
  'Image1' => new ImageFieldMapping(base64_encode(file_get_contents($image)), 'jpg'),
];

array $context: The request context as returned by FillPdfLinkManipulator::parseLink().

Return value

string|null The raw file contents of the new PDF, or NULL if merging failed. The caller has to handle saving or serving the file accordingly.

Overrides PdfBackendInterface::mergeStream

See also

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

1 call to LocalServerPdfBackend::mergeStream()
LocalServerPdfBackend::mergeFile in src/Plugin/PdfBackend/LocalServerPdfBackend.php
Populate a PDF file with field data.

File

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

Class

LocalServerPdfBackend
LocalServer PdfBackend plugin.

Namespace

Drupal\fillpdf\Plugin\PdfBackend

Code

public function mergeStream($pdf_content, array $field_mappings, array $context) {
  $flatten = $context['flatten'];
  $api_fields = [];
  foreach ($field_mappings as $key => $mapping) {
    $api_field = NULL;
    if ($mapping instanceof TextFieldMapping) {
      $api_field = [
        'type' => 'text',
        'data' => $mapping
          ->getData(),
      ];
    }
    elseif ($mapping instanceof ImageFieldMapping) {
      $api_field = [
        'type' => 'image',
        'data' => base64_encode($mapping
          ->getData()),
      ];
      if ($extension = $mapping
        ->getExtension()) {
        $api_field['extension'] = $extension;
      }
    }
    if ($api_field) {
      $api_fields[$key] = $api_field;
    }
  }
  $request = [
    'pdf' => base64_encode($pdf_content),
    'flatten' => $flatten,
    'fields' => $api_fields,
  ];
  $json = json_encode($request);
  try {
    $response = $this->httpClient
      ->post($this->configuration['local_service_endpoint'] . '/api/v1/merge', [
      'body' => $json,
      'headers' => [
        'Content-Type' => 'application/json',
      ],
    ]);
    $decoded = json_decode((string) $response
      ->getBody(), TRUE);
    return base64_decode($decoded['pdf']);
  } catch (RequestException $e) {
    watchdog_exception('fillpdf', $e);
    return NULL;
  }
}