JFreeChart 中文乱码解决(不用添加iTextAsian.jar)

JFreeChart 中文乱码主要是缺少字体,可将其字体设置为系统存在的字体,乱码即可解决:

    public static java.awt.Font getFont(){
		java.awt.Font font;
		try {
			File fontFile = ResourceUtils.getFile("classpath:font/simsun.ttc");//字体文件要放在class path的font文件夹下
			GraphicsEnvironment gEnv = GraphicsEnvironment.getLocalGraphicsEnvironment();
			String[] evnfonts = gEnv.getAvailableFontFamilyNames();
			List<String> list = Arrays.asList(evnfonts);			
			if (!list.contains("宋体")) {//系统没有安装宋体,用字体文件创建一个
				font = java.awt.Font.createFont(java.awt.Font.TRUETYPE_FONT, fontFile);				
			} else {
				font = new java.awt.Font("宋体", java.awt.Font.PLAIN, 12);//读取系统字体
			}
			return font;
		} catch (FileNotFoundException e) {
			log.error("The font file is not exist! Please add the simsun font file to 'classpath:font/simsun.ttc'.");
		} catch (Exception e) {
			log.error("Error occured when creating simsun font.");
		}
		return null;		
    }

 设置JFreeChart 字体:

 

    public static JFreeChart createBarChart3D(DefaultCategoryDataset dataset,String title, String xAxisLabel, String yAxisLabel) {
		JFreeChart chart = ChartFactory.createBarChart3D(title, xAxisLabel, yAxisLabel, dataset, PlotOrientation.VERTICAL, false,
				false, false);
		CategoryPlot plot = chart.getCategoryPlot();	
		chart.setBackgroundPaint(Color.WHITE);

		BarRenderer3D renderer = new BarRenderer3D();
		renderer.setBaseOutlinePaint(Color.BLACK);
		renderer.setMaximumBarWidth(0.1);
		renderer.setSeriesPaint(0, new Color(20, 180, 20));

		renderer.setItemMargin(0.1);
		renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
		renderer.setItemLabelPaint(Color.BLACK);
		renderer.setItemLabelsVisible(true);
		renderer.setBaseItemLabelsVisible(true);
		renderer.setBasePositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_LEFT));
		plot.setRenderer(renderer);
		plot.setForegroundAlpha(0.8f);
		Font font = FontUtils.getFont();
		if(font != null){
			plot.getDomainAxis().setLabelFont(font);
			plot.getDomainAxis().setTickLabelFont(font);
			plot.getRangeAxis().setLabelFont(font);
			plot.getRangeAxis().setTickLabelFont(font);
			Font titleFont = font.deriveFont(Font.BOLD,22);		
			chart.getTitle().setFont(titleFont);
		}	
		return chart;
    }
 

simsun.ttc 字体的下载见:(文章的附件)

PDF iText 使用简单介绍(附中文乱码解决方案)

你可能感兴趣的:(java,jfreechart)