How to download a PDF file generated using pdfkit in React and Express


  1. Install the necessary packages:
bash
npm install pdfkit express
  1. Create an Express route to generate the PDF:
javascript
const PDFDocument = require('pdfkit'); const express = require('express'); const app = express(); app.get('/download-pdf', (req, res) => { const doc = new PDFDocument(); const filename = 'sample.pdf'; // Set response headers res.setHeader('Content-disposition', 'attachment; filename="' + filename + '"'); res.setHeader('Content-type', 'application/pdf'); // Pipe the PDF document to the response object doc.pipe(res); // Add content to the PDF document doc.fontSize(24).text('Hello World'); // Finalize the PDF document doc.end(); });
  1. Create a React component to handle the file download:
javascript
import React from 'react'; import axios from 'axios'; function FileDownload() { const handleClick = async () => { try { const response = await axios.get('/download-pdf', { responseType: 'blob', }); const url = window.URL.createObjectURL(new Blob([response.data])); const link = document.createElement('a'); link.href = url; link.setAttribute('download', 'sample.pdf'); document.body.appendChild(link); link.click(); } catch (error) { console.log(error); } }; return ( <div> <button onClick={handleClick}>Download PDF</button> </div> ); } export default FileDownload;
  1. Render the React component in your app:
javascript
import React from 'react'; import FileDownload from './FileDownload'; function App() { return ( <div> <h1>PDF File Download Example</h1> <FileDownload /> </div> ); } export default App;

When the user clicks the "Download PDF" button, the handleClick function is called. This function sends a GET request to the /download-pdf route on the server. The server generates a new PDF document using pdfkit, adds content to it, and then pipes it to the response object. The response headers are set to download the PDF as an attachment with the filename sample.pdf.

The response data is then converted to a Blob object and a download link is created with the URL of the Blob. When the link is clicked, the PDF file is downloaded to the user's device.

Post a Comment

0 Comments