You are here

class ConvertToPdf in PDF using mPDF 8

Same name and namespace in other branches
  1. 8.2 src/Conversion/ConvertToPdf.php \Drupal\pdf_using_mpdf\Conversion\ConvertToPdf

Class ConvertToPdf.

Hierarchy

Expanded class hierarchy of ConvertToPdf

1 file declares its use of ConvertToPdf
GeneratePdf.php in src/Controller/GeneratePdf.php
1 string reference to 'ConvertToPdf'
pdf_using_mpdf.services.yml in ./pdf_using_mpdf.services.yml
pdf_using_mpdf.services.yml
1 service uses ConvertToPdf
pdf_using_mpdf.conversion in ./pdf_using_mpdf.services.yml
\Drupal\pdf_using_mpdf\Conversion\ConvertToPdf

File

src/Conversion/ConvertToPdf.php, line 17

Namespace

Drupal\pdf_using_mpdf\Conversion
View source
class ConvertToPdf implements ConvertToPdfInterface {

  /**
   * The render interface.
   *
   * @var \Drupal\Core\Render\RendererInterface
   */
  protected $renderer;

  /**
   * The Mpdf object.
   *
   * @var \Mpdf\Mpdf
   */
  protected $mpdf;

  /**
   * Token service.
   *
   * @var \Drupal\Core\Utility\Token
   */
  protected $token;

  /**
   * Config factory.
   *
   * @var \Drupal\Core\Config\ConfigFactoryInterface
   */
  protected $configFactory;

  /**
   * Settings.
   *
   * @var array
   */
  protected $settings;

  /**
   * The node object.
   *
   * @var \Drupal\node\NodeInterface|mixed|null
   */
  protected $node;

  /**
   * The PDF filename.
   *
   * @var string
   */
  protected $filename;

  /**
   * ConvertToPdf constructor.
   *
   * @param \Drupal\Core\Render\RendererInterface $renderer
   *   The render interface.
   * @param \Drupal\Core\Config\ConfigFactoryInterface $config_factory
   *   Config factory.
   * @param \Drupal\Core\Utility\Token $token
   *   Token service.
   */
  public function __construct(RendererInterface $renderer, ConfigFactoryInterface $config_factory, Token $token) {
    $this->renderer = $renderer;
    $this->configFactory = $config_factory;
    $this->token = $token;
    $node = \Drupal::routeMatch()
      ->getParameter('node');
    if ($node instanceof NodeInterface) {
      $this->node = $node;
    }
  }

  /**
   * Get configuration values of this module.
   *
   * @return array
   *   Config settings.
   */
  protected function getConfigValues() {
    return $this->configFactory
      ->getEditable('pdf_using_mpdf.settings')
      ->get('pdf_using_mpdf');
  }

  /**
   * Instantiate Mpdf object.
   */
  protected function init() {
    $mpdf_config = $this
      ->getDefaultConfig();
    $this->mpdf = new Mpdf($mpdf_config);
  }

  /**
   * {@inheritdoc}
   */
  public function convert($html) {
    $this->settings = $this
      ->getConfigValues();
    if (empty($html)) {
      drupal_get_messages('error');
      drupal_set_message(t('No content. PDF cannot be generated for this path.'), 'error');
      return;
    }
    $this
      ->generator($html);
    $this
      ->showPdf();
  }

  /**
   * {@inheritdoc}
   */
  public function convertToString($html) {
    $this->settings = $this
      ->getConfigValues();
    if (empty($html)) {
      drupal_get_messages('error');
      drupal_set_message(t('No content. PDF cannot be generated for this path.'), 'error');
      return;
    }
    $this
      ->generator($html);
    return $this->mpdf
      ->Output('', Destination::STRING_RETURN);
  }

  /**
   * Gets the PDF filename.
   */
  public function getFilename() {
    return $this->filename;
  }

  /**
   * Generate the PDF file using the Mpdf library.
   *
   * @param string $html
   *   Contents of the template already with the node data.
   *
   * @throws \Mpdf\MpdfException
   */
  protected function generator($html) {
    $styles = $this
      ->importStyles();
    $this
      ->init();
    $this
      ->setHeader();

    // Apply custom cascading styles.
    if (!empty($styles)) {
      $this->mpdf
        ->WriteHTML($styles, 1);
    }
    $this->mpdf
      ->WriteHTML($html, 2);
    $this
      ->applyProperties();
    $this
      ->setFooter();
    $this
      ->setFilename();
  }

  /**
   * Set header for PDF file.
   */
  protected function setHeader() {
    $header = $this->settings['pdf_header'];
    if (isset($header) && $header != NULL) {
      $header = $this
        ->replaceTokens($header);
      $this->mpdf
        ->SetHTMLHeader($header);
    }
  }

