Categories
React Answers

How to Download PDF in React.js?

Spread the love

To download PDF with React.js, we can add the download attribute to an anchor element.

For instance, we can write:

import React from "react";

export default function App() {
  return (
    <div>
      <a
        href="https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf"
        download
      >
        Click to download
      </a>
    </div>
  );
}

We just add the download prop to do the download.

If we don’t want to use an anchor element, we can also use the file-saver package to download our file.

To install it, we run:

npm i file-saver

Then we can call the saveAs function from the package by writing:

import React from "react";
import { saveAs } from "file-saver";

export default function App() {
  const saveFile = () => {
    saveAs(
      "https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf",
      "example.pdf"
    );
  };
  return (
    <div>
      <button onClick={saveFile}>download</button>
    </div>
  );
}

The first argument is the URL to download and the 2nd argument is the file name of the downloaded file.

By John Au-Yeung

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

Leave a Reply

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