Skip to content

Instantly share code, notes, and snippets.

@SGarcia710
Last active January 22, 2020 21:37
Show Gist options
  • Save SGarcia710/a3276fc44756c46947655c6bc43906c4 to your computer and use it in GitHub Desktop.
Save SGarcia710/a3276fc44756c46947655c6bc43906c4 to your computer and use it in GitHub Desktop.
ExpressJS Endpoint to generate PDF's using PDFKit library.
const PDFDocument = require("pdfkit");
const generatePDF = async (info, doc) => {
doc
.font("Times-Roman")
.fontSize(12)
.text(info.title);
};
module.exports = {
generatePDF
};
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