To send a PDF file from Node.js to React.js, you can follow these general steps:
- Set up a Node.js server that serves the PDF file. Here's an example using the
express
framework:
jsconst express = require('express');
const app = express();
app.get('/pdf', (req, res) => {
// Replace this with the path to your PDF file
const filePath = '/path/to/my.pdf';
res.sendFile(filePath);
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
- In your React.js component, make a GET request to the Node.js server to fetch the PDF file. You can use the
fetch
API or any other HTTP client library of your choice. Here's an example usingaxios
:
jsimport axios from 'axios';
function MyComponent() {
const downloadPdf = async () => {
try {
const response = await axios.get('/pdf', { responseType: 'blob' });
const pdfBlob = new Blob([response.data], { type: 'application/pdf' });
const pdfUrl = URL.createObjectURL(pdfBlob);
window.open(pdfUrl, '_blank');
} catch (error) {
console.error(error);
}
};
return (
<button onClick={downloadPdf}>
Download PDF
</button>
);
}
In this example, we're using the responseType: 'blob'
option to receive the PDF file as a binary blob instead of a text response. We then create a Blob
object from the response data and create a URL for the object using URL.createObjectURL()
. Finally, we open the URL in a new browser window using window.open()
.
Note that this example opens the PDF file in a new browser window/tab. If you want to download the file directly instead, you can use the download
attribute on an <a>
tag instead of window.open()
.
To generate a PDF file based on data and send it to React.js from Node.js, you can use a PDF generation library like pdfkit
and a file streaming library like fs
. Here's an example code snippet that demonstrates how to do this:
jsconst express = require('express');
const app = express();
const fs = require('fs');
const PDFDocument = require('pdfkit');
app.get('/pdf', (req, res) => {
// Replace this with your data
const data = {
name: 'John Doe',
age: 35,
address: '123 Main St, Anytown USA',
};
// Create a new PDF document
const doc = new PDFDocument();
// Set the PDF response headers
res.setHeader('Content-Type', 'application/pdf');
res.setHeader('Content-Disposition', 'attachment; filename=example.pdf');
// Pipe the PDF document to the response stream
doc.pipe(res);
// Add content to the PDF document
doc.fontSize(16).text('Personal Information:');
doc.fontSize(12).text(`Name: ${data.name}`);
doc.fontSize(12).text(`Age: ${data.age}`);
doc.fontSize(12).text(`Address: ${data.address}`);
// Finalize the PDF document and end the response stream
doc.end();
});
app.listen(3000, () => {
console.log('Server running on port 3000');
});
In this example, we're generating a simple PDF document that contains some personal information based on the data
object. We're using pdfkit
to create the PDF document, and we're streaming the document to the response stream using the pipe()
method. We're also setting the necessary response headers to indicate that we're sending a PDF file as the response.
In your React.js component, you can use the same code as before to fetch the PDF file from the Node.js server and open it in a new browser window:
jsimport axios from 'axios';
function MyComponent() {
const downloadPdf = async () => {
try {
const response = await axios.get('/pdf', { responseType: 'blob' });
const pdfBlob = new Blob([response.data], { type: 'application/pdf' });
const pdfUrl = URL.createObjectURL(pdfBlob);
window.open(pdfUrl, '_blank');
} catch (error) {
console.error(error);
}
};
return (
<button onClick={downloadPdf}>
Download PDF
</button>
);
}
This example is similar to the previous one, except that we're now fetching the PDF file from the /pdf
endpoint on the Node.js server, which generates the PDF document on the fly based on the data
object. The PDF file is still opened in a new browser window/tab when the user clicks the download button.