Sometimes, we want to generate a PDF file from React components with JavaScript.
In this article, we’ll look at how to generate a PDF file from React components with JavaScript.
Generate a PDF File from React Components
To generate a PDF file from React components, we can use the js-pdf
and react-dom/server
libraries.
To install js-pdf
, we run:
npm i js-pdf
react-dom/server
comes with projects created by Create React App by default.
To use it, we write:
import React from "react";
import ReactDOMServer from "react-dom/server";
import jsPDF from "jspdf";
const doc = new jsPDF();
const Foo = <b>foo</b>;
export default function App() {
const save = () => {
doc.html(ReactDOMServer.renderToStaticMarkup(Foo), {
callback: () => {
doc.save("myDocument.pdf");
}
});
};
return (
<div>
<button onClick={save}>save</button>
</div>
);
}
We create a new instance of the jsPDF
constructor and assign it to doc
.
Then we have the Foo
JSX expression which renders some bold text.
Next, in App
, we create the save
function that calls the doc.html
method with the HTML string created by renderToStaticMarkup
method.
And then we set the callback
property to a function that calls docs.save
with the file name to save the rendered HTML version of Foo
as a PDF.
Conclusion
To generate a PDF file from React components, we can use the js-pdf
and react-dom/server
libraries.