Search code examples
phpreactjswkhtmltopdf

Reactjs generating pdf using phpwkhtmltopdf


I am new to reactJs. I created a component to generate a report and I am pulling it as node module to my php application, there I created a smarty template(.tpl) in that I'm using the main.version.js, main.version.css files in the build and passing the required data to the component by data attributes and I'm able to view the report. now the problem is I have to generate a pdf when we click print hyper link from the browser. For this we are using wkhtmltopdf converter using which we are able to merge different pdfs and generating a single pdf. Here I'm getting a blank page. If I give some text that is working fine but not working for the react component content. It is failing for this react component. Please guide me in the right direction.

<html>
<head>
    <link href="{$baseUrl}node_modules/react-component-report/build/main.xxx.css" rel="stylesheet" type="text/css"/>
</head>
<body>
    <div id="root" data-title="Hello" data-name="World" data-reportcontent='{literal}{"users": [11,5],"dates": "2017-09-17" }{/literal}'></div>
    <script src="{$baseUrl}node_modules/react-component-report/build/main.xxx.js"></script>
</body>
</html>

Solution

  • If I understand correctly wktohtml is a command line utility, and you are pointing it at the url of your webpage, which contains react code. You are trying to have that command-line utility render off the react generated page to a PDF.

    If this is correct, I think the problem is that react is a client-side language, so it requires javascript to actually render.

    You can see the html your script is trying to render by loading the same url with curl from the command line. You will see that it just contains some script tags and an empty wrapper where your app would mount.

    There are ways to server render react.js using node.js, or you could look at other methods of generating a PDF. This library looks like it might be able to let you generate the PDF from the browser.

    Some more examples of how this problem can be solved can be found here: http://blog.stahlmandesign.com/export-html-to-pdf-how-hard-can-it-be/