PDF TOOLS

How to Convert HTML to PDF in React (Developer Tutorial)

Published May 16, 2023
Share:

Converting HTML to PDF in React has become an essential feature for many web applications. Whether you are building an invoicing system, report generator, or just need to share information in a universally accepted format, PDF generation is crucial. In this article, we will explore how to create and style PDF files in your React application by converting HTML to PDF using popular libraries.

Before diving into the process of converting HTML to PDF, let's discuss some popular libraries that you can use for PDF generation in your React applications:

  1. React-pdf: A powerful library for creating PDF documents in React applications. It supports various styling options and can create complex, multipage PDFs with ease.
  2. jsPDF: A widely-used JavaScript library for generating PDF files on the fly. It offers a wide range of features, including text styling, image embedding, and more.
  3. html2canvas: This library allows you to capture a screenshot of an HTML element and convert it to a canvas object, which can then be converted to a PDF using other libraries like jsPDF.

Prerequisites for Converting HTML to PDF in React

Familiarity with React and its ecosystem

Before diving into HTML to PDF conversion, it is crucial to have a solid understanding of React. This includes knowledge of JSX, state management, component lifecycles, and hooks.

Understanding of HTML, CSS, and JavaScript

A strong foundation in HTML, CSS, and JavaScript is essential for working with the React-pdf library. This includes knowledge of HTML elements and attributes, CSS styling and selectors, and JavaScript fundamentals such as variables, functions, and loops.

Getting Started with a React Application

Before we proceed with converting HTML to PDF in React, let's quickly go over how to create a new React application using the popular create-react-app CLI tool. This will serve as the foundation for our PDF generation example.

Step 1 Install Node.js

Ensure that you have Node.js installed on your machine. You can download the latest version of Node.js from the official website.

Step 2 Install create-react-app

create-react-app is a widely-used CLI tool for generating React applications. Install it globally using the following command:

npm install -g create-react-app

How to Convert HTML to PDF in React (Developer Tutorial): Figure 1 - Create react app

Step 3 Create a New React Application

Now that you have create-react-app installed, you can create a new React application with the following command:

create-react-app my-pdf-app

How to Convert HTML to PDF in React (Developer Tutorial): Figure 2 - Creating a new react app

This command will generate a new React application in a folder called my-pdf-app. Move into the newly created directory:

cd my-pdf-app

Step 4 Start the Development Server

To start the development server and see your new React application in action, run the following command:

npm start

How to Convert HTML to PDF in React (Developer Tutorial): Figure 3 - Live react app running on localhost

Step 5 Implementing PDF Generation

Now that you have a React application set up, you can follow the steps outlined in the previous sections of this article to implement HTML to PDF React conversion using popular libraries like React-pdf.

Introducing React-pdf Library

React-pdf is a popular library designed specifically for React applications, offering seamless integration with the React ecosystem. Some of its key features include support for inline and external CSS, multi-page PDF generation, advanced styling, and compatibility with server-side rendering (SSR).

Creating PDF Files with React-pdf

In this section, we will focus on using React-pdf for creating PDF files in a React application. To begin, you'll need to install the React-pdf package:

npm install --save @React-pdf/renderer

How to Convert HTML to PDF in React (Developer Tutorial): Figure 4 - React-pdf package

