You are here

class DomPdf in Entity Print 8.2

A Entity Print plugin for the DomPdf library.

Plugin annotation


@PrintEngine(
  id = "dompdf",
  label = @Translation("Dompdf"),
  export_type = "pdf"
)

Hierarchy

Expanded class hierarchy of DomPdf

File

src/Plugin/EntityPrint/PrintEngine/DomPdf.php, line 24

Namespace

Drupal\entity_print\Plugin\EntityPrint\PrintEngine
View source
class DomPdf extends PdfEngineBase implements ContainerFactoryPluginInterface {

  /**
   * Name of DomPdf log file.
   *
   * @var string
   */
  const LOG_FILE_NAME = 'log.html';

  /**
   * The Dompdf instance.
   *
   * @var \Dompdf\Dompdf
   */
  protected $dompdf;

  /**
   * The Dompdf instance.
   *
   * @var \Dompdf\Options
   */
  protected $dompdfOptions;

  /**
   * Keep track of HTML pages as they're added.
   *
   * @var string
   */
  protected $html = '';

  /**
   * Keep track of whether we've rendered or not.
   *
   * @var bool
   */
  protected $hasRendered;

  /**
   * {@inheritdoc}
   */
  public function __construct(array $configuration, $plugin_id, $plugin_definition, ExportTypeInterface $export_type, Request $request) {
    parent::__construct($configuration, $plugin_id, $plugin_definition, $export_type);
    $this->dompdfOptions = new DompdfLibOptions($this->configuration);
    $this->dompdfOptions
      ->setTempDir(\Drupal::service('file_system')
      ->getTempDirectory());
    $this->dompdfOptions
      ->setFontCache(\Drupal::service('file_system')
      ->getTempDirectory());
    $this->dompdfOptions
      ->setFontDir(\Drupal::service('file_system')
      ->getTempDirectory());
    $this->dompdfOptions
      ->setLogOutputFile(\Drupal::service('file_system')
      ->getTempDirectory() . DIRECTORY_SEPARATOR . self::LOG_FILE_NAME);
    $this->dompdfOptions
      ->setIsRemoteEnabled($this->configuration['enable_remote']);
    $this->dompdf = new DompdfLib($this->dompdfOptions);
    if ($this->configuration['disable_log']) {
      $this->dompdfOptions
        ->setLogOutputFile('');
    }
    $this->dompdf
      ->setBaseHost($request
      ->getHttpHost())
      ->setProtocol($request
      ->getScheme() . '://');
    $this
      ->setupHttpContext();
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
    return new static($configuration, $plugin_id, $plugin_definition, $container
      ->get('plugin.manager.entity_print.export_type')
      ->createInstance($plugin_definition['export_type']), $container
      ->get('request_stack')
      ->getCurrentRequest());
  }

  /**
   * {@inheritdoc}
   */
  public static function getInstallationInstructions() {
    return t('Please install with: @command', [
      '@command' => 'composer require "dompdf/dompdf 0.8.0"',
    ]);
  }

  /**
   * {@inheritdoc}
   */
  public function defaultConfiguration() {
    return parent::defaultConfiguration() + [
      'enable_html5_parser' => TRUE,
      'disable_log' => FALSE,
      'enable_remote' => TRUE,
      'cafile' => '',
      'verify_peer' => TRUE,
      'verify_peer_name' => TRUE,
    ];
  }

  /**
   * {@inheritdoc}
   */
  public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
    $form = parent::buildConfigurationForm($form, $form_state);
    $form['enable_html5_parser'] = [
      '#title' => $this
        ->t('Enable HTML5 Parser'),
      '#type' => 'checkbox',
      '#default_value' => $this->configuration['enable_html5_parser'],
      '#description' => $this
        ->t("Note, this library doesn't work without this option enabled."),
    ];
    $form['disable_log'] = [
      '#title' => $this
        ->t('Disable Log'),
      '#type' => 'checkbox',
      '#default_value' => $this->configuration['disable_log'],
      '#description' => $this
        ->t("Check to disable DomPdf logging to <code>@log_file_name</code> in Drupal's temporary directory.", [
        '@log_file_name' => self::LOG_FILE_NAME,
      ]),
    ];
    $form['enable_remote'] = [
      '#title' => $this
        ->t('Enable Remote URLs'),
      '#type' => 'checkbox',
      '#default_value' => $this->configuration['enable_remote'],
      '#description' => $this
        ->t('This settings must be enabled for CSS and Images to work unless you manipulate the source manually.'),
    ];
    $form['ssl_configuration'] = [
      '#type' => 'details',
      '#title' => $this
        ->t('SSL Configuration'),
      '#open' => !empty($this->configuration['cafile']) || empty($this->configuration['verify_peer']) || empty($this->configuration['verify_peer_name']),
    ];
    $form['ssl_configuration']['cafile'] = [
      '#title' => $this
        ->t('CA File'),
      '#type' => 'textfield',
      '#default_value' => $this->configuration['cafile'],
      '#description' => $this
        ->t('Path to the CA file. This may be needed for development boxes that use SSL. You can leave this empty in production.'),
    ];
    $form['ssl_configuration']['verify_peer'] = [
      '#title' => $this
        ->t('Verify Peer'),
      '#type' => 'checkbox',
      '#default_value' => $this->configuration['verify_peer'],
      '#description' => $this
        ->t("Verify an SSL Peer's certificate. For development only, do not disable this in production. See https://curl.haxx.se/libcurl/c/CURLOPT_SSL_VERIFYPEER.html"),
    ];
    $form['ssl_configuration']['verify_peer_name'] = [
      '#title' => $this
        ->t('Verify Peer Name'),
      '#type' => 'checkbox',
      '#default_value' => $this->configuration['verify_peer_name'],
      '#description' => $this
        ->t("Verify an SSL Peer's certificate. For development only, do not disable this in production. See https://curl.haxx.se/libcurl/c/CURLOPT_SSL_VERIFYPEER.html"),
    ];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function addPage($content) {

    // We must keep adding to previously added HTML as loadHtml() replaces the
    // entire document.
    $this->html .= (string) $content;
    $this->dompdf
      ->loadHtml($this->html);
  }

  /**
   * {@inheritdoc}
   */
  public function send($filename, $force_download = TRUE) {
    $this
      ->doRender();

    // Dompdf doesn't have a return value for send so just check the error
    // global it provides.
    if ($errors = $this
      ->getError()) {
      throw new PrintEngineException(sprintf('Failed to generate PDF: %s', $errors));
    }

    // The Dompdf library internally adds the .pdf extension so we remove it
    // from our filename here.
    $filename = preg_replace('/\\.pdf$/i', '', $filename);

    // If the filename received here is NULL, force open in the browser
    // otherwise attempt to have it downloaded.
    $this->dompdf
      ->stream($filename, [
      'Attachment' => $force_download,
    ]);
  }

  /**
   * {@inheritdoc}
   */
  public function getBlob() {
    $this
      ->doRender();
    return $this->dompdf
      ->output();
  }

  /**
   * Tell Dompdf to render the HTML into a PDF.
   */
  protected function doRender() {
    if (!$this->hasRendered) {
      $this->dompdf
        ->render();
      $this->hasRendered = TRUE;
    }
  }

  /**
   * {@inheritdoc}
   */
  protected function getError() {
    global $_dompdf_warnings;
    if (is_array($_dompdf_warnings)) {
      return implode(', ', $_dompdf_warnings);
    }
    return FALSE;
  }

  /**
   * {@inheritdoc}
   */
  public static function dependenciesAvailable() {
    return class_exists('Dompdf\\Dompdf') && !drupal_valid_test_ua();
  }

  /**
   * Setup the HTTP Context used by Dompdf for requesting resources.
   */
  protected function setupHttpContext() {
    $context_options = [
      'ssl' => [
        'verify_peer' => $this->configuration['verify_peer'],
        'verify_peer_name' => $this->configuration['verify_peer_name'],
      ],
    ];
    if ($this->configuration['cafile']) {
      $context_options['ssl']['cafile'] = $this->configuration['cafile'];
    }

    // If we have authentication then add it to the request context.
    if (!empty($this->configuration['username'])) {
      $auth = base64_encode(sprintf('%s:%s', $this->configuration['username'], $this->configuration['password']));
      $context_options['http']['header'] = [
        'Authorization: Basic ' . $auth,
      ];
    }
    $http_context = stream_context_create($context_options);
    $this->dompdf
      ->setHttpContext($http_context);
  }

  /**
   * {@inheritdoc}
   */
  protected function getPaperSizes() {
    return array_combine(array_keys(CPDF::$PAPER_SIZES), array_map('ucfirst', array_keys(CPDF::$PAPER_SIZES)));
  }

  /**
   * {@inheritdoc}
   */
  public function getPrintObject() {
    return $this->dompdf;
  }

}

Members

Namesort descending Modifiers Type Description Overrides
DependencySerializationTrait::$_entityStorages protected property An array of entity type IDs keyed by the property name of their storages.
DependencySerializationTrait::$_serviceIds protected property An array of service IDs keyed by property name used for serialization.
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
DomPdf::$dompdf protected property The Dompdf instance.
DomPdf::$dompdfOptions protected property The Dompdf instance.
DomPdf::$hasRendered protected property Keep track of whether we've rendered or not.
DomPdf::$html protected property Keep track of HTML pages as they're added.
DomPdf::addPage public function Add a string of HTML to a new page. Overrides PrintEngineInterface::addPage
DomPdf::buildConfigurationForm public function Form constructor. Overrides PdfEngineBase::buildConfigurationForm
DomPdf::create public static function Creates an instance of the plugin. Overrides PrintEngineBase::create
DomPdf::defaultConfiguration public function Gets default configuration for this plugin. Overrides PdfEngineBase::defaultConfiguration
DomPdf::dependenciesAvailable public static function Checks if the Print engine dependencies are available. Overrides PrintEngineInterface::dependenciesAvailable
DomPdf::doRender protected function Tell Dompdf to render the HTML into a PDF.
DomPdf::getBlob public function Gets the binary data for the printed document. Overrides PrintEngineInterface::getBlob
DomPdf::getError protected function
DomPdf::getInstallationInstructions public static function Gets the installation instructions for this Print engine. Overrides PrintEngineBase::getInstallationInstructions
DomPdf::getPaperSizes protected function Gets the paper sizes supported. Overrides PdfEngineBase::getPaperSizes
DomPdf::getPrintObject public function Gets the object for this Print engine. Overrides PrintEngineInterface::getPrintObject
DomPdf::LOG_FILE_NAME constant Name of DomPdf log file.
DomPdf::send public function Send the Print contents to the browser. Overrides PrintEngineInterface::send
DomPdf::setupHttpContext protected function Setup the HTTP Context used by Dompdf for requesting resources.
DomPdf::__construct public function Constructs a \Drupal\Component\Plugin\PluginBase object. Overrides PrintEngineBase::__construct
MessengerTrait::$messenger protected property The messenger. 29
MessengerTrait::messenger public function Gets the messenger. 29
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 3
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.
PrintEngineBase::$exportType protected property The export type plugin.
PrintEngineBase::calculateDependencies public function
PrintEngineBase::getConfiguration public function Gets this plugin's configuration. Overrides ConfigurableInterface::getConfiguration
PrintEngineBase::getExportType public function Gets the export type. Overrides PrintEngineInterface::getExportType
PrintEngineBase::LANDSCAPE constant
PrintEngineBase::PORTRAIT constant
PrintEngineBase::setConfiguration public function Sets the configuration for this plugin instance. Overrides ConfigurableInterface::setConfiguration
PrintEngineBase::submitConfigurationForm public function Form submission handler. Overrides PluginFormInterface::submitConfigurationForm 2
PrintEngineBase::validateConfigurationForm public function Form validation handler. Overrides PluginFormInterface::validateConfigurationForm 2
StringTranslationTrait::$stringTranslation protected property The string translation service. 1
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.