Highcharts Demo

author(s): Øystein Moseng

by oysteinmoseng

HTML

<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/lib/jspdf.js"></script>
<script src="https://code.highcharts.com/lib/svg2pdf.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<script src="https://code.highcharts.com/modules/offline-exporting.js"></script>

<div id="container"></div>

CSS

#container {
  max-width: 800px;
  height: 400px;
  margin: 1em auto;
}

JavaScript

// ------------------------------------------
// ------------------------------------------
// Make changes to PDF here
// Note that jsPDF and svg2pdf need to be loaded for this to work (see HTML section).

// Size of page, in addition to chart
var pdfMargins = {
  top: 100,
  bottom: 0,
  left: 10,
  right: 10
};

function modifyPDF(pdf) {
  // See http://raw.githack.com/MrRio/jsPDF/master/docs/ for documentation on the pdf object
  pdf.setFontSize(36);
  pdf.text('PDF document title', 40, 40);
}

// ------------------------------------------
// ------------------------------------------


// Wrap current PDF export to add custom functionality
var oldSvg2pdf = window.svg2pdf;
window.svg2pdf = function(svgEl, pdf) {
  var ret = oldSvg2pdf.apply(this, arguments);
  modifyPDF(pdf);
  return ret;
};

Highcharts.wrap(Highcharts.Chart.prototype, 'exportChartLocal', function(proceed, exportingOptions, chartOptions) {
  var options = Highcharts.merge(this.options.exporting, exportingOptions);
  if (options.type === 'application/pdf') {
    Highcharts.merge(true, options, {
      chartOptions: {
        chart: {
          spacingBottom: pdfMargins.bottom,
          spacingTop: pdfMargins.top,
          spacingLeft: pdfMargins.left,
          spacingRight: pdfMargins.right,
          width: this.container.offsetWidth + pdfMargins.left + pdfMargins.right,
          height: this.container.offsetHeight + pdfMargins.top + pdfMargins.bottom
        }
      }
    });
  }
  return proceed.call(this, options, Highcharts.merge(options.chartOptions || {}, chartOptions));
});

// ------------------------------------------



// Test chart
Highcharts.chart('container', {
  exporting: {
    chartOptions: {
      chart: {
        type: 'spline'
      }
    },
    fallbackToExportServer: false // Force client side exporting
  },

  title: {
    text: 'Chart title'
  },

  subtitle: {
    text: 'Click the button to download as PNG, JPEG, SVG or PDF'
  },

  chart: {
    type: 'area'
 ...