java 生成柱状图、饼状图等图片保存至word文档

写在前面,springboot pom 中引入下面就可以了,省了在csdn找包很麻烦。

1
2
3
4
5
        <dependency>
            <artifactId>jfreechart</artifactId>
            <groupId>org.jfree</groupId>
            <version>1.0.19</version>
        </dependency>

java导出word中 Document 用的包比较乱,这里需要注意是个坑,我最下面测试用了两种方式导出word,XWPFDocument 与 com.lowagie.text包下的Document.,个人感觉XWPFDocument 方式比较好,图片也支持读取流或读图片路径两种方式写入word,相对来说Document只能用Image img = Image.getInstance(“E:\picture\bar.png”);读取路径方式。

Image 类的包导入也要注意,示例只能用java8,java11 写入word报错就没用。
只试了两个柱状图可以用,原引用用导出字体有问题,我下面已经补上了。根据自已想要的样式再稍作调整。
//设置整个图片的标题字体
chart.getTitle().setFont(labelFont);
在这里插入图片描述
原文引用

https://blog.csdn.net/zyb_java/article/details/22291473

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
import com.lowagie.text.Image;
import com.lowagie.text.*;
import com.lowagie.text.rtf.RtfWriter2;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.util.Units;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.CategoryLabelPositions;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;
import org.jfree.chart.labels.StandardPieSectionLabelGenerator;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PiePlot3D;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.chart.renderer.category.LineAndShapeRenderer;
import org.jfree.chart.renderer.category.StackedBarRenderer;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.general.DatasetUtilities;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.general.PieDataset;

import javax.imageio.ImageIO;
import java.awt.Font;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.text.DecimalFormat;
import java.text.NumberFormat;

;


/**
 * <p><center>[wp_ad_camp_2]</center></p><p><br/>
 *
 * @version v1.0.0
 * @className CreateChartServiceImpl.java<br />
 * @packageName com.sinosoft.webmodule.landLibrary<br />
 * @date 2014-3-23 下午04:39:19<br/>
 * </p>
 */

public class Test {<!-- -->
    private static final String CHART_PATH = "E:/picture/";

    @org.junit.Test
    public void main() {<!-- -->
        // 生成单组柱状图
        makeBarChart();
/*        // 生成饼状图
        makePieChart();
        // 生成单组柱状图
        makeBarChart();
        // 生成单组柱状图
        makeBarChart2();
        // 生成多组柱状图
        makeBarGroupChart();
        // 生成堆积柱状图
        makeStackedBarChart();
        // 生成折线图
        makeLineAndShapeChart();*/

    }

    /**
     * 生成折线图
     */
    public void makeLineAndShapeChart() {<!-- -->
        double[][] data = new double[][]{<!-- -->{<!-- -->672, 766, 223, 540, 126},
                {<!-- -->325, 521, 210, 340, 106}, {<!-- -->332, 256, 523, 240, 526}};
        String[] rowKeys = {<!-- -->"苹果", "梨子", "葡萄"};
        String[] columnKeys = {<!-- -->"北京", "上海", "广州", "成都", "深圳"};
        CategoryDataset dataset = getBarData(data, rowKeys, columnKeys);
        createTimeXYChar("折线图", "x轴", "y轴", dataset, "lineAndShap.jpg");
    }

    /**
     * 生成分组的柱状图
     */
    public void makeBarGroupChart() {<!-- -->
        double[][] data = new double[][]{<!-- -->{<!-- -->672, 766, 223, 540, 126},
                {<!-- -->325, 521, 210, 340, 106}, {<!-- -->332, 256, 523, 240, 526}};
        String[] rowKeys = {<!-- -->"苹果", "梨子", "葡萄"};
        String[] columnKeys = {<!-- -->"北京", "上海", "广州", "成都", "深圳"};
        CategoryDataset dataset = getBarData(data, rowKeys, columnKeys);
        createBarChart(dataset, "x坐标", "y坐标", "柱状图", "barGroup.png");
    }

    /**
     * 生成柱状图
     */
    @org.junit.Test
    public void makeBarChart() {<!-- -->
        double[][] data = new double[][]{<!-- -->{<!-- -->672, 766, 223, 540, 126}};
        String[] rowKeys = {<!-- -->"苹果"};
        String[] columnKeys = {<!-- -->"北京", "上海", "广州", "成都", "深圳"};
        CategoryDataset dataset = getBarData(data, rowKeys, columnKeys);
        createBarChart(dataset, "", "", "柱状图", "bar.png");
    }

    /**
     * 生成柱状图
     */
    public void makeBarChart2() {<!-- -->
        double[][] data = new double[][]{<!-- -->{<!-- -->672, 766, 223, 540, 126}};
        String[] rowKeys = {<!-- -->"苹果"};
        String[] columnKeys = {<!-- -->"北京", "上海", "广州", "成都", "深圳"};
        CategoryDataset dataset = getBarData(data, rowKeys, columnKeys);
        createHorizontalBarChart(dataset, "x坐标", "y坐标", "柱状图", "bar2.png");
    }

    /**
     * 生成堆栈柱状图
     */
    public void makeStackedBarChart() {<!-- -->
        double[][] data = new double[][]{<!-- -->{<!-- -->0.21, 0.66, 0.23, 0.40, 0.26},
                {<!-- -->0.25, 0.21, 0.10, 0.40, 0.16}};
        String[] rowKeys = {<!-- -->"苹果", "梨子"};
        String[] columnKeys = {<!-- -->"北京", "上海", "广州", "成都", "深圳"};
        CategoryDataset dataset = getBarData(data, rowKeys, columnKeys);
        createStackedBarChart(dataset, "x坐标", "y坐标", "柱状图", "stsckedBar.png");
    }

    /**
     * 生成饼状图
     */
    public void makePieChart() {<!-- -->
        double[] data = {<!-- -->9, 91};
        String[] keys = {<!-- -->"失败率", "成功率"};

        createValidityComparePimChar(getDataPieSetByUtil(data, keys), "饼状图",
                "pie2.png", keys);
    }

    // 柱状图,折线图 数据集
    public CategoryDataset getBarData(double[][] data, String[] rowKeys,
                                      String[] columnKeys) {<!-- -->
        return DatasetUtilities
                .createCategoryDataset(rowKeys, columnKeys, data);

    }

    // 饼状图 数据集
    public PieDataset getDataPieSetByUtil(double[] data,
                                          String[] datadescription) {<!-- -->
        if (data != null && datadescription != null) {<!-- -->
            if (data.length == datadescription.length) {<!-- -->
                DefaultPieDataset dataset = new DefaultPieDataset();
                for (int i = 0; i < data.length; i++) {<!-- -->
                    dataset.setValue(datadescription[i], data[i]);
                }
                return dataset;
            }

        }

        return null;
    }

