initial commit
This commit is contained in:
83
server.js
Normal file
83
server.js
Normal file
@@ -0,0 +1,83 @@
|
||||
// server.js
|
||||
const express = require('express');
|
||||
const multer = require('multer');
|
||||
const Docxtemplater = require('docxtemplater');
|
||||
const PizZip = require('pizzip');
|
||||
|
||||
const app = express();
|
||||
|
||||
// Configure multer to accept any field
|
||||
const upload = multer({
|
||||
storage: multer.memoryStorage(),
|
||||
}).any();
|
||||
|
||||
app.use(express.json());
|
||||
|
||||
app.post('/process-template', (req, res) => {
|
||||
upload(req, res, function(err) {
|
||||
if (err instanceof multer.MulterError) {
|
||||
console.error('Multer error:', err);
|
||||
return res.status(400).json({ error: 'File upload error', details: err.message });
|
||||
} else if (err) {
|
||||
console.error('Unknown error:', err);
|
||||
return res.status(500).json({ error: 'Unknown error', details: err.message });
|
||||
}
|
||||
|
||||
// Log incoming request details
|
||||
console.log('Files received:', req.files);
|
||||
console.log('Body received:', req.body);
|
||||
|
||||
try {
|
||||
// Find the template file from the uploaded files
|
||||
const templateFile = req.files?.find(file => file.fieldname === 'template');
|
||||
const templateData = req.body?.data ? JSON.parse(req.body.data) : null;
|
||||
console.log(templateData)
|
||||
if (!templateFile || !templateData) {
|
||||
return res.status(400).json({
|
||||
error: 'Missing required fields',
|
||||
received: {
|
||||
templateFile: !!templateFile,
|
||||
templateData: !!templateData
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Get the template file buffer
|
||||
const content = templateFile.buffer;
|
||||
|
||||
// Create a new PizZip instance with the template content
|
||||
const zip = new PizZip(content);
|
||||
|
||||
// Create the template processor
|
||||
const doc = new Docxtemplater(zip, {
|
||||
paragraphLoop: true,
|
||||
linebreaks: true,
|
||||
});
|
||||
|
||||
// Render the document with the provided data
|
||||
doc.render(templateData);
|
||||
|
||||
// Generate the document as a buffer
|
||||
const buffer = doc.getZip().generate({
|
||||
type: 'nodebuffer',
|
||||
compression: 'DEFLATE',
|
||||
});
|
||||
|
||||
// Set response headers for file download
|
||||
res.setHeader('Content-Type', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document');
|
||||
res.setHeader('Content-Disposition', 'attachment; filename=generated-document.docx');
|
||||
|
||||
// Send the generated document
|
||||
res.send(buffer);
|
||||
|
||||
} catch (error) {
|
||||
console.error('Processing error:', error);
|
||||
res.status(500).json({ error: 'Processing error', details: error.message });
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
const PORT = process.env.PORT || 3000;
|
||||
app.listen(PORT, () => {
|
||||
console.log(`Server is running on port ${PORT}`);
|
||||
});
|
||||
Reference in New Issue
Block a user