I am currently testing DOMPDF and got it working quite nice for my purposes, including CSS styling, displaying content fetched from a mysql database etc.
Now I tried to use some Javascript, but it doesn't work. I used a very simple script for testing:
HTML somewhere on the page:
<div id='mydiv1' style='width: 100%;height:20px;background:#ddd;'></div>
The JS (just above the closing </body>
tag (but I also tried it right after the opening <body>
tag):
<script>
document.getElementById('mydiv1').innerHTML = 'this is a test';
</script>
When I echo this page in the browser (I am echoing a variable which contains the plete HTML/PHP page), that text appears in the DIV. When I put the same variable in DOMPDF's loadHtml
and then render and output it, the script-generated text doesn't appear in the PDF (the rest of the page does).
So my question is: Is there any way to make Javascript work in DOMPDF-generated PDFs?
I am currently testing DOMPDF and got it working quite nice for my purposes, including CSS styling, displaying content fetched from a mysql database etc.
Now I tried to use some Javascript, but it doesn't work. I used a very simple script for testing:
HTML somewhere on the page:
<div id='mydiv1' style='width: 100%;height:20px;background:#ddd;'></div>
The JS (just above the closing </body>
tag (but I also tried it right after the opening <body>
tag):
<script>
document.getElementById('mydiv1').innerHTML = 'this is a test';
</script>
When I echo this page in the browser (I am echoing a variable which contains the plete HTML/PHP page), that text appears in the DIV. When I put the same variable in DOMPDF's loadHtml
and then render and output it, the script-generated text doesn't appear in the PDF (the rest of the page does).
So my question is: Is there any way to make Javascript work in DOMPDF-generated PDFs?
Share Improve this question asked Apr 4, 2017 at 22:50 JohannesJohannes 67.8k22 gold badges84 silver badges139 bronze badges 1- 1 This reply to Execute javascript in PHP uses HtmlUnit to generate HTML from a web page and may be of interest. – traktor Commented Apr 4, 2017 at 23:49
2 Answers
Reset to default 2Unfortunately, DOMPDF doesn't support javascript. You may consider looking at something like phantomjs, which can be used to save pdf files, as well.
There is a DomPDF option to turn on inline javascript:
$isJavascriptEnabled = true;
Heres an example of how to use the DomPDF options:
$HTML = <<<HTML
!DOCTYPE html>
<html>
<head>
<body>
some html
</body>
<script> somejs </script>
</head>
</html>
HTML;
require_once "sites/all/libraries/dompdf/autoload.inc.php";
use Dompdf\Dompdf;
use Dompdf\Options;
$options = new Options();
$options->set('isJavascriptEnabled', TRUE);
$dompdf = new Dompdf($options);
$dompdf->load_html($HTML);
$dompdf->setPaper('A4', 'portrait');
$dompdf->render();
$dompdf->stream('blah.pdf');
I took this from DomPDF's options page: https://github./dompdf/dompdf/blob/master/src/Options.php