    /**
     * 柱状图
     *
     * @param dataset    数据集
     * @param xName      x轴的说明(如种类,时间等)
     * @param yName      y轴的说明(如速度,时间等)
     * @param chartTitle 图标题
     * @param charName   生成图片的名字
     * @return
     */
    public String createBarChart(CategoryDataset dataset, String xName,
                                 String yName, String chartTitle, String charName) {<!-- -->
        JFreeChart chart = ChartFactory.createBarChart(chartTitle, // 图表标题
                xName, // 目录轴的显示标签
                yName, // 数值轴的显示标签
                dataset, // 数据集
                PlotOrientation.VERTICAL, // 图表方向:水平、垂直
                false, // 是否显示图例(对于简单的柱状图必须是false),(true时,x轴legend下柱子的标题)
                false, // 是否生成工具
                false // 是否生成URL链接
        );
        //Font labelFont = new Font("SansSerif", Font.TRUETYPE_FONT, 12);
        Font labelFont = new Font("宋体", Font.BOLD, 15);
        //设置整个图片的标题字体
        chart.getTitle().setFont(labelFont);
        //设置x轴上代表柱子的标题,与上面legend:true 配合使用
        // chart.getLegend().setItemFont(labelFont);
        /*
         * VALUE_TEXT_ANTIALIAS_OFF表示将文字的抗锯齿关闭,
         * 使用的关闭抗锯齿后,字体尽量选择12到14号的宋体字,这样文字最清晰好看
         */
        // chart.getRenderingHints().put(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
        chart.setTextAntiAlias(false);
        chart.setBackgroundPaint(Color.white);
        // create plot
        CategoryPlot plot = chart.getCategoryPlot();
        // 设置横虚线可见
        plot.setRangeGridlinesVisible(true);
        // 虚线色彩
        plot.setRangeGridlinePaint(Color.gray);

        // 数据轴精度
/*        NumberAxis vn = (NumberAxis) plot.getRangeAxis();
        // vn.setAutoRangeIncludesZero(true);
        DecimalFormat df = new DecimalFormat("#0.00");
        vn.setNumberFormatOverride(df); // 数据轴数据标签的显示格式*/
        // x轴设置
        CategoryAxis domainAxis = plot.getDomainAxis();
        domainAxis.setLabelFont(labelFont);// 轴标题
        domainAxis.setTickLabelFont(labelFont);// 轴数值

        // Lable(Math.PI/3.0)度倾斜
        // domainAxis.setCategoryLabelPositions(CategoryLabelPositions
        // .createUpRotationLabelPositions(Math.PI / 3.0));

        domainAxis.setMaximumCategoryLabelWidthRatio(0.6f);// 横轴上的 Lable 是否完整显示

        // 设置距离图片左端距离
        domainAxis.setLowerMargin(0.1);
        // 设置距离图片右端距离
        domainAxis.setUpperMargin(0.1);
        // 设置 columnKey 是否间隔显示
        // domainAxis.setSkipCategoryLabelsToFit(true);

        plot.setDomainAxis(domainAxis);
        // 设置柱图背景色(注意,系统取色的时候要使用16位的模式来查看颜色编码,这样比较准确)
        plot.setBackgroundPaint(new Color(255, 255, 204));

        // y轴设置
        ValueAxis rangeAxis = plot.getRangeAxis();
        rangeAxis.setLabelFont(labelFont);
        rangeAxis.setTickLabelFont(labelFont);
        // 设置最高的一个 Item 与图片顶端的距离
        rangeAxis.setUpperMargin(0.15);
        // 设置最低的一个 Item 与图片底端的距离
        rangeAxis.setLowerMargin(0.15);
        plot.setRangeAxis(rangeAxis);

        BarRenderer renderer = new BarRenderer();
        // 设置柱子宽度
        renderer.setMaximumBarWidth(0.05);
        // 设置柱子高度
        renderer.setMinimumBarLength(0.2);
        // 设置柱子边框颜色
        renderer.setBaseOutlinePaint(Color.BLACK);
        // 设置柱子边框可见
        renderer.setDrawBarOutline(true);

        // // 设置柱的颜色
        renderer.setSeriesPaint(0, new Color(204, 255, 255));
        renderer.setSeriesPaint(1, new Color(153, 204, 255));
        renderer.setSeriesPaint(2, new Color(51, 204, 204));

        // 设置每个地区所包含的平行柱的之间距离
        renderer.setItemMargin(0.0);

        // 显示每个柱的数值,并修改该数值的字体属性
        renderer.setIncludeBaseInRange(true);
        renderer
                .setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
        renderer.setBaseItemLabelsVisible(true);

        plot.setRenderer(renderer);
        // 设置柱的透明度
        plot.setForegroundAlpha(1.0f);

        FileOutputStream fos_jpg = null;
        try {<!-- -->
            isChartPathExist(CHART_PATH);
            String chartName = CHART_PATH + charName;
            fos_jpg = new FileOutputStream(chartName);
            ChartUtilities.writeChartAsPNG(fos_jpg, chart, 500, 500, true, 10);
            return chartName;
        } catch (Exception e) {<!-- -->
            e.printStackTrace();
            return null;
        } finally {<!-- -->
            try {<!-- -->
                fos_jpg.close();
            } catch (Exception e) {<!-- -->
                e.printStackTrace();
            }
        }
    }

