Skip to content

Instantly share code, notes, and snippets.

@victorekpo
Forked from ChemaCLi/pdf-charts-generator.js
Created August 25, 2023 03:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save victorekpo/6599c555b4c1a104c8e1e6f9f8df69c5 to your computer and use it in GitHub Desktop.
Save victorekpo/6599c555b4c1a104c8e1e6f9f8df69c5 to your computer and use it in GitHub Desktop.
Generate PDF with ChartJS and PDFKit
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