Once installed, you can create a new React component to define the structure of your PDF document:

    import React from "react";
    import {
      Document,
      Page,
      Text,
      View,
      StyleSheet,
      Image,
      Font,
    } from "@React-pdf/renderer";
    const invoiceData = {
      sender: {
        name: "John Doe",
        address: "123 Main Street",
        city: "New York",
        state: "NY",
        zip: "10001",
      },
      recipient: {
        name: "Jane Smith",
        address: "456 Elm Street",
        city: "San Francisco",
        state: "CA",
        zip: "94107",
      },
      items: [
        { description: "Item 1", quantity: 2, unitPrice: 10 },
        { description: "Item 2", quantity: 3, unitPrice: 15 },
        { description: "Item 3", quantity: 1, unitPrice: 20 },
      ],
      invoiceNumber: "INV-123456",
      date: "April 26, 2023",
    };
    const styles = StyleSheet.create({
      page: {
        backgroundColor: "#FFF",
        padding: 30,
      },
      header: {
        fontSize: 24,
        textAlign: "center",
        marginBottom: 30,
      },
      sender: {
        marginBottom: 20,
      },
      recipient: {
        marginBottom: 30,
      },
      addressLine: {
        fontSize: 12,
        marginBottom: 2,
      },
      itemsTable: {
        display: "table",
        width: "100%",
        borderStyle: "solid",
        borderWidth: 1,
        borderRightWidth: 0,
        borderBottomWidth: 0,
      },
      tableRow: {
        margin: "auto",
        flexDirection: "row",
      },
      tableColHeader: {
        width: "25%",
        borderStyle: "solid",
        borderWidth: 1,
        borderLeftWidth: 0,
        borderTopWidth: 0,
        backgroundColor: "#F0F0F0",
      },
      tableCol: {
        width: "25%",
        borderStyle: "solid",
        borderWidth: 1,
        borderLeftWidth: 0,
        borderTopWidth: 0,
      },
      tableCell: {
        fontSize: 12,
        textAlign: "center",
        padding: 5,
      },
      total: {
        marginTop: 20,
        textAlign: "right",
      },
      totalLabel: {
        fontSize: 14,
        fontWeight: "bold",
      },
      totalValue: {
        fontSize: 14,
      },
    });

    const InvoiceDocument = () => {
      const totalAmount = invoiceData.items.reduce(
        (total, item) => total + item.quantity * item.unitPrice,
        0
      );

      return (

            Invoice

              {invoiceData.sender.name}
              {invoiceData.sender.address}

                {invoiceData.sender.city}, {invoiceData.sender.state}{" "}
                {invoiceData.sender.zip}

              {invoiceData.recipient.name}

                {invoiceData.recipient.address}

                {invoiceData.recipient.city}, {invoiceData.recipient.state}{" "}
                {invoiceData.recipient.zip}

                  Description

                  Quantity

                  Unit Price

                  Amount

              {invoiceData.items.map((item, index) => (

                    {item.description}

                    {item.quantity}

                      {item.unitPrice.toFixed(2)}

                      {(item.quantity * item.unitPrice).toFixed(2)}

              ))}

              Total:
              ${totalAmount.toFixed(2)}

      );
    };

    export default InvoiceDocument;
JAVASCRIPT

Now, you can use the PDFDownloadLink component from React-pdf to download the generated PDF file:

    import React from 'react';
    import { PDFDownloadLink } from '@React-pdf/renderer';
    import InvoiceDocument from './InvoiceDocument';
    import './App.css';

    const App = () => (

          {({ blob, url, loading, error }) =>
            loading ? 'Loading document...' : 'Download Invoice'
          }

    );

    export default App;
JAVASCRIPT

Now add some CSS Styles in App.css for a custom UI:


    .app-container {
      display: flex;
      justify-content: center;
      align-items: center;
      min-height: 100vh;
      background-color: #d1e8ff;
    }

    .download-button {
      display: inline-block;
      background-color: #5a8fd5;
      color: #fff;
      font-size: 18px;
      font-weight: bold;
      padding: 12px 24px;
      border-radius: 4px;
      text-decoration: none;
      cursor: pointer;
      transition: background-color 0.3s ease;
    }

    .download-button:hover {
      background-color: #3a68b7;
    } 

Open localhost:3000 in your browser.

How to Convert HTML to PDF in React (Developer Tutorial): Figure 5 - React PDF running in localhost

When you click on the Download button, the PDF file will be downloaded.

How to Convert HTML to PDF in React (Developer Tutorial): Figure 6 - Downloaded invoice

Here is the output of the PDF file from HTML document:

How to Convert HTML to PDF in React (Developer Tutorial): Figure 7 - Document Output

Styling your PDF Files

The React-pdf library supports a wide range of styling options, similar to CSS. Here are some common styling properties you can use to customize the appearance of your PDF files:

  • color: Sets the text color.
  • fontSize: Sets the font size of the text.
  • fontFamily: Sets the font family of the text.
  • textAlign: Sets the text alignment (e.g., 'left', 'right', 'center', or 'justify').
  • margin: Sets the margin around an element.
  • padding: Sets the padding inside an element.
  • border: Sets the border around an element.
  • backgroundColor: Sets the background color of an element.

Alternate PDF Library for React Developers

IronPDF for Node.js is an excellent alternative for converting HTML to PDF in react. Developed by IronSoftware, it is a powerful library that allows developers to generate and manipulate PDF documents directly from their Node.js applications. One of the standout features of IronPDF is its ability to handle JavaScript execution within HTML content during PDF generation, enabling dynamic and interactive PDF creation.

With support for various platforms including Windows, MacOS, Linux, Docker, and cloud platforms like Azure and AWS, IronPDF ensures cross-platform compatibility. Its user-friendly API allows developers to quickly integrate PDF generation and manipulation into their Node.js projects.

React is a JavaScript library for building user interfaces, and since IronPDF is built for Node.js, you can integrate IronPDF into your React applications by utilizing its Node.js API.

Here's a an outline of how you can use IronPDF with React:

  1. Install IronPDF: You can install IronPDF in your React project using npm or yarn.

    npm install @ironsoftware/ironpdf
  2. Integrate with React Components: You can create React components that utilize IronPDF to generate and manipulate PDFs. For example, you can have a component that takes HTML content as input and converts it to a PDF using IronPDF's API.

    import React from 'react';
    import { PdfDocument } from '@ironsoftware/ironpdf';
    
    const HTMLToPDFComponent = () => {
      const convertHTMLToPDF = async (htmlContent) => {
          try {
              const pdf = await PdfDocument.fromHtml(htmlContent);
              await pdf.saveAs('generated_pdf.pdf');
              alert('PDF generated successfully!');
          } catch (error) {
              console.error('Error generating PDF:', error);
          }
      };
    
      return (
          <div>
              {/* Input HTML content */}
              <textarea onChange={(e) => convertHTMLToPDF(e.target.value)} />
          </div>
      );
    };
    
    export default HTMLToPDFComponent;
    JAVASCRIPT
  3. Handle PDF Generation: Utilize IronPDF's functionality within your React components to handle PDF generation, manipulation, and saving. You can use IronPDF's methods for converting HTML strings, URLs, or images to PDFs.
  4. Render PDFs: Once you've generated PDFs using IronPDF, you can render them within your React application using appropriate components or libraries for displaying PDF documents.

    import React from 'react';
    
    const PDFViewerComponent = () => {
      return (
          <div>
              {/* Render PDF using appropriate component or library */}
              <iframe src="generated_pdf.pdf" width="100%" height="600px" title="PDF Viewer" />
          </div>
      );
    };
    
    export default PDFViewerComponent;
    JAVASCRIPT

With IronPDF, developers can efficiently generate professional-grade PDF documents from various sources, customize them to meet their specific requirements, and seamlessly integrate PDF generation capabilities into their .NET applications. IronPDF also supports advanced features such as CSS, JavaScript, and custom fonts, ensuring that your generated PDF files will match your application's design and requirements.

Conclusion

In this article, we have covered the process of converting HTML to PDF in React using the React-pdf library. We discussed popular libraries for PDF generation, how to create and style PDF files using React-pdf, and additional options for generating more complex PDF documents.

By following this guide, you should now have a solid understanding of how to generate PDF files in your React applications, allowing you to generate high quality PDF's and meet the needs of various use cases.

IronPDF offers a free trial, which allows you to test the library and determine if it meets your needs before committing to a purchase. After the trial period, IronPDF licenses start from $749, which includes priority support and updates. Additionally, is also available for other languages like C# .NET, Java and Python. Download the library from here and give it a try.

< PREVIOUS
How to Print PDF File in JavaScript

Ready to get started? Version: 2024.9 just released

Free npm Install View Licenses >