Created
September 30, 2023 21:42
-
-
Save 0916dhkim/d2f20277cc44d47186b86331291fdc05 to your computer and use it in GitHub Desktop.
File download from express
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const express = require("express"); | |
const PDF = require("pdfkit"); | |
const PizZip = require("pizzip"); | |
const Docxtemplater = require("docxtemplater"); | |
const fs = require("fs"); | |
const path = require("path"); | |
const server = express(); | |
server.get("/mypdf", async (req, res, next) => { | |
try { | |
const doc = new PDF(); | |
doc.text("Hello, World!"); | |
doc.pipe(res); | |
doc.end(); | |
} catch (e) { | |
next(e); | |
} | |
}); | |
server.get("/myword", async (req, res, next) => { | |
try { | |
// Load the docx file as binary content | |
const content = fs.readFileSync( | |
path.resolve(__dirname, "input.docx"), | |
"binary" | |
); | |
const zip = new PizZip(content); | |
const doc = new Docxtemplater(zip, { | |
paragraphLoop: true, | |
linebreaks: true, | |
}); | |
// Render the document (Replace {first_name} by John, {last_name} by Doe, ...) | |
doc.render({ | |
first_name: "John", | |
last_name: "Doe", | |
phone: "0652455478", | |
description: "New Website", | |
}); | |
const buf = doc.getZip().generate({ | |
type: "nodebuffer", | |
// compression: DEFLATE adds a compression step. | |
// For a 50MB output document, expect 500ms additional CPU time | |
compression: "DEFLATE", | |
}); | |
res.setHeader("Content-Type", "application/octet-stream"); | |
res.setHeader("Content-Disposition", 'attachment; filename="word.docx"'); | |
res.send(buf); | |
} catch (e) { | |
next(e); | |
} | |
}); | |
server.listen(5000, () => { | |
console.log("Listening to 5000"); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment