45 lines
1.5 KiB
Plaintext
45 lines
1.5 KiB
Plaintext
const express = require('express');
|
|
const fs = require('fs');
|
|
const path = require('path');
|
|
const Docxtemplater = require('docxtemplater');
|
|
const PizZip = require('pizzip');
|
|
|
|
const app = express();
|
|
|
|
// Enable JSON parsing for incoming requests
|
|
app.use(express.json());
|
|
app.use(express.urlencoded({ extended: false }));
|
|
|
|
// Endpoint to generate the document
|
|
app.post('/generate-doc', (req, res) => {
|
|
try {
|
|
// Load your DOCX template (ensure the template is in the same directory)
|
|
const content = fs.readFileSync(path.resolve(__dirname, 'template.docx'), 'binary');
|
|
const zip = new PizZip(content);
|
|
const doc = new Docxtemplater(zip, { paragraphLoop: true, linebreaks: true });
|
|
|
|
// Set your template variables from the request body
|
|
doc.setData(req.body);
|
|
|
|
// Render the document (this only replaces placeholders, preserving your formatting)
|
|
doc.render();
|
|
|
|
// Generate the updated document as a buffer
|
|
const buf = doc.getZip().generate({ type: 'nodebuffer' });
|
|
|
|
res.set({
|
|
'Content-Type': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
|
'Content-Disposition': 'attachment; filename=output.docx'
|
|
});
|
|
res.send(buf);
|
|
} catch (error) {
|
|
console.error('Error during document generation:', error);
|
|
res.status(500).send('An error occurred while generating the document.');
|
|
}
|
|
});
|
|
|
|
const PORT = process.env.PORT || 3000;
|
|
app.listen(PORT, () => {
|
|
console.log(`Docxtemplater service listening on port ${PORT}`);
|
|
});
|