Last active
January 22, 2020 21:37
-
-
Save SGarcia710/a3276fc44756c46947655c6bc43906c4 to your computer and use it in GitHub Desktop.
ExpressJS Endpoint to generate PDF's using PDFKit library.
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 PDFDocument = require("pdfkit"); | |
const generatePDF = async (info, doc) => { | |
doc | |
.font("Times-Roman") | |
.fontSize(12) | |
.text(info.title); | |
}; | |
module.exports = { | |
generatePDF | |
}; |
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 router = express.Router(); | |
const PDFDocument = require("pdfkit"); | |
const pdfController = require("../controllers/pdfController"); | |
router.post("/", async (request, response) => { | |
try { | |
const doc = new PDFDocument({ bufferPages: true }); | |
let buffers = []; | |
doc.on("data", buffers.push.bind(buffers)); | |
doc.on("end", () => { | |
let pdfData = Buffer.concat(buffers); | |
response | |
.writeHead(200, { | |
"Content-Length": Buffer.byteLength(pdfData), | |
"Content-Type": "application/pdf", | |
"Content-disposition": "attachment;filename=report.pdf" | |
})// it responses with the PDF file download. | |
.end(pdfData); | |
}); | |
pdfController.generatePDF(request.body, doc); // Here you send the data for the PDF Document and the blank PDF Buffer. | |
doc.end(); | |
} catch (error) { | |
response.status(400).json({ message: error.message, code: error.code }); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment