Blog
Convert HTML to PDF with Javascript and React
Intro
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 portal.api2pdf.com. It only takes a minute.
import React, { Component } from 'react'; | |
class HtmlToPdf extends Component { | |
convertHtmlToPdf(e) { | |
fetch('https://v2018.api2pdf.com/chrome/html', { | |
method: 'post', | |
headers: { | |
'Accept': 'application/json', | |
'Content-Type': 'application/json', | |
'Authorization': 'YOUR-API-KEY' //Get your API key from https://portal.api2pdf.com | |
}, | |
body: JSON.stringify({html: '<p>hello world from reactjs</p>', inlinePdf: true, fileName: 'test.pdf' }) | |
}).then(res=>res.json()) | |
.then(res => console.log(res.pdf)); | |
} | |
render() { | |
return ( | |
<div className="App"> | |
<button onClick={this.convertHtmlToPdf.bind(this)}>Generate Pdf</button> | |
</div> | |
); | |
} | |
} | |
export default HtmlToPdf; |
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:
Note
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.