Programming & Development / March 27, 2025

Handling Base64-Encoded PDFs in React

React base64 PDF download PDF React PDF viewer iframe react-pdf

When working with PDFs in a React application, there might be situations where the PDF is encoded as a base64 string. This can happen when a PDF is stored or received as base64 data, and you need to display it or allow the user to download it. In this tutorial, we’ll explore how to decode and display a base64-encoded PDF in React, as well as how to download it when a button is clicked.

💻 Displaying a Base64 PDF in React

To display a base64-encoded PDF in React, you can use the HTML iframe element or a more advanced React library like react-pdf. Here, we will go over both approaches.

Approach 1: Using an iframe

If you want a simple solution, you can use an <iframe> element to display the base64 PDF.

Step 1: Create the PDFViewer Component

This component receives a base64-encoded string and renders the PDF using an iframe.

jsx

import React, { useState, useEffect } from 'react';

const PDFViewer = ({ base64Data }) => {
  const [pdfData, setPdfData] = useState('');

  useEffect(() => {
    if (base64Data) {
      setPdfData(`data:application/pdf;base64,${base64Data}`);
    }
  }, [base64Data]);

  return (
    <div>
      {pdfData ? (
        <iframe
          src={pdfData}
          title="PDF Viewer"
          width="100%"
          height="600px"
        />
      ) : (
        <p>Loading PDF...</p>
      )}
    </div>
  );
};

export default PDFViewer;

Step 2: Use the PDFViewer Component

In your main application, pass the base64-encoded PDF string to the PDFViewer component.

jsx

import React from 'react';
import ReactDOM from 'react-dom';
import PDFViewer from './PDFViewer';

// Your base64-encoded PDF string
const base64PDF = 'JVBERi0xLjQKJcfsj6IK...';  // shortened for brevity

ReactDOM.render(
  <PDFViewer base64Data={base64PDF} />,
  document.getElementById('root')
);

Approach 2: Using react-pdf Library

For a more feature-rich solution, you can use the react-pdf library, which allows for more control over rendering PDFs (such as rendering specific pages, zooming, etc.).

Step 1: Install react-pdf

First, install the library:

bash

npm install @react-pdf-viewer --save

Step 2: Set Up the PDFViewer Component with react-pdf

Here’s how you can modify the PDFViewer component to use react-pdf:

jsx

import React, { useState, useEffect } from 'react';
import { Document, Page } from '@react-pdf-viewer';

const PDFViewer = ({ base64Data }) => {
  const [pdfData, setPdfData] = useState(null);

  useEffect(() => {
    if (base64Data) {
      const pdfDataUri = `data:application/pdf;base64,${base64Data}`;
      setPdfData(pdfDataUri);
    }
  }, [base64Data]);

  return (
    <div>
      {pdfData ? (
        <Document file={pdfData}>
          <Page pageNumber={1} />
        </Document>
      ) : (
        <p>Loading PDF...</p>
      )}
    </div>
  );
};

export default PDFViewer;

This approach gives you greater flexibility, such as rendering specific pages and adding more advanced controls.

💾 Downloading a Base64 PDF in React

In some cases, you might want to allow users to download a base64-encoded PDF. Here’s how you can implement a download button to trigger the PDF download.

Step 1: Create a DownloadPDFButton Component

This component will allow users to download the PDF when clicked.

jsx

import React from 'react';

const DownloadPDFButton = ({ base64Data, fileName }) => {

  const downloadPDF = () => {
    const linkSource = `data:application/pdf;base64,${base64Data}`;
    const downloadLink = document.createElement('a');

    downloadLink.href = linkSource;
    downloadLink.download = fileName;  // You can customize the file name
    downloadLink.click();
  };

  return (
    <button onClick={downloadPDF}>Download PDF</button>
  );
};

export default DownloadPDFButton;

Step 2: Use the DownloadPDFButton Component

Pass the base64-encoded PDF string and the desired file name to the DownloadPDFButton component.

jsx

import React from 'react';
import ReactDOM from 'react-dom';
import DownloadPDFButton from './DownloadPDFButton';

// Your base64-encoded PDF string
const base64PDF = 'JVBERi0xLjQKJcfsj6IK...';  // shortened for brevity

ReactDOM.render(
  <DownloadPDFButton base64Data={base64PDF} fileName="example.pdf" />,
  document.getElementById('root')
);

How It Works:

  • Creating a Download Link: The function creates a link (<a>) element, sets its href attribute to the base64-encoded PDF, and assigns a download attribute with the specified file name.
  • Triggering the Download: The click() method is called on the link to programmatically trigger the download without navigating to a new page or opening a new window.

🎯 Summary

In this tutorial, we covered how to work with base64-encoded PDFs in React. You can display the PDF using either an <iframe> or a more advanced library like react-pdf. Additionally, we discussed how to implement a download button that allows users to download the PDF as a file.

  • Displaying PDFs: Use an iframe or react-pdf for more control and features.
  • Downloading PDFs: Trigger the download by creating a link with a data URI and using the download attribute.

These techniques will help you efficiently manage and present base64-encoded PDFs in your React applications.


Comments

No comments yet

Add a new Comment

NUHMAN.COM

Information Technology website for Programming & Development, Web Design & UX/UI, Startups & Innovation, Gadgets & Consumer Tech, Cloud Computing & Enterprise Tech, Cybersecurity, Artificial Intelligence (AI) & Machine Learning (ML), Gaming Technology, Mobile Development, Tech News & Trends, Open Source & Linux, Data Science & Analytics

Categories

Tags

©{" "} Nuhmans.com . All Rights Reserved. Designed by{" "} HTML Codex