← Back to Guides

Charts in PDFs

Generate PDF reports with embedded charts. Chart-Output returns PNG/JPEG buffers that you can embed in any PDF library.

Option 1: pdfkit (Node.js)

import { ChartOutput } from '@chart-output/node';
import PDFDocument from 'pdfkit';

const client = new ChartOutput({ apiKey: process.env.CHART_OUTPUT_API_KEY });
const chartPng = await client.render({
  type: 'bar',
  data: { labels: ['Q1','Q2','Q3','Q4'], datasets: [{ data: [100,150,120,180] }] },
  format: 'png',
  width: 600,
  height: 300,
});

const doc = new PDFDocument();
doc.pipe(fs.createWriteStream('report.pdf'));
doc.fontSize(24).text('Quarterly Report', 50, 50);
doc.image(chartPng, 50, 100, { width: 500 });
doc.end();

Option 2: PDF output format

Chart-Output can return PDF directly. Use format: "pdf" for a single-chart PDF.

const pdfBuffer = await client.render({
  type: 'line',
  data: { labels: ['Jan','Feb','Mar'], datasets: [{ data: [10,20,30] }] },
  format: 'pdf',
  width: 800,
  height: 400,
});
fs.writeFileSync('chart.pdf', pdfBuffer);

Option 3: Puppeteer

For complex layouts, render the chart as an image URL and embed in an HTML template, then use Puppeteer to generate the PDF.

const { url } = await client.render({ ...spec, returnUrl: true });
const html = `<html><body><img src="${url}" /></body></html>`;
// Use Puppeteer to render HTML to PDF