  /**
   * Apply additional properties to PDF file.
   */
  protected function applyProperties() {

    // Set Watermark.
    $watermark_option = $this->settings['watermark_option'];
    $watermark_opacity = $this->settings['watermark_opacity'];
    if ($watermark_option == 0) {
      $text = $this->settings['pdf_watermark_text'];
      if (!empty($text)) {
        $this->mpdf
          ->SetWatermarkText($text, $watermark_opacity);
        $this->mpdf->showWatermarkText = TRUE;
      }
    }
    else {
      $image_id = $this->settings['watermark_image'];
      if (isset($image_id[0])) {
        $file = File::load($image_id[0]);
        $image_path = $file
          ->getFileUri();
        $image_path = file_create_url($image_path);
        $this->mpdf
          ->SetWatermarkImage($image_path, $watermark_opacity);
        $this->mpdf->showWatermarkImage = TRUE;
      }
    }

    // Set Title.
    $title = $this->settings['pdf_set_title'];
    if (!empty($title)) {
      $this->mpdf
        ->SetTitle($title);
    }

    // Set Author.
    $author = $this->settings['pdf_set_author'];
    if (!empty($author)) {
      $this->mpdf
        ->SetAuthor($author);
    }

    // Set Subject.
    $subject = $this->settings['pdf_set_subject'];
    if (isset($subject) && $subject != NULL) {
      $this->mpdf
        ->SetSubject($subject);
    }

    // Set Creator.
    $creator = $this->settings['pdf_set_creator'];
    if (!empty($creator)) {
      $this->mpdf
        ->SetCreator($creator);
    }

    // Set Password.
    $password = $this->settings['pdf_password'];
    if (!empty($password)) {
      $this->mpdf
        ->SetProtection([
        'print',
        'copy',
      ], $password, $password);
    }
  }

  /**
   * Set footer for PDF file.
   */
  protected function setFooter() {
    $footer = $this->settings['pdf_footer'];
    if (isset($footer) && $footer != NULL) {
      $footer = $this
        ->replaceTokens($footer);
      $this->mpdf
        ->SetHTMLFooter($footer);
    }
  }

  /**
   * Sets the PDF filename.
   */
  protected function setFilename() {
    $this->filename = $this
      ->replaceTokens($this->settings['pdf_filename']);
  }

  /**
   * Show PDF to the user.
   */
  public function showPdf() {
    switch ($this->settings['pdf_save_option']) {
      case 0:
        $this->mpdf
          ->Output($this->filename . '.pdf', Destination::INLINE);
        break;
      case 1:
        $this->mpdf
          ->Output($this->filename . '.pdf', Destination::DOWNLOAD);
        break;
      case 2:
        $folder = \Drupal::service('file_system')
          ->realpath(file_default_scheme() . "://");
        $folder .= '/pdf_using_mpdf';
        $this->mpdf
          ->Output($folder . '/' . $this->filename . '.pdf', Destination::FILE);
        drupal_set_message(t('PDF File <em>@filename</em> has been saved to the server.', [
          '@filename' => $this->filename . '.pdf',
        ]));
        break;
    }
  }

  /**
   * Configuration values to instantiate Mpdf constructor.
   *
   * @return array
   *   Default configuration.
   */
  public function getDefaultConfig() {
    $orientation = $this->settings['orientation'] == 'L' ? '-L' : '';
    $config = [
      'tempDir' => file_directory_temp(),
      'useActiveForms' => TRUE,
      'format' => $this->settings['pdf_page_size'] . $orientation,
      'default_font_size' => $this->settings['pdf_font_size'] . 'pt',
      'default_font' => $this->settings['pdf_default_font'],
      'margin_left' => $this->settings['margin_left'],
      'margin_right' => $this->settings['margin_right'],
      'margin_top' => $this->settings['margin_top'],
      'margin_bottom' => $this->settings['margin_bottom'],
      'margin_header' => $this->settings['margin_header'],
      'margin_footer' => $this->settings['margin_footer'],
      'dpi' => $this->settings['dpi'],
      'img_dpi' => $this->settings['img_dpi'],
      'enabled_content_types' => $this->settings['enabled_content_types'],
    ];
    return $config;
  }

  /**
   * Check if the custom stylesheet exists.
   *
   * @return string
   *   The css file.
   */
  protected function importStyles() {
    $file = '';
    $path = DRUPAL_ROOT . '/' . $this->settings['pdf_css_file'];
    if (file_exists($path)) {
      $file = file_get_contents($path);
    }
    return $file;
  }

  /**
   * Replaces tokens.
   *
   * @param string $text
   *   The text that can contain tokens.
   *
   * @return string
   *   Text with tokens replaced.
   */
  protected function replaceTokens($text) {
    $data = [];
    if ($this->node) {
      $data['node'] = $this->node;
    }
    return $this->token
      ->replace($text, $data);
  }

}

Members

Namesort descending Modifiers Type Description Overrides
ConvertToPdf::$configFactory protected property Config factory.
ConvertToPdf::$filename protected property The PDF filename.
ConvertToPdf::$mpdf protected property The Mpdf object.
ConvertToPdf::$node protected property The node object.
ConvertToPdf::$renderer protected property The render interface.
ConvertToPdf::$settings protected property Settings.
ConvertToPdf::$token protected property Token service.
ConvertToPdf::applyProperties protected function Apply additional properties to PDF file.
ConvertToPdf::convert public function Converts HTML to PDF. Overrides ConvertToPdfInterface::convert
ConvertToPdf::convertToString public function Converts html to PDF and return as a string. Overrides ConvertToPdfInterface::convertToString
ConvertToPdf::generator protected function Generate the PDF file using the Mpdf library.
ConvertToPdf::getConfigValues protected function Get configuration values of this module.
ConvertToPdf::getDefaultConfig public function Configuration values to instantiate Mpdf constructor.
ConvertToPdf::getFilename public function Gets the PDF filename.
ConvertToPdf::importStyles protected function Check if the custom stylesheet exists.
ConvertToPdf::init protected function Instantiate Mpdf object.
ConvertToPdf::replaceTokens protected function Replaces tokens.
ConvertToPdf::setFilename protected function Sets the PDF filename.
ConvertToPdf::setFooter protected function Set footer for PDF file.
ConvertToPdf::setHeader protected function Set header for PDF file.
ConvertToPdf::showPdf public function Show PDF to the user.
ConvertToPdf::__construct public function ConvertToPdf constructor.