Enable injecting print CSS into document

This commit is contained in:
Benjamin Beganović 2020-08-25 10:51:49 +02:00
parent ff2f8c8905
commit 234beee61b
3 changed files with 83 additions and 14 deletions

View File

@ -32,9 +32,15 @@ class PdfMaker
'<?xml version="1.0" encoding="utf-8" standalone="yes"??>' => '',
];
private $options;
public function __construct(array $data)
{
$this->data = $data;
if (array_key_exists('options', $data)) {
$this->options = $data['options'];
}
}
public function design(string $design)
@ -61,6 +67,8 @@ class PdfMaker
public function getCompiledHTML($final = false)
{
$this->processOptions();
if ($final) {
$html = $this->document->saveXML();

View File

@ -47,7 +47,11 @@ trait PdfMakerUtilities
public function updateElementProperties(array $elements)
{
foreach ($elements as $element) {
if (isset($element['tag'])) {
$node = $this->document->getElementsByTagName($element['tag'])->item(0);
} else {
$node = $this->document->getElementById($element['id']);
}
if (isset($element['properties'])) {
foreach ($element['properties'] as $property => $value) {
@ -104,7 +108,6 @@ trait PdfMakerUtilities
public function createElementContent($element, $children)
{
foreach ($children as $child) {
$_child = $this->document->createElement($child['element'], $child['content']);
$element->appendChild($_child);
@ -149,4 +152,32 @@ trait PdfMakerUtilities
return $element;
}
public function processOptions()
{
if (isset($this->options['print_css']) && $this->options['print_css']) {
$this->insertPrintCSS();
}
}
public function insertPrintCSS()
{
$css = '.page-header,.page-header-space{height:100px}.page-footer,.page-footer-space{height:50px}.page-footer{position:fixed;bottom:0;width:100%;border-top:1px solid #000;background:#ff0}.page-header{position:fixed;top:0;width:100%;border-bottom:1px solid #000;background:#ff0}.page{page-break-after:always}@page{margin:20mm}@media print{thead{display:table-header-group}tfoot{display:table-footer-group}button{display:none}body{margin:0}}';
$css_node = $this->document->createTextNode($css);
$style = $this->document->getElementsByTagName('style')->item(0);
if ($style) {
return $style->appendChild($css_node);
}
$head = $this->document->getElementsByTagName('head')->item(0);
if ($head) {
$style_node = $this->document->createElement('style', $css);
return $head->appendChild($style_node);
}
}
}

View File

@ -356,4 +356,34 @@ class PdfMakerTest extends TestCase
$this->assertStringContainsString('id="product-table"', $html);
}
public function testWrapperHTMLWorks()
{
$design = new ExampleDesign();
$html = $design
->document()
->getSectionHTML('product-table');
$state = [
'template' => [],
'variables' => [
'labels' => [],
'values' => [],
],
'options' => [
'print_css' => true,
],
];
$maker = new PdfMaker($state);
$maker
->design(ExampleDesign::class)
->build();
exec('echo "" > storage/logs/laravel.log');
info($maker->getCompiledHTML(true));
}
}