title: Apache POI Java - Docx Charts and Graphs
body: <p>Iv been working with XWPF documents for several weeks now and I have not been able to add charts. Pie charts, Bar charts. I plan to manually inject a chart with XML into the file but i think its excessive. I just want to add a chart to a Docx template. Aspose and javadocx are not options.</p>
  
  <pre><code>XWPFDocument document = new XWPFDocument(getClass().getResourceAsStream("/templates/standard.docx"));
  //INSERT PIE CHART
  FileOutputStream out = new FileOutputStream(new File("output/output.docx");
  document.write(out);
  </code></pre>
  
  <p>[UPDATE - The Easy Route]</p>
  
  <p>Due to time it would take to successfully write an injection method, iv found a handy (Quick n dirty) way of adding charts. This is not the normal word charts but one generated from a library, stored as a picture and inserted.</p>
  
  <p>First, i downloaded the library from <a href="http://knowm.org/open-source/xchart/xchart-example-code" rel="nofollow noreferrer">http://knowm.org/open-source/xchart/xchart-example-code</a>.</p>
  
  <p>Second, one you have implemented your XWPFdocument, you create a chart and append it as an image.</p>
  
  <pre><code>private XWPFDocument add_chart(XWPFDocument document)
  {
      // New Chart Element
      CategoryChart chart = new CategoryChartBuilder().width(500).height(400).theme(Styler.ChartTheme.GGPlot2).title(getClass().getSimpleName()).build();
      chart.setTitle("Issue Count");
      // Customize Chart
      Color[] sliceColors = new Color[]{new Color(27, 50, 119), new Color(58, 146, 56), new Color(0, 161, 222), new Color(154, 205, 102), new Color(246, 199, 182)};
      chart.getStyler().setSeriesColors(sliceColors);
  
      // Series
      chart.addSeries("Critical", new ArrayList&lt;&gt;(Arrays.asList(new String[]{"Count"})), new ArrayList&lt;&gt;(Arrays.asList(new Number[]{10})));
      chart.addSeries("High", new ArrayList&lt;&gt;(Arrays.asList(new String[]{"High"})), new ArrayList&lt;&gt;(Arrays.asList(new Number[]{5})));
      chart.addSeries("Medium", new ArrayList&lt;&gt;(Arrays.asList(new String[]{"Medium"})), new ArrayList&lt;&gt;(Arrays.asList(new Number[]{2})));
      chart.addSeries("Low", new ArrayList&lt;&gt;(Arrays.asList(new String[]{"Low"})), new ArrayList&lt;&gt;(Arrays.asList(new Number[]{1})));
  
      // Create and store a jpg image of the chart, then append it to the document
      BitmapEncoder.saveBitmapWithDPI(chart, "tmp.jpg", BitmapFormat.JPG, 300);
      document.createParagraph().createRun().addPicture(new FileInputStream("tmp.jpg"), XWPFDocument.PICTURE_TYPE_JPEG, "tmp.jpg", Units.toEMU(500), Units.toEMU(400));
      return document;
  }
  </code></pre>
  
  <p>An example of one chart i made using the library:
  <a href="https://i.stack.imgur.com/x3UQ4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/x3UQ4.png" alt="POI-chart-example"></a></p>