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.
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 portal.api2pdf.com. 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.
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:
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: create pdf with react, doc to pdf react, generate pdf with react, html to pdf client side, html to pdf react, html to pdf reactjs, react component pdf, reactjs headless chrome, reactjs libreoffice, reactjs wkhtmltopdf, url to pdf javascript, url to pdf reactjs, web page to pdf javascript, web page to pdf reactjs, word to pdf reactComments are closed.