search
React

How to integrate jsPDF Library in React to Edit PDF in Browser

Quick guide to using jsPDF in React applications for creating and editing PDF documents directly in the browser.

person By Gautam Sharma
calendar_today December 29, 2024
schedule 4 min read
React PDF jsPDF JavaScript

jsPDF is a powerful library for generating PDFs client-side in React applications. Here’s how to get started quickly.

Installation

Install jsPDF in your React project:

npm install jspdf

Basic PDF Component

Create a simple PDF generator:

import React from 'react';
import jsPDF from 'jspdf';

function PDFGenerator() {
  const generatePDF = () => {
    const doc = new jsPDF();
    doc.text('Hello from React!', 20, 20);
    doc.save('document.pdf');
  };

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

export default PDFGenerator;

Adding Dynamic Content

Generate PDFs from React state:

import { useState } from 'react';
import jsPDF from 'jspdf';

function DynamicPDF() {
  const [title, setTitle] = useState('');
  const [content, setContent] = useState('');

  const createPDF = () => {
    const doc = new jsPDF();

    doc.setFontSize(18);
    doc.text(title, 20, 20);

    doc.setFontSize(12);
    const lines = doc.splitTextToSize(content, 170);
    doc.text(lines, 20, 35);

    doc.save(`${title}.pdf`);
  };

  return (
    <div>
      <input
        value={title}
        onChange={(e) => setTitle(e.target.value)}
        placeholder="Title"
      />
      <textarea
        value={content}
        onChange={(e) => setContent(e.target.value)}
        placeholder="Content"
      />
      <button onClick={createPDF}>Create PDF</button>
    </div>
  );
}

Styling and Formatting

Add styles to your PDF:

const createStyledPDF = () => {
  const doc = new jsPDF();

  // Title
  doc.setFontSize(22);
  doc.setFont(undefined, 'bold');
  doc.text('My Document', 105, 20, { align: 'center' });

  // Subtitle with color
  doc.setFontSize(14);
  doc.setTextColor(100, 100, 100);
  doc.text('Generated from React', 105, 30, { align: 'center' });

  // Body content
  doc.setTextColor(0, 0, 0);
  doc.setFontSize(12);
  doc.setFont(undefined, 'normal');
  doc.text('Your content here...', 20, 45);

  doc.save('styled.pdf');
};

Converting HTML to PDF

Use html2canvas to convert React components:

npm install html2canvas
import { useRef } from 'react';
import jsPDF from 'jspdf';
import html2canvas from 'html2canvas';

function HTMLToPDF() {
  const contentRef = useRef();

  const exportToPDF = async () => {
    const element = contentRef.current;
    const canvas = await html2canvas(element);
    const imgData = canvas.toDataURL('image/png');

    const pdf = new jsPDF();
    const imgWidth = 190;
    const imgHeight = (canvas.height * imgWidth) / canvas.width;

    pdf.addImage(imgData, 'PNG', 10, 10, imgWidth, imgHeight);
    pdf.save('export.pdf');
  };

  return (
    <div>
      <div ref={contentRef}>
        <h1>Content to Export</h1>
        <p>This will become a PDF</p>
      </div>
      <button onClick={exportToPDF}>Export PDF</button>
    </div>
  );
}

Adding Images

Include images in your PDF:

const addImageToPDF = async () => {
  const doc = new jsPDF();

  // From URL or import
  const imgData = 'data:image/png;base64,...';

  doc.addImage(imgData, 'PNG', 15, 40, 180, 160);
  doc.save('with-image.pdf');
};

Multiple Pages

Handle multi-page documents:

const createMultiPagePDF = () => {
  const doc = new jsPDF();

  doc.text('Page 1', 20, 20);

  doc.addPage();
  doc.text('Page 2', 20, 20);

  doc.addPage();
  doc.text('Page 3', 20, 20);

  doc.save('multi-page.pdf');
};

Complete Example

Full React component with form:

import { useState } from 'react';
import jsPDF from 'jspdf';

function InvoiceGenerator() {
  const [formData, setFormData] = useState({
    clientName: '',
    amount: '',
    date: ''
  });

  const handleChange = (e) => {
    setFormData({
      ...formData,
      [e.target.name]: e.target.value
    });
  };

  const generateInvoice = () => {
    const doc = new jsPDF();

    doc.setFontSize(20);
    doc.text('INVOICE', 105, 20, { align: 'center' });

    doc.setFontSize(12);
    doc.text(`Client: ${formData.clientName}`, 20, 40);
    doc.text(`Amount: $${formData.amount}`, 20, 50);
    doc.text(`Date: ${formData.date}`, 20, 60);

    doc.save(`invoice-${formData.clientName}.pdf`);
  };

  return (
    <form onSubmit={(e) => { e.preventDefault(); generateInvoice(); }}>
      <input
        name="clientName"
        value={formData.clientName}
        onChange={handleChange}
        placeholder="Client Name"
        required
      />
      <input
        name="amount"
        type="number"
        value={formData.amount}
        onChange={handleChange}
        placeholder="Amount"
        required
      />
      <input
        name="date"
        type="date"
        value={formData.date}
        onChange={handleChange}
        required
      />
      <button type="submit">Generate Invoice</button>
    </form>
  );
}

export default InvoiceGenerator;

Key Methods

  • doc.text(text, x, y) - Add text
  • doc.setFontSize(size) - Set font size
  • doc.setFont(undefined, style) - Set bold/italic
  • doc.addPage() - Add new page
  • doc.addImage(data, format, x, y, w, h) - Add images
  • doc.save(filename) - Download PDF

Tips

  • Use splitTextToSize() for long text that needs wrapping
  • Coordinates are in millimeters by default
  • A4 page is 210mm wide by 297mm tall
  • Origin (0,0) is top-left corner
  • Always handle async operations when using html2canvas

jsPDF makes PDF generation in React simple and powerful!

Gautam Sharma

About Gautam Sharma

Full-stack developer and tech blogger sharing coding tutorials and best practices

Related Articles

React

Getting Started with React Hooks in 2025

Learn how to use React Hooks effectively in your modern React applications with practical examples and best practices.

December 15, 2024
React

QR Codes with React: Quick Implementation

Build QR code scanner and generator in React. Simple setup with react-qr-code and html5-qrcode libraries.

December 31, 2024
HTML

jsPDF Tutorial: Generate PDF in Browser Using HTML & JavaScript (Full Working Example)

Learn to create PDFs directly in the browser with jsPDF. Step-by-step guide with working examples for invoices, tickets, and styled documents.

December 31, 2024