How to download PDF Files in ReactJS?

ReactJS is one of the industry standards for anyone looking to build modern web applications. The program provides an efficient way for programmers to create interactive, efficient, and reusable user interfaces. This tutorial provides guidelines for learning how to download PDF files in ReactJS.

Learning to download PDF files in ReactJS accords programmers a couple of benefits. For starters, you can use the knowledge to save and access documents for offline use. Other benefits also include the ability to share reports, invoices, and downloadable resources. The skillset will enhance the user experience in your projects by providing downloadable content directly in-app.

Prerequisites

Let us cover the list of things you require before embarking on the task at hand.

  • You must first have a basic understanding of ReactJS, duh! There are loads of ReactJS tutorials to help you get a basic understanding of how the program works.
  • You must also have a basic understanding of HTML and JavaScript because ReactJS relies on these programming frameworks.
  • The last thing is having a working React development environment. This means downloading Node.js and Node Package Manager (npm) directly from the official website: (https://nodejs.org/).

You are good to go once you consider the above ReactJS prerequisites.

Setting Up the React Project

This stage requires you to create a React app using the create-react-app command. Ideally, you could also use an existing project instead. You should also install the necessary dependencies like ‘axios’ for fetching files.

Method 1: Downloading PDF Using HTML Anchor Tag

Follow the prompts below to download PDF files using an HTML anchoring tag.

  1. The first step is to create a link to your PDF file using the <a> tag in React.

  2. The next step is to utilize the ‘download’ attribute. This will force the file to download in your project.

The code ought to resemble the snippet below in your ReactJS environment before substituting the required path and file name strings.

import React from 'react';

function DownloadPDF() {
    return (
        <div>
            <h1>Download PDF Example</h1>
            {/ The anchor tag with a download attribute /}
            <a href="/sample.pdf" download="SampleFile.pdf">
                <button>Download PDF</button>
            </a>
        </div>
    );
}

export default DownloadPDF;

Output:

Method 2: Downloading PDF from an API or External URL

You can follow the steps below if you opt for the API/URL method to download PDF files in your application.

  1. Start by using the ‘fetch’ or ‘axios’ command to retrieve the PDF file.

  2. Proceed by converting the response to a Blob and creating a URL.

  3. The last step is triggering the download using JavaScript.

Below is a sample code to illustrate how the API/URL download method works in a RectJS environment.

import React from 'react';

function DownloadPDF() {
    const handleDownload = async () => {
        try {
            // Fetch the PDF from an external URL
            const response = await fetch('example.com/sample.pdf', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/pdf',
                },
            });

            // Convert the response into a blob
            const blob = await response.blob();

          // Create a link element, set its href to the blob URL, and trigger a download
            const url = window.URL.createObjectURL(new Blob([blob]));
            const link = document.createElement('a');
            link.href = url;
            link.setAttribute('download', 'SampleFile.pdf'); // You can specify the file name
            document.body.appendChild(link);
            link.click();
            link.parentNode.removeChild(link); // Clean up after the download
        } catch (error) {
            console.error('Error downloading the PDF:', error);
        }
    };

    return (
        <div>
            <h1>Download PDF from External URL</h1>
            <button onClick={handleDownload}>Download PDF</button>
        </div>
    );
}

export default DownloadPDF;

Output:

Method 3: Using FileSaver.js Library

Let us get right to it by following the steps below to learn how to use the FileSaver.js library.

  1. Step one is to install the ‘file-saver’ function in your ReactJS environment using npm/yarn.

  2. The next step is importing the ‘file-saver’ in the preferred ReactJS project.

  3. Finally, use the ‘saveAs’ command string to implement the download functionality.

You can use the practical example below to understand the benefits of utilizing the ‘file-saver’ functionality for handling file downloads in your projects.

import React from 'react';
import { saveAs } from 'file-saver';
import axios from 'axios';

function DownloadPDF() {
    const handleDownload = async () => {
        try {
            // Fetch the PDF from an external URL using axios
            const response = await axios.get('example.com/sample.pdf', {
                responseType: 'blob', // Important: this tells axios to treat the response as a binary data (blob)
            });

            // Use FileSaver.js to save the file
            saveAs(response.data, 'SampleFile.pdf'); // You can specify the file name here
        } catch (error) {
            console.error('Error downloading the PDF:', error);
        }
    };

    return (
        <div>
            <h1>Download PDF using FileSaver.js</h1>
            <button onClick={handleDownload}>Download PDF</button>
        </div>
    );
}

export default DownloadPDF;

Output:

Handling Errors and Edge Cases

Users can encounter network errors during the file-downloading process. It is prudent to implement safety mechanisms like the ‘.catch()’ function in ‘fetch’ or ‘axios’ to capture and manage network errors.

Consider using a progress indicator to help your users gauge the download process and enhance the user experience. You could also deliberate on chunking large downloads to improve performance and reduce memory usage.

Conclusion

Downloading PDF files in ReactJS is easily doable as evident from the above tutorial. Ensure you test the three methods before deciding which best works for you. Test your project on different browsers to get a feel of how users will experience your React application.