PostRenderSubscriber.php in Entity Print 8.2
File
src/EventSubscriber/PostRenderSubscriber.php
View source
<?php
namespace Drupal\entity_print\EventSubscriber;
use Drupal\Core\Config\ConfigFactoryInterface;
use Drupal\entity_print\Event\PrintEvents;
use Drupal\entity_print\Event\PrintHtmlAlterEvent;
use Masterminds\HTML5;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\RequestStack;
class PostRenderSubscriber implements EventSubscriberInterface {
protected $configFactory;
protected $requestStack;
public function __construct(ConfigFactoryInterface $config_factory, RequestStack $request_stack) {
$this->configFactory = $config_factory;
$this->requestStack = $request_stack;
}
public function postRender(PrintHtmlAlterEvent $event) {
$config = $this->configFactory
->get('entity_print.settings');
if ($config
->get('print_engines.pdf_engine') !== 'phpwkhtmltopdf') {
return;
}
$html_string =& $event
->getHtml();
$html5 = new HTML5();
$document = $html5
->loadHTML($html_string);
$transform = function ($tag, $attribute) use ($document) {
$base_url = $this->requestStack
->getCurrentRequest()
->getSchemeAndHttpHost();
foreach ($document
->getElementsByTagName($tag) as $node) {
$attribute_value = $node
->getAttribute($attribute);
if (mb_substr($attribute_value, 0, 2) === '//') {
$node
->setAttribute($attribute, $base_url . mb_substr($attribute_value, 1));
}
elseif (mb_substr($attribute_value, 0, 1) === '/') {
$node
->setAttribute($attribute, $base_url . $attribute_value);
}
}
};
$transform('link', 'href');
$transform('a', 'href');
$transform('img', 'src');
$html_string = $html5
->saveHTML($document);
}
public static function getSubscribedEvents() {
return [
PrintEvents::POST_RENDER => 'postRender',
];
}
}