Type to generate custom UI components with AI

Type to generate UI components from text

OR

Browse thousands of MUI, Tailwind, React components that are fully customizable and responsive.

Explore Components

React PDF: A Step-by-Step Guide on How to Generate PDFs

In this step-by-step guide, we delve into the world of React PDF, exploring how to render and generate dynamic Portable Document Format (PDF) files within a React application.

By the conclusion of this article, you will acquire the knowledge needed to develop a PDF generator, as demonstrated below (See the live demo here).

The article provides a comprehensive breakdown of various methods and third-party libraries, including but not limited to react-pdf, react-pdf-viewer, React PDF (Renderer), and PDFme.

Whether you need to display an existing document file in your React application or create a new one from scratch, this guide has got you covered.

Let’s dive in!

What is a PDF document?

A PDF (Portable Document Format) is a universal file format developed by Adobe. It maintains the integrity of a document’s formatting, fonts, images, and layout, irrespective of the software or hardware used to open or print it.

PDF files, which can house a combination of text and images, can be generated from a variety of sources, including word processors, desktop publishing applications, or even scanned documents.

Working with PDF documents in React

Working with PDFs in React can involve creating a document using code or displaying an existing PDF document within a codebase. This is typically accomplished through third-party libraries, as the functionality is not readily available in standard web APIs.

Give Purecode AI a try today to instantly generate thousands of customizable, styled Bootstrap and JavaScript components to accelerate your web development projects.

Setting up React Application

We’re going to make use of Next.js, a React framework, follow the guide below to set up a Next.js Application.

Step 1: Run the command below in your terminal to bootstrap a new Next.js app, called pdf-app-playground.

npx create-next-app pdf-app-playground

Step 2: Select the options below from the terminal prompts and wait for the installation to be completed.

Then, Step 3: After a successful installation, run the command below to navigate into the newly created folder.

cd pdf-app-playground

Step 4: Open up the directory in your preferred code editor. If you’re using Visual Studio Code (VSCode), you can easily open the folder by entering the command below in your terminal:

code .

Step 5: Start your server by running the following command in your terminal:

yarn dev

After successfully starting the server, it will be accessible on port http://localhost:3000 or any available port on your computer.

Your screen should display a webpage similar to the one shown below:

Step 6: Remove other CSS declarations and update your globals.css file with the following.

@tailwind base;
@tailwind components;
@tailwind utilities;

Step 7: Update the /page.tsx with the following code:

import Link from "next/link";

export default function Home() {
  return (
    <main className='flex flex-col items-center text-center justify-center gap-5 min-h-screen px-3'>
      <h2 className='text-xl'>Select a playground demo below 👇🏽</h2>
      <nav className='flex flex-col md:flex-row justify-center items-center gap-3 pt-3'>
        <Link
          href='/view-pdf-using-iframe'
          className='border border-slate-800 px-3 py-2 hover:bg-slate-50 font-medium text-sm sm:text-lg'
        >
          View PDF using Iframe
        </Link>
        <Link
          href='/view-pdf-using-react-pdf'
          className='border border-slate-800 px-3 py-2 hover:bg-slate-50 font-medium text-sm sm:text-lg'
        >
          View PDF using React-PDF
        </Link>
        <Link
          href='/create-pdf-using-react-pdf-renderer'
          className='border border-slate-800 px-3 py-2 hover:bg-slate-50 font-medium text-sm sm:text-lg'
        >
          Create PDF using React-PDF-renderer
        </Link>
      </nav>
    </main>
  );
}

Upon successful implementation, your browser should render an output that resembles the following example:

As we progress through this article, we will be developing individual pages corresponding to each route button. These pages will be designed to showcase the specific functionality associated with their respective buttons.

Rendering a PDF file in React

Rendering a PDF file within a React application opens up a realm of possibilities, allowing developers to seamlessly integrate rich and dynamic PDF content into their web experiences.

We’ll explore different ways of rendering PDFs in a React application

Using an Iframe Tag

The easiest method for rendering a PDF in any front-end project is by using the iframe tag. We can display a format file using the JSX iframe tag in React by following the steps below.

1: Add a pdf file to your public folder. You can download one from here.

2: Create a new view-pdf-using-iframe folder inside the app folder.

3: Create a new page.tsx file inside the new folder with the following code.

export default function Home() {
  return (
    <main className='flex min-h-screen flex-col items-center justify-between py-5 px-24'>
      <iframe
        src='codewithunclebigbay.pdf'
        width='500'
        height='300'
        className='w-full min-h-screen'
      />
    </main>
  );
}

Step 4: Click the “View PDF using Iframe” button and you should be redirected to the PDF page as demonstrated below.

You can find the completed code for this article in this repository.

Here are some disadvantages of using an iframe tag to render PDF files:

DisadvantageDescription
Limited controlIframes offer minimal control over the PDF viewer and features like zooming, panning, and text searching. Integration with other UI elements can be challenging.
Styling and layoutStyling the iframe and ensuring seamless integration with the application’s design can be difficult. Responsiveness across devices might also be an issue.
AccessibilityScreen readers and assistive technologies might not effectively handle content within iframes, creating accessibility barriers.
SecurityIframes can introduce security vulnerabilities if not handled carefully, especially when loading content from untrusted sources.
PerformanceIframes can impact performance due to the overhead of loading and rendering content from a separate source, especially for large PDFs or on slower devices.
Cross-origin issuesIf the PDF is hosted on a different domain, cross-origin restrictions might limit interactions with the iframe’s content.
User experienceThe presence of an iframe can disrupt the user experience, especially if scrolling or interactions within the iframe don’t behave as expected within the application’s context.

React Packages for Rendering PDF files in React

In this section, we’ll explore some dedicated React packages that offer advanced features and functionalities for rendering files, providing more versatility and customization options compared to the traditional iframe tag.

React-pdf

react-pdf is a popular library in the React ecosystem that allows developers to render files within React applications. It provides components and utilities to easily display, navigate, and interact with PDF documents using components.

This library enables seamless integration of format files into React-based projects, offering features like page navigation, zooming, and rendering text and images from format file documents.

React-pdf Installation

Step 1: Run the command below to install the react-pdf package in your project.

yarn add react-pdf

Step 2: Since we’re using Next.js, update your next.config.js file with the webpack settings below.

/** @type {import('next').NextConfig} */
const nextConfig = {
  webpack: (config) => {
    config.resolve.alias.canvas = false;
    return config;
  },
};

export default nextConfig;

React-pdf Usage

Step 1: Create a new view-pdf-using-react-pdf folder in the app folder

Step 2: Create a new page.tsx file inside the new folder with the following code.

"use client";

import { useState } from "react";
import { Document, Page } from "react-pdf";
import { pdfjs } from "react-pdf";

import "react-pdf/dist/esm/Page/AnnotationLayer.css";
import "react-pdf/dist/esm/Page/TextLayer.css";

// Import worker
pdfjs.GlobalWorkerOptions.workerSrc = `//unpkg.com/pdfjs-dist@${pdfjs.version}/build/pdf.worker.min.js`;

export default function Home() {
  const [numPages, setNumPages] = useState(0);
  const [currentPageNumber, setCurrentPageNumber] = useState(1);

  function onDocumentLoadSuccess({ numPages }) {
    setNumPages(numPages);
  }

  return (
    <main className='flex flex-col justify-center items-center gap-3 py-5 px-24'>
      <Document
        file='/codewithunclebigbay.pdf'
        onLoadSuccess={onDocumentLoadSuccess}
      >
        <Page
          pageNumber={currentPageNumber}
          renderAnnotationLayer={false}
          renderTextLayer={false}
        />
      </Document>

      <section className='flex justify-center items-center gap-3 mb-10'>
        {currentPageNumber !== 1 ? (
          <button
            className='border border-slate-200 py-1.5 px-2 rounded'
            onClick={() => {
              setCurrentPageNumber(currentPageNumber - 1);
            }}
          >
            Prev
          </button>
        ) : null}
        <p className='text-lg font-medium'>
          Page {currentPageNumber} of {numPages}
        </p>
        {numPages && numPages > currentPageNumber ? (
          <button
            className='border border-slate-200 py-1.5 px-2 rounded'
            onClick={() => {
              setCurrentPageNumber(currentPageNumber + 1);
            }}
          >
            Next
          </button>
        ) : null}
      </section>
    </main>
  );
}

Then, Step 3: Click the “View PDF using React PDF” button and you should be redirected to the PDF page as demonstrated below.

The code is already compatible with multi-page PDFs. Simply replace the current PDF file URL with a multi-page one, and it should function as demonstrated below.

You can find the completed code for this article in this repository.

React-pdf-viewer

react-pdf-viewer is a versatile library designed to render and interact with PDF documents within applications. It offers a wide range of features including displaying PDF files, navigating through pages, zooming in and out, searching for text, and accessing annotations.

This library provides developers with customizable components and hooks, enabling seamless integration of PDF viewing functionality into their React projects while offering a smooth and intuitive user experience for handling documents.

Discover more about the powerful installation process and the versatile basic usage of react-pdf-viewer.

PSPDFKit

PSPDFKit is a comprehensive PDF SDK (Software Development Kit) that enables developers to integrate powerful PDF functionality into their applications. It offers a wide range of features for viewing, annotating, editing, and processing PDF documents across various platforms and devices.

PSPDFKit provides developers with a robust set of tools and APIs to customize and extend PDF capabilities within their applications, ensuring a seamless and efficient user experience for working with PDF

Learn more about the PSPDFKit guide and its features by visiting here.

Creating a PDF file in React

Creating a PDF file in React can be accomplished by leveraging a variety of libraries that have been specifically designed to handle file generation and manipulation within the framework. Two popular options among these libraries are React PDF (Renderer) and PDFme, which we’ll discuss in the next sections.

React Packages for Creating PDF files in React

Below, we’ll delve into exploring a selection of packages specifically designed for generating PDF files. These packages offer a range of features and capabilities to help developers efficiently generate PDF documents within their React applications.

By leveraging these libraries, developers can ensure a seamless and user-friendly experience when working with PDF files, ultimately enhancing the overall functionality of their applications.

React PDF (Renderer)

React PDF (Renderer) is a robust tool that allows you to generate PDF files directly from your React components. You can define the structure and style of your document using familiar syntax, and the library will convert it into a PDF file.

React PDF (Renderer) Installation

Step 1: Run the command below in your terminal to install react-pdf renderer in your app.

yarn add @react-pdf/renderer

React PDF (Renderer) Usage

Step 1: Create a new create-pdf-using-react-pdf-renderer folder in the app folder.

Step 2: Create a new page.tsx file inside the new folder with the following code.

"use client";

import React, { useState } from "react";
import {
  Page,
  Text,
  View,
  Document,
  StyleSheet,
  PDFDownloadLink,
} from "@react-pdf/renderer";

// Create styles
const styles = StyleSheet.create({
  page: {
    padding: "12px",
    height: "100px",
  },
  section: {
    backgroundColor: "#E4E4E4",
    display: "flex",
    flexDirection: "column",
    gap: "12px",
    margin: 10,
    padding: 10,
    flexGrow: 1,
  },
  logo: {
    width: 70,
    height: 70,
    marginTop: "15px",
  },
});

// Create Document Component
const PDFView = ({
  fullname,
  profession,
  yearsOfExperience,
}: {
  fullname: string;
  profession: string;
  yearsOfExperience: string;
}) => (
  <Document>
    <Page size='A4' style={styles.page}>
      <View style={styles.section}>
        <Text>Fullname: {fullname}</Text>
        <Text>Profession: {profession}</Text>
        <Text>Years of Experience: {yearsOfExperience}</Text>
      </View>
    </Page>
  </Document>
);

const PDFCreatorPage = () => {
  const [showPdf, setShowPdf] = useState(false);
  const [fullname, setFullname] = useState("");
  const [profession, setProfession] = useState("");
  const [yearsOfExperience, setYearsOfExperience] = useState("");

  const handleGeneratePDF = () => {
    if (!fullname || !profession || !yearsOfExperience)
      return alert("All fields are required");
    setShowPdf(true);
  };

  const inputStyles = "border border-slate-200 p-1.5 rounded";

  return (
    <div className='flex justify-center items-center min-h-screen'>
      {showPdf ? (
        <div className='flex flex-col items-center'>
          <PDFView
            fullname={fullname}
            profession={profession}
            yearsOfExperience={yearsOfExperience}
          />
          <PDFDownloadLink
            className='text-blue-500 underline'
            document={
              <PDFView
                fullname={fullname}
                profession={profession}
                yearsOfExperience={yearsOfExperience}
              />
            }
            fileName='my_pdf.pdf'
          >
            {({ blob, url, loading, error }) =>
              loading ? "Loading document..." : "Download pdf file"
            }
          </PDFDownloadLink>
        </div>
      ) : (
        <section className='flex flex-col gap-2'>
          <input
            className={inputStyles}
            placeholder='Fullname'
            onChange={(e) => setFullname(e.target.value)}
          />
          <input
            className={inputStyles}
            placeholder='Profession'
            onChange={(e) => setProfession(e.target.value)}
          />
          <input
            className={inputStyles}
            placeholder='Years of experience'
            onChange={(e) => setYearsOfExperience(e.target.value)}
          />
          <button
            onClick={handleGeneratePDF}
            className='bg-slate-700 px-2 py-1.5 rounded text-slate-100'
          >
            Generate PDF
          </button>
        </section>
      )}
    </div>
  );
};

export default PDFCreatorPage;

From the code above, we create a component named PDFCreatorPage that allows users to input their details, generates a document based on the input, and provides a download link for the generated PDF.

Step 4: Click the “Create PDF using React PDF renderer” button and you should be redirected to a page where you can enter some data for the pdf as demonstrated below.

Steps in the demo:

1: Fill out the form fields and select the “Generate PDF” button.

2: You will be directed to the PDF view of the completed form.

3: Click the “Download PDF file” link to open the PDF in your preferred PDF application.

You can find the completed code for this section in this repository and see the live demo here.

Pdfme

PDFme is a free and open-source PDF generator library written in TypeScript. It includes a React-based UI template editor called Designer, which allows users to easily create and modify PDF templates.

The library is designed to be fast and versatile, capable of generating PDFs with no complex operations required.

Additionally, PDF templates are represented as structured JSON data, making them easy to understand and work with. The library can be used both in Node.js and in web browsers, and it offers features such as text, image, and barcode generation. PDFme is developed by the community and is licensed under the MIT license.

Discover more about the PDFme guide and its extensive features by visiting the Getting Started documentation.

You can find the completed code for this article in this repository.

Wrapping Up React PDF

In conclusion, working with PDF files in React is a versatile and necessary skill for many web applications. Whether you’re rendering existing PDFs with libraries like react-pdf and react-pdf-viewer, or creating dynamic ones with React PDF (Renderer) and PDFme, there’s a range of tools at your disposal.

Each library offers unique features and capabilities, but all share the common goal of making PDF manipulation more accessible.

By understanding how to use these tools, you can enhance your web applications and provide more value to your users.

Check out Purecode AI!

I recommend you try out Purecode AI, an AI tool that can generate custom HTML, CSS, and JavaScript components. Here are some of its features:

  • It uses an AI assistant to generate thousands of responsive pre-made components for you.
  • The components come with default styling using CSS, Tailwind CSS, or your own custom styles so you can match your brand’s design.
  • You can easily customize the generated components to suit your specific needs – change colors, spacing, paddings, margins, etc.
  • It generates both the HTML markup and CSS styles for the components, saving you development time.
  • It also includes some JavaScript functionality within the components to make them interactive
Ayodele Samuel Adebayo

Ayodele Samuel Adebayo