我有一个带有自定义路径和自定义 Controller 的自定义页面构建,我想让它可打印以供下载。
我正在查看可打印模块,但我不知道如何获取将其打印为 pdf 文件的路径。
有什么想法吗?
最佳答案
使用可打印模块本身的 Controller ,我能够生成 pdf。您只需要将实体 View (比较 showFormat 方法)与您自己的渲染数组(构建)交换即可。 ConfigFactory 在此示例中实际上并未使用。
<?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();
}
}
关于php - 如何在 Drupal 8 中使用带有自定义页面的可打印模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48153083/