View source
<?php
namespace Drupal\pdf_generator;
use Dompdf\Dompdf;
use Dompdf\Options;
use Dompdf\Adapter\CPDF;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Render\Renderer;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\RequestStack;
use Drupal\Core\StringTranslation\StringTranslationTrait;
class DomPdfGenerator {
use StringTranslationTrait;
protected $options;
protected $dompdf;
protected $moduleHandler;
protected $renderer;
protected $requestStack;
public function __construct(Renderer $renderer, RequestStack $request_stack, ModuleHandlerInterface $module_handler) {
$this->renderer = $renderer;
$this->requestStack = $request_stack;
$this->moduleHandler = $module_handler;
$this->options = new Options();
$this->options
->set('enable_css_float', TRUE);
$this->options
->set('enable_html5_parser', TRUE);
$this->options
->set('enable_remote', TRUE);
$this->options
->set('defaultFont', 'Times');
}
public function getResponse($title, array $content, $preview = FALSE, array $options = [], $pageSize = 'A4', $disposition = 'portrait', $cssText = NULL, $cssPath = NULL) {
$request = $this->requestStack
->getCurrentRequest();
$base_url = $request
->getSchemeAndHttpHost();
foreach ($options as $key => $option) {
$this->options
->set($key, $option);
}
$this->dompdf = new Dompdf($this->options);
$css = file_get_contents(drupal_get_path('module', 'pdf_generator') . '/css/pdf.css');
if (!empty($cssText)) {
$css .= "\r\n";
$css .= $cssText;
}
if (!empty($cssPath) && file_exists($cssPath)) {
$css .= "\r\n";
$css .= file_get_contents($cssPath);
}
$build = [
'#theme' => 'pdf_generator_print',
'#css' => [
'#markup' => $css,
],
'#content' => $content,
'#title' => $title,
];
if ($preview) {
return $build;
}
$html = $this->renderer
->render($build);
$html = urldecode($html);
$html = str_replace('src="' . $base_url . '/', 'src="', $html);
$html = str_replace('href="/', 'href="' . $base_url . '/', $html);
$html = str_replace('src="/', 'src="' . DRUPAL_ROOT . '/', $html);
$this->dompdf
->setOptions($this->options);
$this->dompdf
->loadHtml($html);
$this->dompdf
->setPaper($pageSize, $disposition);
$this->moduleHandler
->alter('pdf_generator_pre_render', $this->dompdf);
$this->dompdf
->render();
$response = new Response();
$response
->setContent($this->dompdf
->output());
$response->headers
->set('Content-Type', 'application/pdf');
if (is_array($title)) {
$title = $this->renderer
->render($title);
}
$filename = strtolower(trim(preg_replace('#\\W+#', '_', $title), '_'));
$response->headers
->set('Content-Disposition', "attachment; filename={$filename}.pdf");
return $response;
}
public function pageSizes() {
$sizes = array_keys(CPDF::$PAPER_SIZES);
return array_combine($sizes, array_map('ucfirst', $sizes));
}
public function availableDisposition() {
return [
'portrait' => $this
->t('Portrait'),
'landscape' => $this
->t('Landscape'),
];
}
}