Convert HTML to PDF with Javascript and React

December 19th, 2018 / by api2pdf /


In a previous post, we provided guidance with how to generate PDFs from HTML and web pages with javascript and jquery. In this post, we provide a sample React component to convert HTML to PDFs using Headless Chrome or wkhtmltopdf.

Api2Pdf is an HTML to PDF API that allows developers to generate PDFs at massive scale.

HTML to PDF with ReactJs and Client side javascript

API2PDF’s REST documentation is located here. In the sample below we are using the Headless Chrome HTML to PDF endpoint as our sample. However, you can swap this out for wkhtmltopdf as well as LibreOffice (convert Word to PDF, Powerpoint to PDF, etc).

But first, in order to use the code, you need to place your API key in the code where it says ‘YOUR -API-KEY’, which you can acquire by quickly creating an account at It only takes a minute.

The sample just hard codes some basic HTML <p>hello world from reactjs</p> — feel free to put your own HTML in here, or modify the function by passing in your HTML as a parameter and using that.

Advanced Options

In our example, we do not use any advanced options. We pass in inlinePdf: true, which allows the PDF to be opened up directly in a browser window, as well as a test file name, but that’s about it. Api2Pdf supports advanced usage such as landscape mode, custom margins, headers, and footers in the PDF.

For Headless Chrome, you can view all of the advanced options here. You would want to modify the payload to reflect your options. See the documentation for details, but this is a sample that converts the PDF to landscape mode:

{html: ‘<p>hello world from reactjs</p>’, inlinePdf: true, fileName: ‘test.pdf’, options: { landscape: true} }


By putting your API key in a component like this, it is available to the public. Best practice would suggest that you generate PDFs from the server side, hiding your API key. But if you’re in a situation where that is difficult, and you trust your users, generating PDFs from client side may be your only alternative.

Tags: , , , , , , , , , , , , , ,

Comments are closed.