Generate a PDF from JSON data using jspdf in a React application

To generate a PDF from JSON data using `jspdf` in a React application, you can follow these steps:

Install Dependencies:

Install `jspdf` and `jspdf-autotable` for handling tables in the PDF:

npm install jspdf jspdf-autotable --save

Create a Component for PDF Generation:

Create a new component, let’s call it `JSONToPDF.js`, in your src folder.

Write the Code:

Here’s an example of how you can generate a PDF from JSON data using `jspdf` and `jspdf-autotable`:

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

function JSONToPDF({ jsonData }) {
  const generatePDF = () => {
    const doc = new jsPDF();
    const tableColumn = ['ID', 'Name', 'Age'];
    const tableRows = [];

    jsonData.forEach(item => {
      const rowData = [
        item.id.toString(),
        item.name,
        item.age.toString()
      ];
      tableRows.push(rowData);
    });

    doc.autoTable(tableColumn, tableRows);
    doc.save('generated-pdf.pdf');
  };

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

export default JSONToPDF;

Use the Component:

Use the `JSONToPDF` the component in your application and pass the JSON data as props:

import React from 'react';
import JSONToPDF from './JSONToPDF';

function App() {
  const jsonData = [
    { id: 1, name: 'John Doe', age: 30 },
    { id: 2, name: 'Jane Smith', age: 25 },
    { id: 3, name: 'Alice Johnson', age: 35 }
  ];

  return (
    <div>
      <h1>Generate PDF from JSON Data</h1>
      <JSONToPDF jsonData={jsonData} />
    </div>
  );
}

export default App;

Customize as Needed:

You can customize the PDF generation code to format the table, add headers, footers, styles, and more according to your requirements.

Testing and Deployment:

Test the PDF generation functionality thoroughly with various JSON datasets to ensure it works as expected. Once satisfied, you can deploy your React application as usual.

This code will generate a PDF with a table representing the JSON data provided. Adjust the table columns and rows according to your JSON structure.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top