Categories
React Answers

How to Generate a PDF File from React Components?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

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.

Leave a Reply

Your email address will not be published. Required fields are marked *