-
-
Save victorekpo/6599c555b4c1a104c8e1e6f9f8df69c5 to your computer and use it in GitHub Desktop.
Generate PDF with ChartJS and PDFKit
This file contains 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 fs = require('fs') | |
const tmp = require("tmp"); | |
const PDFDocument = require('pdfkit'); | |
const MemoryStream = require('memorystream'); | |
const { ChartJSNodeCanvas } = require('chartjs-node-canvas'); | |
export async function generatePDFWithCharts() { | |
// Sample chart with ChartJS | |
const chartJSNodeCanvas = new ChartJSNodeCanvas({ type: 'png', width: 800, height: 600 }); | |
const configuration = { | |
type: 'bar', | |
data: { | |
labels: ['Q1', 'Q2', 'Q3', 'Q4'], | |
datasets: [{ | |
label: 'Users', | |
data: [50, 60, 70, 180] | |
}] | |
} | |
}; | |
// Generate chart image | |
const imageBuffer = await chartJSNodeCanvas.renderToBuffer(configuration); | |
// Write the chart image to the system because the PDF needs a path | |
const tempImg = tmp.fileSync({ postfix: ".png" }); | |
fs.writeFileSync(tempImg.name, imageBuffer); | |
// Prepare the PDF | |
const doc = new PDFDocument; | |
doc.fontSize(25).text('Here is some vector foo...', 100, 80); | |
// Use the image we just wrote to the system | |
doc.image(tempImg.name, 0, 15, {width: 300}) | |
.text('Proportional to width', 0, 0); | |
// Create a stream to hold the PDF in memory | |
const memStream = new MemoryStream(null, { | |
readable : false | |
}); | |
doc.pipe(memStream); | |
// Write the PDF stream buffer to the file system | |
doc.on('end', function () { | |
const pdfBuffer = Buffer.concat(memStream.queue) | |
// From here you'll be able to read the file and handle it as you wish | |
const tempPDF = tmp.fileSync({ postfix: ".pdf" }); | |
fs.writeFileSync(tempPDF.name, pdfBuffer); | |
console.log({ tempPDF }) | |
}) | |
doc.end(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment