Vishnu Sharma Vishnu Sharma - 6 months ago 105
PHP Question

Execute Javascript in PDF

I am converting the html to pdf using wkhtmltopdf and conversion is working completely fine using below code:

shell_exec('wkhtmltopdf Haryana.pdf');

Now, suppose there are some DIV's hidden in
file. Say,


<div style="display:none;">Hello</div>

so, the word 'Hello' will also not print in the converted PDF(which is obvious).

What I need to do is to show all the hidden text to the converted PDF.

What I tried till now is, created a JS file say
which has code to show all the hidden DIV's

var elements = document.getElementsByTagName('DIV')
for (var i = 0; i < elements.length; i++){
if (elements[i].style.display == 'none') {
elements[i].style.display = 'block';

and also applying this JS file while creating a PDF like below:

shell_exec('wkhtmltopdf --enable-javascript --run-script /var/www/html/search/external-js.js Haryana.pdf');

Still, PDF is converting fine but hidden text are not visible.

Please help me to show all the hidden text in pdf. I hope i am able to clear the question.

Note: I can't make changes in the html files because we have thousands of files like this.

UPDATE : When added
option and running the following code in putty

wkhtmltopdf --debug-javascript --enable-javascript --run-script /var/www/html/search/external-js.js Haryana.pdf;

i am getting following output:

Loading pages (1/6)
Warning: undefined:0 SyntaxError: Invalid flags supplied to RegExp constructor.
Counting pages (2/6)
Resolving links (4/6)
Loading headers and footers (5/6)
Printing pages (6/6)

which have some warning. I am sure this warning is coming because of
--run-script /var/www/html/search/external-js.js
but why? I have added this as per the official documentation.

I am stuck with this...can anybody please help me out?


Finally, after done lots of R&D I get the solution :-). I was on the right track and what i did was instead of passing the JS script url, i just passed the whole script content to wkhtmltopdf.

Here is the code:

$script = 'var elements = document.getElementsByTagName(\'DIV\');
           for (var i = 0; i < elements.length; i++)
            if (elements[i].style.display == \'none\') 
            elements[i].style.display = \'block\';

shell_exec('wkhtmltopdf --run-script "'.$script.'" Haryana.pdf');

That's it :-)

I feel may be some other user face same problem in future so, i am posting this as answer.