    /**
     * 柱状图 返回JFreeChart
     *
     * @param dataset    数据集
     * @param xName      x轴的说明(如种类,时间等)
     * @param yName      y轴的说明(如速度,时间等)
     * @param chartTitle 图标题
     * @param charName   生成图片的名字
     * @return JFreeChart
     */
    public JFreeChart createBarChart2(CategoryDataset dataset, String xName,
                                      String yName, String chartTitle, String charName) {<!-- -->
        JFreeChart chart = ChartFactory.createBarChart(chartTitle, // 图表标题
                xName, // 目录轴的显示标签
                yName, // 数值轴的显示标签
                dataset, // 数据集
                PlotOrientation.VERTICAL, // 图表方向:水平、垂直
                false, // 是否显示图例(对于简单的柱状图必须是false),(true时,x轴legend下柱子的标题)
                false, // 是否生成工具
                false // 是否生成URL链接
        );
        //Font labelFont = new Font("SansSerif", Font.TRUETYPE_FONT, 12);
        Font labelFont = new Font("宋体", Font.BOLD, 15);
        //设置整个图片的标题字体
        chart.getTitle().setFont(labelFont);
        //设置x轴上代表柱子的标题,与上面legend:true 配合使用
        // chart.getLegend().setItemFont(labelFont);
        /*
         * VALUE_TEXT_ANTIALIAS_OFF表示将文字的抗锯齿关闭,
         * 使用的关闭抗锯齿后,字体尽量选择12到14号的宋体字,这样文字最清晰好看
         */
        // chart.getRenderingHints().put(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);
        chart.setTextAntiAlias(false);
        chart.setBackgroundPaint(Color.white);
        // create plot
        CategoryPlot plot = chart.getCategoryPlot();
        // 设置横虚线可见
        plot.setRangeGridlinesVisible(true);
        // 虚线色彩
        plot.setRangeGridlinePaint(Color.gray);

        // 数据轴精度
/*        NumberAxis vn = (NumberAxis) plot.getRangeAxis();
        // vn.setAutoRangeIncludesZero(true);
        DecimalFormat df = new DecimalFormat("#0.00");
        vn.setNumberFormatOverride(df); // 数据轴数据标签的显示格式*/
        // x轴设置
        CategoryAxis domainAxis = plot.getDomainAxis();
        domainAxis.setLabelFont(labelFont);// 轴标题
        domainAxis.setTickLabelFont(labelFont);// 轴数值

        // Lable(Math.PI/3.0)度倾斜
        // domainAxis.setCategoryLabelPositions(CategoryLabelPositions
        // .createUpRotationLabelPositions(Math.PI / 3.0));

        domainAxis.setMaximumCategoryLabelWidthRatio(0.6f);// 横轴上的 Lable 是否完整显示

        // 设置距离图片左端距离
        domainAxis.setLowerMargin(0.1);
        // 设置距离图片右端距离
        domainAxis.setUpperMargin(0.1);
        // 设置 columnKey 是否间隔显示
        // domainAxis.setSkipCategoryLabelsToFit(true);

        plot.setDomainAxis(domainAxis);
        // 设置柱图背景色(注意,系统取色的时候要使用16位的模式来查看颜色编码,这样比较准确)
        plot.setBackgroundPaint(new Color(255, 255, 204));

        // y轴设置
        ValueAxis rangeAxis = plot.getRangeAxis();
        rangeAxis.setLabelFont(labelFont);
        rangeAxis.setTickLabelFont(labelFont);
        // 设置最高的一个 Item 与图片顶端的距离
        rangeAxis.setUpperMargin(0.15);
        // 设置最低的一个 Item 与图片底端的距离
        rangeAxis.setLowerMargin(0.15);
        plot.setRangeAxis(rangeAxis);

        BarRenderer renderer = new BarRenderer();
        // 设置柱子宽度
        renderer.setMaximumBarWidth(0.05);
        // 设置柱子高度
        renderer.setMinimumBarLength(0.2);
        // 设置柱子边框颜色
        renderer.setBaseOutlinePaint(Color.BLACK);
        // 设置柱子边框可见
        renderer.setDrawBarOutline(true);

        // // 设置柱的颜色
        renderer.setSeriesPaint(0, new Color(204, 255, 255));
        renderer.setSeriesPaint(1, new Color(153, 204, 255));
        renderer.setSeriesPaint(2, new Color(51, 204, 204));

        // 设置每个地区所包含的平行柱的之间距离
        renderer.setItemMargin(0.0);

        // 显示每个柱的数值,并修改该数值的字体属性
        renderer.setIncludeBaseInRange(true);
        renderer
                .setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
        renderer.setBaseItemLabelsVisible(true);

        plot.setRenderer(renderer);
        // 设置柱的透明度
        plot.setForegroundAlpha(1.0f);

        FileOutputStream fos_jpg = null;
        return chart;
    }

    /**
     * 横向图
     *
     * @param dataset    数据集
     * @param xName      x轴的说明(如种类,时间等)
     * @param yName      y轴的说明(如速度,时间等)
     * @param chartTitle 图标题
     * @param charName   生成图片的名字
     * @return
     */
    public String createHorizontalBarChart(CategoryDataset dataset,
                                           String xName, String yName, String chartTitle, String charName) {<!-- -->
        JFreeChart chart = ChartFactory.createBarChart(chartTitle, // 图表标题
                xName, // 目录轴的显示标签
                yName, // 数值轴的显示标签
                dataset, // 数据集
                PlotOrientation.VERTICAL, // 图表方向:水平、垂直
                true, // 是否显示图例(对于简单的柱状图必须是false)
                false, // 是否生成工具
                false // 是否生成URL链接
        );

        CategoryPlot plot = chart.getCategoryPlot();
        // 数据轴精度
        NumberAxis vn = (NumberAxis) plot.getRangeAxis();
        // 设置刻度必须从0开始
        // vn.setAutoRangeIncludesZero(true);
        DecimalFormat df = new DecimalFormat("#0.00");
        vn.setNumberFormatOverride(df); // 数据轴数据标签的显示格式

        CategoryAxis domainAxis = plot.getDomainAxis();

        domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45); // 横轴上的
        // Lable
        Font labelFont = new Font("SansSerif", Font.TRUETYPE_FONT, 12);

