Convert a React Component to PDF

As a React developer with over a decade of experience, I’ve often faced the challenge of exporting parts of a web app, especially React components, into PDF files. Whether it’s generating invoices, reports, or shipping labels, the ability to convert UI components directly to PDFs is a highly sought-after feature.

Unfortunately, React doesn’t offer a built-in way to export components as PDFs. But, through my experience, I’ve found several reliable methods that make this process easy and efficient.

In this guide, I’ll share practical techniques to convert React components into PDFs, complete with working code examples tailored for real-world use cases in the USA.

Convert React Components to PDF

PDFs are a universal format ideal for sharing and printing documents without losing layout or formatting. Imagine you’re building an e-commerce dashboard for a US-based retailer, and users need to download order summaries or shipping labels. Embedding PDF generation directly in your React app improves user experience and streamlines workflows.

Method 1: Use the react-to-pdf Library

One of the simplest ways I’ve found to convert React components to PDF is using the react-to-pdf package. It wraps your component and lets you generate a PDF with just a button click.

  • Wrap the React component you want to export inside a ref.
  • Use the react-to-pdf component to trigger PDF generation.
  • The library captures the component’s HTML and converts it into a PDF.

Installation

npm install react-to-pdf

Example: Export a US Shipping Label Component

import React, { useRef } from 'react';
import ReactToPdf from 'react-to-pdf';

const ShippingLabel = () => {
  return (
    <div style={{ padding: 20, border: '1px solid #000', width: 400 }}>
      <h2>Shipping Label</h2>
      <p><strong>Sender:</strong> 123 Main St, Springfield, IL, USA</p>
      <p><strong>Recipient:</strong> 456 Elm St, Austin, TX, USA</p>
      <p><strong>Tracking Number:</strong> 1Z999AA10123456784</p>
    </div>
  );
};

const App = () => {
  const ref = useRef();

  return (
    <div>
      <div ref={ref}>
        <ShippingLabel />
      </div>
      <ReactToPdf targetRef={ref} filename="shipping-label.pdf">
        {({ toPdf }) => (
          <button onClick={toPdf}>Download PDF</button>
        )}
      </ReactToPdf>
    </div>
  );
};

export default App;

You can refer to the screenshot below to see the output.

Convert React Component to PDF
  • Minimal setup and dependencies.
  • Works well for simple components.
  • Supports styling and images within the component.
  • Great for quick PDF generation without server-side processing.

Method 2: Use jsPDF with html2canvas

For more complex scenarios, such as when you need precise control over the PDF output or want to customize the PDF content dynamically, I recommend combining jsPDF and html2canvas.

  • html2canvas takes a screenshot of your React component and converts it into a canvas image.
  • jsPDF then adds this image to a PDF document.
  • You can customize page size, orientation, and add multiple pages if needed.

Installation

npm install jspdf html2canvas

Example: Export a US Invoice Component

import React, { useRef } from 'react';
import jsPDF from 'jspdf';
import html2canvas from 'html2canvas';

const Invoice = () => {
  return (
    <div style={{ width: 600, padding: 20, border: '1px solid black', backgroundColor: '#fff' }}>
      <h1>Invoice</h1>
      <p><strong>Company:</strong> Tech Solutions LLC, San Francisco, CA</p>
      <p><strong>Client:</strong> John Doe, New York, NY</p>
      <table style={{ width: '100%', borderCollapse: 'collapse' }}>
        <thead>
          <tr>
            <th style={{ border: '1px solid black' }}>Item</th>
            <th style={{ border: '1px solid black' }}>Qty</th>
            <th style={{ border: '1px solid black' }}>Price</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td style={{ border: '1px solid black' }}>React Training</td>
            <td style={{ border: '1px solid black' }}>1</td>
            <td style={{ border: '1px solid black' }}>$500</td>
          </tr>
          <tr>
            <td style={{ border: '1px solid black' }}>Consultation</td>
            <td style={{ border: '1px solid black' }}>2</td>
            <td style={{ border: '1px solid black' }}>$300</td>
          </tr>
        </tbody>
      </table>
      <h3>Total: $1100</h3>
    </div>
  );
};

const App = () => {
  const invoiceRef = useRef();

  const generatePdf = () => {
    const input = invoiceRef.current;
    html2canvas(input, { scale: 2 }).then(canvas => {
      const imgData = canvas.toDataURL('image/png');
      const pdf = new jsPDF('p', 'pt', 'a4');
      const imgProps = pdf.getImageProperties(imgData);
      const pdfWidth = pdf.internal.pageSize.getWidth();
      const pdfHeight = (imgProps.height * pdfWidth) / imgProps.width;

      pdf.addImage(imgData, 'PNG', 0, 0, pdfWidth, pdfHeight);
      pdf.save('invoice.pdf');
    });
  };

  return (
    <div>
      <div ref={invoiceRef}>
        <Invoice />
      </div>
      <button onClick={generatePdf}>Download Invoice PDF</button>
    </div>
  );
};

export default App;

You can refer to the screenshot below to see the output.

Convert React Component to PDF in React
  • Handles complex layouts and styles better.
  • You get an exact visual snapshot of your component.
  • Allows customization of PDF pages and content.
  • Ideal for professional documents like invoices or reports.

Method 3: Use react-pdf Library for Dynamic PDFs

If you want to create PDFs using React components but without relying on DOM rendering, react-pdf is a powerful library. It lets you build PDFs with React primitives like <Document>, <Page>, and <Text>.

  • You define your PDF structure using React components.
  • It generates PDFs server-side or client-side without needing the DOM.
  • Great for generating multi-page PDFs dynamically.

Installation

npm install @react-pdf/renderer

Example: Simple PDF Document

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

const styles = StyleSheet.create({
  page: { padding: 30 },
  section: { marginBottom: 10 },
  title: { fontSize: 20, marginBottom: 20 },
});

const MyDocument = () => (
  <Document>
    <Page size="A4" style={styles.page}>
      <View style={styles.section}>
        <Text style={styles.title}>US Employee Report</Text>
        <Text>Name: Jane Smith</Text>
        <Text>Position: Software Engineer</Text>
        <Text>Location: Seattle, WA</Text>
      </View>
    </Page>
  </Document>
);

const App = () => (
  <div>
    <PDFDownloadLink document={<MyDocument />} fileName="employee-report.pdf">
      {({ loading }) => (loading ? 'Loading document...' : 'Download Employee Report')}
    </PDFDownloadLink>
  </div>
);

export default App;
  • You need fully customized PDFs independent of your React UI.
  • Generating multi-page documents with dynamic data.
  • Server-side rendering of PDFs (e.g., with Node.js).

Tips From My Experience

  • If you want a fast and easy solution for simple UI components, start with react-to-pdf.
  • For pixel-perfect exports of your existing UI, html2canvas + jsPDF is the way to go.
  • For complex documents or server-side PDF generation, react-pdf offers the best flexibility.
  • Always test your PDF outputs on different devices and printers common in the USA to ensure compatibility.
  • Remember to consider accessibility and file size when generating PDFs.

I hope you found this guide helpful in understanding how to convert React components into PDFs. Each method has its strengths depending on your project’s needs.

You can also read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.