Skip to content

Instantly share code, notes, and snippets.

@ChemaCLi
Last active November 9, 2023 13:09
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ChemaCLi/006b2d0615cd617ff88900ba119189f8 to your computer and use it in GitHub Desktop.
Save ChemaCLi/006b2d0615cd617ff88900ba119189f8 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();
}
@Ahmadre
Copy link

Ahmadre commented Oct 31, 2023

This is not working out of the box and required native packages to be installed on the environment os.

@ChemaCLi
Copy link
Author

@Ahmadre yeah you're right. This script works on NodeJS. I made it for a backend solution. Do you need something to work in the frontend? what is your use case?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment