I have a custom page build with a custom path and custom Controller, and I would like to make it printable to download it.
I'm looking at the printable module, but I don't see how to get the path to print it as a pdf file.
Any idea?
Using the controller of the printable module itself, I was able to generate a pdf. You only need to exchange the entity view (compare the showFormat method) with your own render array (build). ConfigFactory is not actually used in this example.
<?php
namespace Drupal\your_module\Controller;
use Drupal\Core\Config\ConfigFactory;
use Drupal\Core\Controller\ControllerBase;
use Drupal\printable\PrintableFormatPluginManager;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
/**
* Returns response.
*/
class PrintViewController extends ControllerBase {
/**
* The printable format plugin manager.
*
* @var \Drupal\printable\PrintableFormatPluginManager
*/
protected $printableFormatManager;
/**
* The configuration factory.
*
* @var \Drupal\Core\Config\ConfigFactory
*/
protected $configFactory;
/**
* Constructs a PrintViewController 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')
);
}
/**
* Builds the response.
*/
public function build() {
$build['content'] = [
'#type' => 'item',
'#markup' => $this->t('It works!'),
];
return $this->showFormat($build, 'pdf'); // One of 'pdf' / 'print'
}
/**
* Returns the entity rendered via the given printable format.
*
* @param array $build
* The render array be printed.
* @param string $printable_format
* The identifier of the hardcopy format plugin (i.e. print or pdf).
*
* @return \Symfony\Component\HttpFoundation\Response
* The printable response.
*/
public function showFormat(array $build, $printable_format) {
if (!$this->printableFormatManager->getDefinition($printable_format, FALSE)) {
throw new NotFoundHttpException();
}
$format = $this->printableFormatManager->createInstance($printable_format);
$format->setContent($build);
return $format->getResponse();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With