ChartUtil { public static void writeChartAsPDF(OutputStream aOS, JFreeChart chart, int aWidth, int aHeight) throws IOException { PDFDocumentGraphics2D pdfGenerator = new PDFDocumentGraphics2D(true, aOS, aWidth, aHeight); pdfGenerator.setDeviceDPI(PDFDocumentGraphics2D.NORMAL_PDF_RESOLUTION); pdfGenerator.setGraphicContext(new GraphicContext()); pdfGenerator.setSVGDimension(aWidth, aHeight); pdfGenerator.setClip(0, 0, aWidth, aHeight); pdfGenerator.setRenderingHint(KEY_ANTIALIASING, VALUE_ANTIALIAS_ON); pdfGenerator.setRenderingHint(KEY_INTERPOLATION, VALUE_INTERPOLATION_BILINEAR); chart.setBackgroundPaint(Color.white); chart.getPlot().setBackgroundPaint(Color.white); chart.draw(pdfGenerator, new Rectangle(aWidth, aHeight)); pdfGenerator.finish(); }  static void writeChartAsSVG(OutputStream aOS, JFreeChart chart, int aWidth, int aHeight); static void writeChartAsPDF(OutputStream aOS, JFreeChart chart, int aWidth, int aHeight);  }
@Test public void testPDF() throws Exception { double[][] data = new double[2][10]; for (int n = 1; n < 10; n++) { data[0][n] = 1.0 / n; data[1][n] = 1.0 - (1.0 / n); } DefaultXYDataset dataset = new DefaultXYDataset(); dataset.addSeries("data", data); JFreeChart chart = ChartFactory.createXYLineChart(null, "Recall", "Precision", dataset, PlotOrientation.VERTICAL, false, false, false); chart.getXYPlot().setRenderer(new XYSplineRenderer()); chart.getXYPlot().getRangeAxis().setRange(0.0, 1.0); chart.getXYPlot().getDomainAxis().setRange(0.0, 1.0); File tmp = File.createTempFile("testfile", ".pdf"); try (OutputStream os = new FileOutputStream(tmp)) { ChartUtil.writeChartAsPDF(os, chart, 400, 400); } }