        domainAxis.setLabelFont(labelFont);// 轴标题
        domainAxis.setTickLabelFont(labelFont);// 轴数值

        domainAxis.setMaximumCategoryLabelWidthRatio(0.8f);// 横轴上的 Lable 是否完整显示
        // domainAxis.setVerticalCategoryLabels(false);
        plot.setDomainAxis(domainAxis);

        ValueAxis rangeAxis = plot.getRangeAxis();
        // 设置最高的一个 Item 与图片顶端的距离
        rangeAxis.setUpperMargin(0.15);
        // 设置最低的一个 Item 与图片底端的距离
        rangeAxis.setLowerMargin(0.15);
        plot.setRangeAxis(rangeAxis);
        BarRenderer renderer = new BarRenderer();
        // 设置柱子宽度
        renderer.setMaximumBarWidth(0.03);
        // 设置柱子高度
        renderer.setMinimumBarLength(30);

        renderer.setBaseOutlinePaint(Color.BLACK);

        // 设置柱的颜色
        renderer.setSeriesPaint(0, Color.GREEN);
        renderer.setSeriesPaint(1, new Color(0, 0, 255));
        // 设置每个地区所包含的平行柱的之间距离
        renderer.setItemMargin(0.5);
        // 显示每个柱的数值,并修改该数值的字体属性
        renderer
                .setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
        // 设置柱的数值可见
        renderer.setBaseItemLabelsVisible(true);

        plot.setRenderer(renderer);
        // 设置柱的透明度
        plot.setForegroundAlpha(0.6f);

