You are here

PrintableController.php in Printer and PDF versions for Drupal 8+ 8

Same filename and directory in other branches
  1. 2.x src/Controller/PrintableController.php

File

src/Controller/PrintableController.php
View source
<?php

namespace Drupal\printable\Controller;

use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\printable\PrintableFormatPluginManager;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Drupal\Core\Config\ConfigFactory;

/**
 * Controller to display an entity in a particular printable format.
 */
class PrintableController extends ControllerBase implements ContainerInjectionInterface {

  /**
   * The printable format plugin manager.
   *
   * @var \Drupal\printable\PrintableFormatPluginManager
   */
  protected $printableFormatManager;

  /**
   * The configuration factory.
   *
   * @var \Drupal\Core\Config\ConfigFactory
   */
  protected $configFactory;

  /**
   * Constructs a \Drupal\printable\Controller\PrintableController object.
   *
   * @param \Drupal\printable\PrintableFormatPluginManager $printable_format_manager
   *   The printable format plugin manager.
   * @param \Drupal\Core\Config\ConfigFactory $config_factory
   *   The config factory class instance.
   */
  public function __construct(PrintableFormatPluginManager $printable_format_manager, ConfigFactory $config_factory) {
    $this->printableFormatManager = $printable_format_manager;
    $this->configFactory = $config_factory;
  }

  /**
   * {@inheritdoc}
   */
  public static function create(ContainerInterface $container) {
    return new static($container
      ->get('printable.format_plugin_manager'), $container
      ->get('config.factory'));
  }

  /**
   * Returns the entity rendered via the given printable format.
   *
   * @param \Drupal\Core\Entity\EntityInterface $entity
   *   The entity to be printed.
   * @param string $printable_format
   *   The identifier of the hadcopy format plugin.
   *
   * @return \Symfony\Component\HttpFoundation\Response
   *   The printable response.
   */
  public function showFormat(EntityInterface $entity, $printable_format) {
    if ($this->printableFormatManager
      ->getDefinition($printable_format)) {
      $format = $this->printableFormatManager
        ->createInstance($printable_format);
      $content = $this
        ->entityManager()
        ->getViewBuilder($entity
        ->getEntityTypeId())
        ->view($entity, 'printable');
      $format
        ->setContent($content);
      return $format
        ->getResponse();
    }
    else {
      throw new NotFoundHttpException();
    }
  }

}

Classes

Namesort descending Description
PrintableController Controller to display an entity in a particular printable format.