Sure, here is an example codebase for creating an API that generates dynamic PDF certificates using the MERN stack:
- Server-side code (Node.js, Express.js, MongoDB, Mongoose)
Create a directory called server and navigate to it.
Create a file called app.js and add the following code to it:
// Import required modules
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');
const certificate = require('./routes/certificate');
// Initialize express app
const app = express();
// Configure middleware
app.use(express.json());
app.use(cors());
// Connect to MongoDB database
mongoose.connect('mongodb://localhost/certificates', { useNewUrlParser: true, useUnifiedTopology: true });
const db = mongoose.connection;
db.once('open', () => {
console.log('Connected to MongoDB database.');
});
// Configure routes
app.use('/certificate', certificate);
// Run server
const port = 5000;
app.listen(port, () => console.log(`Server started on port ${port}.`));
Create a directory called routes and navigate to it.
Create a file called certificate.js and add the following code to it:
// Import required modules
const express = require('express');
const router = express.Router();
const PDFDocument = require('pdfkit');
const fs = require('fs');
const Certificate = require('../models/Certificate');
// Define API endpoint for generating certificates
router.post('/', (req, res) => {
// Create PDF document
const doc = new PDFDocument();
// Write certificate content
doc.fontSize(18).text(`Certificate of Completion`, { align: 'center' });
doc.moveDown();
doc.fontSize(14).text(`This is to certify that ${req.body.recipientName} has successfully completed the course on ${req.body.courseName} on ${req.body.completionDate}.`, { align: 'justify' });
doc.moveDown();
doc.fontSize(12).text(`Issued on ${new Date()}.`, { align: 'right' });
// Save PDF to file system
const fileName = `${req.body.recipientName.split(' ')[0].toLowerCase()}-${req.body.courseName.toLowerCase()}-${req.body.completionDate}.pdf`;
doc.pipe(fs.createWriteStream(fileName));
doc.end();
// Save certificate data to database
const certificate = new Certificate({
recipientName: req.body.recipientName,
courseName: req.body.courseName,
completionDate: req.body.completionDate,
fileName: fileName
});
certificate.save()
.then(result => {
console.log(result);
res.json({ message: 'Certificate generated successfully.' });
})
.catch(err => {
console.log(err);
res.status(500).json({ error: err });
});
});
// Export router
module.exports = router;
Create a directory called models and navigate to it.
Create a file called Certificate.js and add the following code to it:
// Import required modules
const mongoose = require('mongoose');
// Define certificate schema
const certificateSchema = new mongoose.Schema({
recipientName: { type: String, required: true },
courseName: { type: String, required: true },
completionDate: { type: Date, required: true },
fileName: { type: String, required: true }
});
// Export certificate model
module.exports = mongoose.model('Certificate', certificateSchema);
- Client-side code (ReactJs)
Create a directory called client and navigate to it.
Create a React application using the create-react-app command line tool:
npx create-react-app my-app
Navigate to the my-app/src directory.
Create a file called App.js and add the following code to it:
import React, { useState } from 'react';
import axios from 'axios';
function App() {
const [recipientName, setRecipientName] = useState('');
const [courseName, setCourseName] = useState('');
const [completionDate, setCompletionDate] = useState('');
const handleSubmit = event => {
event.preventDefault();
axios.post('http://localhost:5000/certificate', { recipientName, courseName, completionDate })
.then(response => console.log(response.data))
.catch(error => console.log(error));
};
return (
<div>
<h1>Dynamic PDF Certificate Generator</h1>
<form onSubmit={handleSubmit}>
<label htmlFor="recipient-name">Recipient Name:</label>
<input type="text" id="recipient-name" value={recipientName} onChange={event => setRecipientName(event.target.value)} />
<br />
<label htmlFor="course-name">Course Name:</label>
<input type="text" id="course-name" value={courseName} onChange={event => setCourseName(event.target.value)} />
<br />
<label htmlFor="completion-date">Completion Date:</label>
<input type="date" id="completion-date" value={completionDate} onChange={event => setCompletionDate(event.target.value)} />
<br />
<button type="submit">Generate Certificate</button>
</form>
</div>
);
}
export default App;
Save the code and start the React server using the following command:
npm start
This is an example codebase for creating an API that generates dynamic PDF certificates using the MERN stack. You can modify the code according to your needs.