You are here

class LocalServerPdfBackend 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

LocalServer PdfBackend plugin.

Plugin annotation


@PdfBackend(
  id = "local_service",
  label = @Translation("FillPDF LocalServer"),
  description = @Translation("Network-accessible, self-installed PDF API. You will need a VPS or dedicated server."),
  weight = 5
)

Hierarchy

Expanded class hierarchy of LocalServerPdfBackend

File

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

Namespace

Drupal\fillpdf\Plugin\PdfBackend
View source
class LocalServerPdfBackend extends PdfBackendBase implements ContainerFactoryPluginInterface {

  /**
   * The file system.
   *
   * @var \Drupal\Core\File\FileSystem
   */
  protected $fileSystem;

  /**
   * The Guzzle http client.
   *
   * @var \GuzzleHttp\Client
   */
  protected $httpClient;

  /**
   * Constructs a LocalServerPdfBackend plugin object.
   *
   * @param array $configuration
   *   A configuration array containing information about the plugin instance.
   * @param string $plugin_id
   *   The plugin_id for the plugin instance.
   * @param array $plugin_definition
   *   The plugin implementation definition.
   * @param \GuzzleHttp\Client $http_client
   *   The Guzzle http client.
   */
  public function __construct(array $configuration, $plugin_id, array $plugin_definition, Client $http_client) {
    parent::__construct($configuration, $plugin_id, $plugin_definition);
    $this->httpClient = $http_client;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static($configuration, $plugin_id, $plugin_definition, $container
      ->get('http_client'));
  }

  /**
   * {@inheritdoc}
   */
  public function parseFile(FileInterface $template_file) {
    $pdf_content = file_get_contents($template_file
      ->getFileUri());
    return $this
      ->parseStream($pdf_content);
  }

  /**
   * {@inheritdoc}
   */
  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;
  }

  /**
   * {@inheritdoc}
   */
  public function mergeFile(FileInterface $template_file, array $field_mappings, array $context) {
    $pdf_content = file_get_contents($template_file
      ->getFileUri());
    return $this
      ->mergeStream($pdf_content, $field_mappings, $context);
  }

  /**
   * {@inheritdoc}
   */
  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;
    }
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property
DependencySerializationTrait::$_serviceIds protected property
DependencySerializationTrait::__sleep public function 2
DependencySerializationTrait::__wakeup public function 2
LocalServerPdfBackend::$fileSystem protected property The file system.
LocalServerPdfBackend::$httpClient protected property The Guzzle http client.
LocalServerPdfBackend::create public static function Creates an instance of the plugin. Overrides ContainerFactoryPluginInterface::create
LocalServerPdfBackend::mergeFile public function Populate a PDF file with field data. Overrides PdfBackendInterface::mergeFile
LocalServerPdfBackend::mergeStream public function Populate a PDF file with field data. Overrides PdfBackendInterface::mergeStream
LocalServerPdfBackend::parseFile public function Parse a PDF and return a list of its fields. Overrides PdfBackendInterface::parseFile
LocalServerPdfBackend::parseStream public function Parse a PDF and return a list of its fields. Overrides PdfBackendInterface::parseStream
LocalServerPdfBackend::__construct public function Constructs a LocalServerPdfBackend plugin object. Overrides PluginBase::__construct
MessengerTrait::$messenger protected property The messenger. 27
MessengerTrait::messenger public function Gets the messenger. 27
MessengerTrait::setMessenger public function Sets the messenger.
PluginBase::$configuration protected property Configuration information passed into the plugin. 1
PluginBase::$pluginDefinition protected property The plugin implementation definition. 1
PluginBase::$pluginId protected property The plugin_id.
PluginBase::DERIVATIVE_SEPARATOR constant A string which is used to separate base plugin IDs from the derivative ID.
PluginBase::getBaseId public function Gets the base_plugin_id of the plugin instance. Overrides DerivativeInspectionInterface::getBaseId
PluginBase::getDerivativeId public function Gets the derivative_id of the plugin instance. Overrides DerivativeInspectionInterface::getDerivativeId
PluginBase::getPluginDefinition public function Gets the definition of the plugin implementation. Overrides PluginInspectionInterface::getPluginDefinition 2
PluginBase::getPluginId public function Gets the plugin_id of the plugin instance. Overrides PluginInspectionInterface::getPluginId
PluginBase::isConfigurable public function Determines if the plugin is configurable.
StringTranslationTrait::$stringTranslation protected property The string translation service. 4
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.