        FileOutputStream fos_jpg = null;
        try {<!-- -->
            isChartPathExist(CHART_PATH);
            String chartName = CHART_PATH + charName;
            fos_jpg = new FileOutputStream(chartName);
            ChartUtilities.writeChartAsPNG(fos_jpg, chart, 500, 500, true, 10);
            return chartName;
        } catch (Exception e) {<!-- -->
            e.printStackTrace();
            return null;
        } finally {<!-- -->
            try {<!-- -->
                fos_jpg.close();
            } catch (Exception e) {<!-- -->
                e.printStackTrace();
            }
        }
    }

    /**
     * 饼状图
     *
     * @param dataset    数据集
     * @param chartTitle 图标题
     * @param charName   生成图的名字
     * @param pieKeys    分饼的名字集
     * @return
     */
    public String createValidityComparePimChar(PieDataset dataset,
                                               String chartTitle, String charName, String[] pieKeys) {<!-- -->
        JFreeChart chart = ChartFactory.createPieChart3D(chartTitle, // chart
                // title
                dataset,// data
                true,// include legend
                true, false);

        // 使下说明标签字体清晰,去锯齿类似于
        // chart.getRenderingHints().put(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_OFF);的效果
        chart.setTextAntiAlias(false);
        // 图片背景色
        chart.setBackgroundPaint(Color.white);
        // 设置图标题的字体重新设置title
        Font font = new Font("隶书", Font.BOLD, 25);
        TextTitle title = new TextTitle(chartTitle);
        title.setFont(font);
        chart.setTitle(title);

        PiePlot3D plot = (PiePlot3D) chart.getPlot();
        // 图片中显示百分比:默认方式

        // 指定饼图轮廓线的颜色
        // plot.setBaseSectionOutlinePaint(Color.BLACK);
        // plot.setBaseSectionPaint(Color.BLACK);

        // 设置无数据时的信息
        plot.setNoDataMessage("无对应的数据,请重新查询。");

        // 设置无数据时的信息显示颜色
        plot.setNoDataMessagePaint(Color.red);

        // 图片中显示百分比:自定义方式,{0} 表示选项, {1} 表示数值, {2} 表示所占比例 ,小数点后两位
        plot.setLabelGenerator(new StandardPieSectionLabelGenerator(
                "{0}={1}({2})", NumberFormat.getNumberInstance(),
                new DecimalFormat("0.00%")));
        // 图例显示百分比:自定义方式, {0} 表示选项, {1} 表示数值, {2} 表示所占比例
        plot.setLegendLabelGenerator(new StandardPieSectionLabelGenerator(
                "{0}={1}({2})"));

        plot.setLabelFont(new Font("SansSerif", Font.TRUETYPE_FONT, 12));

        // 指定图片的透明度(0.0-1.0)
        plot.setForegroundAlpha(0.65f);
        // 指定显示的饼图上圆形(false)还椭圆形(true)
        plot.setCircular(false, true);

        // 设置第一个 饼块section 的开始位置,默认是12点钟方向
        plot.setStartAngle(90);

        // // 设置分饼颜色
        plot.setSectionPaint(pieKeys[0], new Color(244, 194, 144));
        plot.setSectionPaint(pieKeys[1], new Color(144, 233, 144));

        FileOutputStream fos_jpg = null;
        try {<!-- -->
            // 文件夹不存在则创建
            isChartPathExist(CHART_PATH);
            String chartName = CHART_PATH + charName;
            fos_jpg = new FileOutputStream(chartName);
            // 高宽的设置影响椭圆饼图的形状
            ChartUtilities.writeChartAsPNG(fos_jpg, chart, 500, 230);

            return chartName;
        } catch (Exception e) {<!-- -->
            e.printStackTrace();
            return null;
        } finally {<!-- -->
            try {<!-- -->
                fos_jpg.close();
                System.out.println("create pie-chart.");
            } catch (Exception e) {<!-- -->
                e.printStackTrace();
            }
        }

    }

    /**
     * 判断文件夹是否存在,如果不存在则新建
     *
     * @param chartPath
     */
    private void isChartPathExist(String chartPath) {<!-- -->
        File file = new File(chartPath);
        if (!file.exists()) {<!-- -->
            file.mkdirs();
            // log.info("CHART_PATH="+CHART_PATH+"create.");
        }
    }

    /**
     * 折线图
     *
     * @param chartTitle
     * @param x
     * @param y
     * @param xyDataset
     * @param charName
     * @return
     */
    public String createTimeXYChar(String chartTitle, String x, String y,
                                   CategoryDataset xyDataset, String charName) {<!-- -->
        JFreeChart chart = ChartFactory.createLineChart(chartTitle, x, y,
                xyDataset, PlotOrientation.VERTICAL, true, true, false);

        chart.setTextAntiAlias(false);
        chart.setBackgroundPaint(Color.WHITE);
        // 设置图标题的字体重新设置title
        Font font = new Font("隶书", Font.BOLD, 25);
        TextTitle title = new TextTitle(chartTitle);
        title.setFont(font);
        chart.setTitle(title);
        // 设置面板字体
        Font labelFont = new Font("SansSerif", Font.TRUETYPE_FONT, 12);

        chart.setBackgroundPaint(Color.WHITE);

        CategoryPlot categoryplot = (CategoryPlot) chart.getPlot();
        // x轴 // 分类轴网格是否可见
        categoryplot.setDomainGridlinesVisible(true);
        // y轴 //数据轴网格是否可见
        categoryplot.setRangeGridlinesVisible(true);

        categoryplot.setRangeGridlinePaint(Color.WHITE);// 虚线色彩

        categoryplot.setDomainGridlinePaint(Color.WHITE);// 虚线色彩

        categoryplot.setBackgroundPaint(Color.lightGray);

        // 设置轴和面板之间的距离
        // categoryplot.setAxisOffset(new RectangleInsets(5D, 5D, 5D, 5D));

        CategoryAxis domainAxis = categoryplot.getDomainAxis();

        domainAxis.setLabelFont(labelFont);// 轴标题
        domainAxis.setTickLabelFont(labelFont);// 轴数值

        domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45); // 横轴上的
        // Lable
        // 45度倾斜
        // 设置距离图片左端距离
        domainAxis.setLowerMargin(0.0);
        // 设置距离图片右端距离
        domainAxis.setUpperMargin(0.0);

        NumberAxis numberaxis = (NumberAxis) categoryplot.getRangeAxis();
        numberaxis.setStandardTickUnits(NumberAxis.createIntegerTickUnits());
        numberaxis.setAutoRangeIncludesZero(true);

        // 获得renderer 注意这里是下嗍造型到lineandshaperenderer!!
        LineAndShapeRenderer lineandshaperenderer = (LineAndShapeRenderer) categoryplot
                .getRenderer();

        lineandshaperenderer.setBaseShapesVisible(true); // series 点(即数据点)可见
        lineandshaperenderer.setBaseLinesVisible(true); // series 点(即数据点)间有连线可见

        // 显示折点数据
        // lineandshaperenderer.setBaseItemLabelGenerator(new
        // StandardCategoryItemLabelGenerator());
        // lineandshaperenderer.setBaseItemLabelsVisible(true);

        FileOutputStream fos_jpg = null;
        try {<!-- -->
            isChartPathExist(CHART_PATH);
            String chartName = CHART_PATH + charName;
            fos_jpg = new FileOutputStream(chartName);

            // 将报表保存为png文件
            ChartUtilities.writeChartAsPNG(fos_jpg, chart, 500, 510);

            return chartName;
        } catch (Exception e) {<!-- -->
            e.printStackTrace();
            return null;
        } finally {<!-- -->
            try {<!-- -->
                fos_jpg.close();
                System.out.println("create time-createTimeXYChar.");
            } catch (Exception e) {<!-- -->
                e.printStackTrace();
            }
        }
    }

    /**
     * 堆栈柱状图
     *
     * @param dataset
     * @param xName
     * @param yName
     * @param chartTitle
     * @param charName
     * @return
     */
    public String createStackedBarChart(CategoryDataset dataset, String xName,
                                        String yName, String chartTitle, String charName) {<!-- -->
        // 1:得到 CategoryDataset

        // 2:JFreeChart对象
        JFreeChart chart = ChartFactory.createStackedBarChart(chartTitle, // 图表标题
                xName, // 目录轴的显示标签
                yName, // 数值轴的显示标签
                dataset, // 数据集
                PlotOrientation.VERTICAL, // 图表方向:水平、垂直
                true, // 是否显示图例(对于简单的柱状图必须是false)
                false, // 是否生成工具
                false // 是否生成URL链接
        );
        // 图例字体清晰
        chart.setTextAntiAlias(false);

        chart.setBackgroundPaint(Color.WHITE);

        // 2 .2 主标题对象 主标题对象是 TextTitle 类型
        chart
                .setTitle(new TextTitle(chartTitle, new Font("隶书", Font.BOLD,
                        25)));
        // 2 .2.1:设置中文
        // x,y轴坐标字体
        Font labelFont = new Font("SansSerif", Font.TRUETYPE_FONT, 12);

        // 2 .3 Plot 对象 Plot 对象是图形的绘制结构对象
        CategoryPlot plot = chart.getCategoryPlot();

        // 设置横虚线可见
        plot.setRangeGridlinesVisible(true);
        // 虚线色彩
        plot.setRangeGridlinePaint(Color.gray);

        // 数据轴精度
        NumberAxis vn = (NumberAxis) plot.getRangeAxis();
        // 设置最大值是1
        vn.setUpperBound(1);
        // 设置数据轴坐标从0开始
        // vn.setAutoRangeIncludesZero(true);
        // 数据显示格式是百分比
        DecimalFormat df = new DecimalFormat("0.00%");
        vn.setNumberFormatOverride(df); // 数据轴数据标签的显示格式
        // DomainAxis (区域轴,相当于 x 轴), RangeAxis (范围轴,相当于 y 轴)
        CategoryAxis domainAxis = plot.getDomainAxis();

        domainAxis.setLabelFont(labelFont);// 轴标题
        domainAxis.setTickLabelFont(labelFont);// 轴数值

        // x轴坐标太长,建议设置倾斜,如下两种方式选其一,两种效果相同
        // 倾斜(1)横轴上的 Lable 45度倾斜
        // domainAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);
        // 倾斜(2)Lable(Math.PI 3.0)度倾斜
        // domainAxis.setCategoryLabelPositions(CategoryLabelPositions
        // .createUpRotationLabelPositions(Math.PI / 3.0));

        domainAxis.setMaximumCategoryLabelWidthRatio(0.6f);// 横轴上的 Lable 是否完整显示

        plot.setDomainAxis(domainAxis);

        // y轴设置
        ValueAxis rangeAxis = plot.getRangeAxis();
        rangeAxis.setLabelFont(labelFont);
        rangeAxis.setTickLabelFont(labelFont);
        // 设置最高的一个 Item 与图片顶端的距离
        rangeAxis.setUpperMargin(0.15);
        // 设置最低的一个 Item 与图片底端的距离
        rangeAxis.setLowerMargin(0.15);
        plot.setRangeAxis(rangeAxis);

        // Renderer 对象是图形的绘制单元
        StackedBarRenderer renderer = new StackedBarRenderer();
        // 设置柱子宽度
        renderer.setMaximumBarWidth(0.05);
        // 设置柱子高度
        renderer.setMinimumBarLength(0.1);
        // 设置柱的边框颜色
        renderer.setBaseOutlinePaint(Color.BLACK);
        // 设置柱的边框可见
        renderer.setDrawBarOutline(true);

        // // 设置柱的颜色(可设定也可默认)
        renderer.setSeriesPaint(0, new Color(204, 255, 204));
        renderer.setSeriesPaint(1, new Color(255, 204, 153));

        // 设置每个地区所包含的平行柱的之间距离
        renderer.setItemMargin(0.4);

        plot.setRenderer(renderer);
        // 设置柱的透明度(如果是3D的必须设置才能达到立体效果,如果是2D的设置则使颜色变淡)
        // plot.setForegroundAlpha(0.65f);

        FileOutputStream fos_jpg = null;
        try {<!-- -->
            isChartPathExist(CHART_PATH);
            String chartName = CHART_PATH + charName;
            fos_jpg = new FileOutputStream(chartName);
            ChartUtilities.writeChartAsPNG(fos_jpg, chart, 500, 500, true, 10);
            return chartName;
        } catch (Exception e) {<!-- -->
            e.printStackTrace();
            return null;
        } finally {<!-- -->
            try {<!-- -->
                fos_jpg.close();
            } catch (Exception e) {<!-- -->
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取图片流
     *
     * @param jfreechart
     * @param weight
     * @param height
     * @return
     */
    public static InputStream getChartStream(JFreeChart jfreechart, int weight, int height) {<!-- -->
        InputStream input = null;
        try {<!-- -->
            BufferedImage bufferedImage = jfreechart.createBufferedImage(weight, height);
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            ImageIO.write(bufferedImage, "png", os);
            input = new ByteArrayInputStream(os.toByteArray());
        } catch (Exception e) {<!-- -->
            e.printStackTrace();
            System.out.println("-------------------------------------" + e.getMessage());
        }
        return input;
    }


    /**
     * java 8 必须
     */
    @org.junit.Test
    public void createXWPFDocument() throws IOException, DocumentException, InvalidFormatException {<!-- -->
        System.out.println("createXWPFDocument==================");
        XWPFDocument doc = new XWPFDocument();
        double[][] data = new double[][]{<!-- -->{<!-- -->672, 766, 223, 540, 126}};
        String[] rowKeys = {<!-- -->"苹果"};
        String[] columnKeys = {<!-- -->"北京", "上海", "广州", "成都", "深圳"};
        CategoryDataset dataset = getBarData(data, rowKeys, columnKeys);
        JFreeChart jfreechart = this.createBarChart2(dataset, "", "", "柱状图", "barGroup.png");
        InputStream inputStream = getChartStream(jfreechart, 550, 300);

        XWPFParagraph paragraph = doc.createParagraph();
        XWPFRun run = paragraph.createRun();
        run.setBold(true); //加粗
        run.setText("加粗的内容");
        run.setColor("FF0000");
        run.setText("红色的字。");
        XWPFParagraph paragraph2 = doc.createParagraph();
        XWPFRun run2 = paragraph2.createRun();
        run2.addPicture(inputStream, XWPFDocument.PICTURE_TYPE_PNG, "图片1", Units.toEMU(400), Units.toEMU(300));
        OutputStream os = new FileOutputStream("E:\\picture\\test.docx");
        //把doc输出到输出流
        doc.write(os);
    }

    @org.junit.Test
    public void TestDocument() throws DocumentException {<!-- -->
        //创建文本
        Document doc = new Document(PageSize.A4);
        try {<!-- -->
            RtfWriter2.getInstance(doc,
                    new FileOutputStream("E://picture//test2.doc"));
            doc.open();

            double[][] data = new double[][]{<!-- -->{<!-- -->672, 766, 223, 540, 126}};
            String[] rowKeys = {<!-- -->"苹果"};
            String[] columnKeys = {<!-- -->"北京", "上海", "广州", "成都", "深圳"};
            CategoryDataset dataset = getBarData(data, rowKeys, columnKeys);
            JFreeChart jfreechart = this.createBarChart2(dataset, "", "", "柱状图", "barGroup.png");
            InputStream inputStream = getChartStream(jfreechart, 550, 300);

            com.lowagie.text.Font font = new com.lowagie.text.Font(com.lowagie.text.Font.NORMAL, 12, com.lowagie.text.Font.BOLD, new Color(0, 0, 0));
            Paragraph paragraph = new Paragraph("5.学生家长对学校开展爱国主义教育(活动形式、活动效果等)的评价", font);
            paragraph.setAlignment(1);
            Image img = Image.getInstance("E:\\picture\\bar.png");
            img.scaleAbsolute(400, 400);//自定义大小
            //img.scaleToFit(500, 300);//
            paragraph.add(img);
            doc.add(paragraph);


            doc.close();
            System.out.println("=============com.lowagie.text.Document");
        } catch (FileNotFoundException e) {<!-- -->
            e.printStackTrace();
        } catch (IOException e) {<!-- -->
            e.printStackTrace();
        }
    }
}