Skip to content

Adding Custom HTML Elements into the chart container

If you want to place custom UI blocks directly inside your OrgChart JS container, for example a title and a legend, you can append regular HTML elements after the chart is rendered. You can also include those elements in the exported PDF.

Minimal Setup

html
<script src="https://cdn.balkan.app/orgchart.js"></script>
<div id="tree"></div>
<div id="legent-content" style="display:none;">...</div>
<style id="myStyle">/* styles used on screen and in export */</style>

Key JavaScript Parts

Initialize the chart and add a custom PDF menu action:

js
let chart = new OrgChart(document.getElementById("tree"), {
  template: "olivia",
  orientation: OrgChart.orientation.bottom_left,
  mode: "dark",
  menu: {
    pdfExport: {
      text: "Export PDF",
      icon: OrgChart.icon.png(24, 24, "#7A7A7A"),
      onClick: () => chart.exportToPDF({ format: "A4" })
    }
  }
});

On first redraw, append custom title and legend into the chart container and keep their HTML:

js
let initialized = false;
let titleHTML, legentHTML;

chart.onRedraw(() => {
  if (initialized) return;
  // Create title and legend, append to chart.element
  // Save outerHTML into titleHTML and legentHTML
  initialized = true;
});

Before PDF export, inject custom HTML and styles into the exported page:

js
chart.onExportStart((args) => {
  const width = args.options.width === "auto"
    ? args.pages[0].getAttribute("width")
    : args.options.width;
  const height = args.options.height === "auto"
    ? args.pages[0].getAttribute("height")
    : args.options.height;

  args.pages[0].innerHTML += `<foreignobject x="0" y="0" width="${width}" height="${height}">${titleHTML + legentHTML}</foreignobject>`;
  args.styles += document.getElementById("myStyle").outerHTML;
});

Why This Pattern

You keep the chart clean, add custom UI only when needed, and ensure the same title/legend are visible both in the browser and in the exported PDF.