Sometimes, we want to generate a PDF file from React components.
In this article, we’ll look at how to generate a PDF file from React components.
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.
 
		
9 replies on “How to Generate a PDF File from React Components?”
Any advice on how to change the styles of the printout? The functionality works perfectly, but it’s white lettering over a white bg.
Try changing the styles of the component.
js-pdf do not exist
Did anyone make it work with styled-components?
I TRIED USING THE METHOD, BUT IT JUST DOWNLOADS A BLANK PAGE, PLEASE WHAT AM I MISSING
It might not work if you have dynamic logic in your component.
I also tried to use a simple h2 tag, but it still downloads a blank page
instead passing just
Foo, try passing<Foo />the component to renderToStaticMarkup method.This https://udithajanadara.medium.com/export-react-component-as-a-pdf-5afba8ba02ee explains how to export your component inheriting its style.