使用ItextPdf+Freemarker+jfreechart实现将数据+使用jfreechart生成的图表转为html,再转为pdf。

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.2</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>11</java.version>
    </properties>

    <dependencies>

        <dependency>
		    <groupId>com.itextpdf</groupId>
		    <artifactId>html2pdf</artifactId>
		    <version>2.1.4</version>
		  </dependency>

<!--        导出为HTML所用的依赖包-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
            <version>2.0.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>javax.mail</groupId>
            <artifactId>mail</artifactId>
            <version>1.4</version>
        </dependency>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>font-asian</artifactId>
            <version>7.1.2</version>
        </dependency>
        <dependency>
            <groupId>net.sourceforge.dynamicreports</groupId>
            <artifactId>dynamicreports-core</artifactId>
            <version>3.0.4</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-freemarker</artifactId>
            <version>2.3.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.jfree</groupId>
            <artifactId>jcommon</artifactId>
            <version>1.0.24</version>
        </dependency>
        <dependency>
            <groupId>org.jfree</groupId>
            <artifactId>jfreechart</artifactId>
            <version>1.0.19</version>
        </dependency>
        <dependency>
            <groupId>jfree</groupId>
            <artifactId>jfreechart-experimental</artifactId>
            <version>1.0.9</version>
        </dependency>
        <dependency>
            <groupId>cn.lesper</groupId>
            <artifactId>iTextAsian</artifactId>
            <version>3.0</version>
        </dependency>

        <dependency>
           <groupId>cn.afterturn</groupId>
           <artifactId>easypoi-base</artifactId>
           <version>4.1.0</version>
        </dependency>
        <dependency>
           <groupId>org.jfree</groupId>
           <artifactId>jcommon</artifactId>
           <version>1.0.24</version>
        </dependency>
        <dependency>
           <groupId>org.jfree</groupId>
           <artifactId>jfreechart</artifactId>
           <version>1.0.19</version>
        </dependency>

      <dependency>
          <groupId>org.projectlombok</groupId>
          <artifactId>lombok</artifactId>
          <version>1.16.18</version>
          <scope>provided</scope>
      </dependency>

        <dependency>
			<groupId>cn.afterturn</groupId>
			<artifactId>easypoi-base</artifactId>
			<version>4.1.0</version>
		</dependency>
		<dependency>
			<groupId>org.jfree</groupId>
			<artifactId>jcommon</artifactId>
			<version>1.0.24</version>
		</dependency>
		<dependency>
			<groupId>org.jfree</groupId>
			<artifactId>jfreechart</artifactId>
			<version>1.5.0</version>
		</dependency>

        <dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi-ooxml</artifactId>
			<version>4.1.2</version>
		</dependency>
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi-ooxml-schemas</artifactId>
			<version>4.1.2</version>
		</dependency>
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi</artifactId>
			<version>4.1.2</version>
		</dependency>
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi-scratchpad</artifactId>
			<version>4.1.2</version>
		</dependency>
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-collections4</artifactId>
			<version>4.4</version>
		</dependency>
		<dependency>
			<groupId>commons-codec</groupId>
			<artifactId>commons-codec</artifactId>
			<version>1.13</version>
		</dependency>
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-compress</artifactId>
			<version>1.19</version>
		</dependency>
		<dependency>
			<groupId>org.apache.xmlbeans</groupId>
			<artifactId>xmlbeans</artifactId>
			<version>3.1.0</version>
		</dependency>
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>ooxml-schemas</artifactId>
			<version>1.4</version>
		</dependency>


        <!--   easyexcel    -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel</artifactId>
            <version>2.2.7</version>
        </dependency>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext-asian</artifactId>
            <version>5.2.0</version>
        </dependency>

        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.5.10</version>
        </dependency>

<!--        <dependency>-->
<!--            <groupId>org.apache.poi</groupId>-->
<!--            <artifactId>poi-ooxml</artifactId>-->
<!--            <version>3.17</version>-->
<!--        </dependency>-->
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.7.17</version>
        </dependency>

<!--        <dependency>-->
<!--            <groupId>org.apache.poi</groupId>-->
<!--            <artifactId>poi-ooxml-schemas</artifactId>-->
<!--            <version>3.17</version>-->
<!--        </dependency>-->
        <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
        <dependency>
          <groupId>commons-io</groupId>
          <artifactId>commons-io</artifactId>
          <version>2.6</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.12.0</version>
        </dependency>
<!--        <dependency>-->
<!--          <groupId>org.apache.poi</groupId>-->
<!--          <artifactId>poi-ooxml</artifactId>-->
<!--          <version>3.17</version>-->
<!--        </dependency>-->
<!--        <dependency>-->
<!--            <groupId>org.apache.poi</groupId>-->
<!--            <artifactId>poi</artifactId>-->
<!--            <version>3.17</version>-->
<!--        </dependency>-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
            <version>2.6.1</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>
package com.example.demo.entity;

public class chartDto {

    private Double[] chartText;

    public Double[] getChartText() {
        return chartText;
    }

    public void setChartText(Double[] chartText) {
        this.chartText = chartText;
    }
}
package com.example.demo.entity;

import java.io.Serializable;
import java.util.Vector;

/**
 * 系列:名字和数据集合 构成一条曲线</br> 可以将serie看作一根线或者一根柱子:
 *
 * <p>
 * 参照JS图表来描述数据:</br> series: [{ name: 'Tokyo', data: [7.0, 6.9, 9.5, 14.5]
 * },</br> { name: 'New York', data: [-0.2, 0.8, 5.7, 11.3} ]</br>
 * </p>
 *
 * @author ccw
 * @date 2014-6-4
 */
public class Serie implements Serializable {

	private static final long serialVersionUID = 1L;
	private String name;// 名字
	private Vector<Object> data;// 数据值

	public Serie() {

	}

	/**
	 *
	 * @param name
	 *            名称(线条名称)
	 * @param data
	 *            数据(线条上的所有数据值)
	 */
	public Serie(String name, Vector<Object> data) {

		this.name = name;
		this.data = data;
	}

	/**
	 *
	 * @param name
	 *            名称(线条名称)
	 * @param array
	 *            数据(线条上的所有数据值)
	 */
	public Serie(String name, Object[] array) {
		this.name = name;
		if (array != null) {
			data = new Vector<Object>(array.length);
			for (int i = 0; i < array.length; i++) {
				data.add(array[i]);
			}
		}
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Vector<Object> getData() {
		return data;
	}

	public void setData(Vector<Object> data) {
		this.data = data;
	}

}
package com.example.demo.entity;

import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.write.style.ContentStyle;
import com.alibaba.excel.annotation.write.style.HeadFontStyle;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.poi.ss.usermodel.FillPatternType;

@AllArgsConstructor
@NoArgsConstructor
@Data
@Builder
@HeadFontStyle(fontHeightInPoints=14)

public class User {
    @ExcelProperty(value = "ID",index = 0)
    private Long id;
    @ExcelProperty(value = "用户名",index = 1)
    private String name;
    @ExcelProperty(value = "邮件",index = 2)
    private String email;
    @ExcelProperty(value = "生日",index = 3)
    private String birthdat;
    @ExcelProperty(value = "性别",index = 4)
    private String sex;
    private Double nm;
}
package com.example.demo.entity;


import java.util.List;

public class usera {
    private String title;
    private List<userSon> columnName;
    private String path;

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    public usera(String title, List<userSon> columnName) {
        this.title = title;
        this.columnName = columnName;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public usera() {
    }


    public List<userSon> getColumnName() {
        return columnName;
    }

    public void setColumnName(List<userSon> columnName) {
        this.columnName = columnName;
    }


}
package com.example.demo.entity;


public class userSon {
        private String name;
        private String age;
        private String email;
        private String csnr;
        private String oooo;
        private String pppp;
        private String iiii;
        private String uuuu;

    public String getCsnr() {
        return csnr;
    }

    public void setCsnr(String csnr) {
        this.csnr = csnr;
    }

    public String getOooo() {
        return oooo;
    }

    public void setOooo(String oooo) {
        this.oooo = oooo;
    }

    public String getPppp() {
        return pppp;
    }

    public void setPppp(String pppp) {
        this.pppp = pppp;
    }

    public String getIiii() {
        return iiii;
    }

    public void setIiii(String iiii) {
        this.iiii = iiii;
    }

    public String getUuuu() {
        return uuuu;
    }

    public void setUuuu(String uuuu) {
        this.uuuu = uuuu;
    }

    public userSon(String name, String age, String email) {
            this.name = name;
            this.age = age;
            this.email = email;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public userSon() {
        }

        public String getAge() {
            return age;
        }

        public void setAge(String age) {
            this.age = age;
        }

        public String getEmail() {
            return email;
        }

        public void setEmail(String email) {
            this.email = email;
        }
}
package com.example.demo.utils;

import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.stereotype.Component;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

@Component
public class base64 {
     public String getImgStr(String imgFile){
	//将图片文件转化为字节数组字符串,并对其进行Base64编码处理


	InputStream in = null;
	byte[] data = null;
	//读取图片字节数组
	try
	{
		in = new FileInputStream(imgFile);
		data = new byte[in.available()];
		in.read(data);
		in.close();
	}
		catch (IOException e)
	{
		e.printStackTrace();
	}
		return new String(Base64.encodeBase64(data));
	}
}
package com.example.demo.utils;

import java.awt.Color;
import java.util.Vector;

import com.example.demo.entity.Serie;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.block.BlockBorder;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.ui.RectangleEdge;

/**
 * 生成JFreeChart图表的工厂类<br/>
 * 目的:根据MVC的设计思想,数据与展现分离。调用者只需传入数据,即可生成图表。
 *
 * @author liuyimin
 *
 */
public class ChartFactory {
	/**
	 * 生成柱状图
	 *
	 * @param title
	 *            柱状图的标题
	 * @param categoryAxisLabel
	 *            x轴标题
	 * @param valueAxisLabel
	 *            y轴标题
	 * @param series
	 *            数据
	 * @param categories
	 *            类别
	 * @return
	 */
	public static JFreeChart createBarChart(String title,
											String categoryAxisLabel, String valueAxisLabel,
											Vector<Serie> series, String[] categories) {
		// 1:创建数据集合
		DefaultCategoryDataset dataset = ChartUtils
				.createDefaultCategoryDataset(series, categories);
		JFreeChart chart = org.jfree.chart.ChartFactory.createBarChart(title,
				categoryAxisLabel, valueAxisLabel, dataset, PlotOrientation.VERTICAL,false,false,false);
		// 3:设置抗锯齿,防止字体显示不清楚
		ChartUtilsAbandon.setAntiAlias(chart);// 抗锯齿
		// 4:对柱子进行渲染
		ChartUtilsAbandon.setBarRenderer(chart.getCategoryPlot(), false);//
		// 5:对其他部分进行渲染
		ChartUtilsAbandon.setXAixs(chart.getCategoryPlot());// X坐标轴渲染
		ChartUtilsAbandon.setYAixs(chart.getCategoryPlot());// Y坐标轴渲染
//		// 设置标注无边框
//		chart.getLegend().setFrame(new BlockBorder(Color.WHITE));
		return chart;
	}

	/**
	 * 生成饼图
	 *
	 * @param title
	 *            饼图的标题
	 * @param categories
	 *            类别
	 * @param datas
	 *            数据
	 * @return
	 */
	public static JFreeChart createPieChart(String title, String[] categories,
			Object[] datas) {
		// 1:创建数据集合
		DefaultPieDataset dataset = ChartUtils.createDefaultPieDataset(
				categories, datas);
		JFreeChart chart = org.jfree.chart.ChartFactory.createPieChart(title,
				dataset,false,false,false);
		// 3:设置抗锯齿,防止字体显示不清楚
		ChartUtilsAbandon.setAntiAlias(chart);// 抗锯齿
		// 4:对柱子进行渲染[创建不同图形]
		ChartUtilsAbandon.setPieRender(chart.getPlot());
		/**
		 * 可以注释测试
		 */
		// plot.setSimpleLabels(true);//简单标签,不绘制线条
		// plot.setLabelGenerator(null);//不显示数字
		// 设置标注无边框
//		chart.getLegend().setFrame(new BlockBorder(Color.WHITE));
		// 标注位于右侧
//		chart.getLegend().setPosition(RectangleEdge.RIGHT);
		return chart;
	}

	/**
	 * 生成折线图
	 *
	 * @param title
	 *            折线图的标题
	 * @param categoryAxisLabel
	 *            x轴标题
	 * @param valueAxisLabel
	 *            y轴标题
	 * @param series
	 *            数据
	 * @param categories
	 *            类别
	 * @return
	 */
	public static JFreeChart createLineChart(String title,
			String categoryAxisLabel, String valueAxisLabel,
			Vector<Serie> series, String[] categories) {
		// 1:创建数据集合
		DefaultCategoryDataset dataset = ChartUtils
				.createDefaultCategoryDataset(series, categories);
		JFreeChart chart = org.jfree.chart.ChartFactory.createLineChart(title,
				categoryAxisLabel, valueAxisLabel, dataset,PlotOrientation.VERTICAL,false,false,false);
		// 3:设置抗锯齿,防止字体显示不清楚
		ChartUtilsAbandon.setAntiAlias(chart);// 抗锯齿
		// 4:对柱子进行渲染[[采用不同渲染]]
		ChartUtilsAbandon.setLineRender(chart.getCategoryPlot(), false, false);//
		// 5:对其他部分进行渲染
		ChartUtilsAbandon.setXAixs(chart.getCategoryPlot());// X坐标轴渲染
		ChartUtilsAbandon.setYAixs(chart.getCategoryPlot());// Y坐标轴渲染
		// 设置标注无边框
//		chart.getLegend().setFrame(new BlockBorder(Color.WHITE));
		return chart;
	}

	/**
	 * 生成StackedBarChart
	 *
	 * @param title
	 *            StackedBarChart的标题
	 * @param domainAxisLabel
	 * @param rangeAxisLabel
	 * @param series
	 *            数据
	 * @param categories
	 *            类别
	 * @return
	 */
	public static JFreeChart createStackedBarChart(String title,
			String domainAxisLabel, String rangeAxisLabel,
			Vector<Serie> series, String[] categories) {
		// 1:创建数据集合
		DefaultCategoryDataset dataset = ChartUtils
				.createDefaultCategoryDataset(series, categories);
		JFreeChart chart = org.jfree.chart.ChartFactory.createStackedBarChart(
				title, domainAxisLabel, rangeAxisLabel, dataset,PlotOrientation.VERTICAL,false,false,false);
		// 3:设置抗锯齿,防止字体显示不清楚
		ChartUtilsAbandon.setAntiAlias(chart);// 抗锯齿
		// 4:对柱子进行渲染[创建不同图形]
		ChartUtilsAbandon.setStackBarRender(chart.getCategoryPlot());
		// 5:对其他部分进行渲染
		ChartUtilsAbandon.setXAixs(chart.getCategoryPlot());// X坐标轴渲染
		ChartUtilsAbandon.setYAixs(chart.getCategoryPlot());// Y坐标轴渲染
		// 设置标注无边框
//		chart.getLegend().setFrame(new BlockBorder(Color.WHITE));
		return chart;
	}
}
package com.example.demo.utils;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Paint;
import java.awt.Rectangle;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Vector;

import com.example.demo.entity.Serie;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.StandardChartTheme;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.axis.DateTickUnit;
import org.jfree.chart.axis.DateTickUnitType;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.block.BlockBorder;
import org.jfree.chart.labels.ItemLabelAnchor;
import org.jfree.chart.labels.ItemLabelPosition;
import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;
import org.jfree.chart.labels.StandardPieSectionLabelGenerator;
import org.jfree.chart.labels.StandardXYItemLabelGenerator;
import org.jfree.chart.labels.StandardXYToolTipGenerator;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.DefaultDrawingSupplier;
import org.jfree.chart.plot.PieLabelLinkStyle;
import org.jfree.chart.plot.PiePlot;
import org.jfree.chart.plot.Plot;
import org.jfree.chart.plot.XYPlot;
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.renderer.category.StandardBarPainter;
import org.jfree.chart.renderer.xy.StandardXYBarPainter;
import org.jfree.chart.renderer.xy.XYBarRenderer;
import org.jfree.chart.renderer.xy.XYLineAndShapeRenderer;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.time.Day;
import org.jfree.data.time.TimeSeries;
import org.jfree.ui.RectangleInsets;
import org.jfree.ui.TextAnchor;

/**
 * Jfreechart工具类
 * <p>
 * 解决中文乱码问题<br>
 * 用来创建类别图表数据集、创建饼图数据集、时间序列图数据集<br>
 * 用来对柱状图、折线图、饼图、堆积柱状图、时间序列图的样式进行渲染<br>
 * 设置X-Y坐标轴样式
 * <p>
 *
 *
 * @author chenchangwen
 * @since:2014-2-18
 *
 */
public class ChartUtils {
	private static String NO_DATA_MSG = "数据加载失败";
	private static Font FONT = new Font("宋体", Font.PLAIN, 12);
	public static Color[] CHART_COLORS = { new Color(31, 129, 188),
			new Color(92, 92, 97), new Color(144, 237, 125),
			new Color(255, 188, 117), new Color(153, 158, 255),
			new Color(255, 117, 153), new Color(253, 236, 109),
			new Color(128, 133, 232), new Color(158, 90, 102),
			new Color(255, 204, 102) };// 颜色

	static {
		setChartTheme();
	}

	public ChartUtils() {
	}

	/**
	 * 中文主题样式 解决乱码
	 */
	public static void setChartTheme() {
		// 设置中文主题样式 解决乱码
		StandardChartTheme chartTheme = new StandardChartTheme("CN");
		// 设置标题字体
		chartTheme.setExtraLargeFont(FONT);
		// 设置图例的字体
		chartTheme.setRegularFont(FONT);
		// 设置轴向的字体
		chartTheme.setLargeFont(FONT);
//		chartTheme.setSmallFont(FONT);
		chartTheme.setTitlePaint(new Color(51, 51, 51));
		chartTheme.setSubtitlePaint(new Color(85, 85, 85));

		chartTheme.setLegendBackgroundPaint(Color.WHITE);// 设置标注
		chartTheme.setLegendItemPaint(Color.pink);//
		chartTheme.setChartBackgroundPaint(Color.WHITE);
		// 绘制颜色绘制颜色.轮廓供应商
		// paintSequence,outlinePaintSequence,strokeSequence,outlineStrokeSequence,shapeSequence

		Paint[] OUTLINE_PAINT_SEQUENCE = new Paint[] { Color.WHITE };
		// 绘制器颜色源
		DefaultDrawingSupplier drawingSupplier = new DefaultDrawingSupplier(
				CHART_COLORS, CHART_COLORS, OUTLINE_PAINT_SEQUENCE,
				DefaultDrawingSupplier.DEFAULT_STROKE_SEQUENCE,
				DefaultDrawingSupplier.DEFAULT_OUTLINE_STROKE_SEQUENCE,
				DefaultDrawingSupplier.DEFAULT_SHAPE_SEQUENCE);
		chartTheme.setDrawingSupplier(drawingSupplier);

		chartTheme.setPlotBackgroundPaint(Color.WHITE);// 绘制区域
		chartTheme.setPlotOutlinePaint(Color.WHITE);// 绘制区域外边框
		chartTheme.setLabelLinkPaint(new Color(8, 55, 114));// 链接标签颜色
		chartTheme.setLabelLinkStyle(PieLabelLinkStyle.CUBIC_CURVE);

		chartTheme.setAxisOffset(new RectangleInsets(5, 12, 5, 12));
		chartTheme.setDomainGridlinePaint(new Color(192, 208, 224));// X坐标轴垂直网格颜色
		chartTheme.setRangeGridlinePaint(new Color(192, 192, 192));// Y坐标轴水平网格颜色

//		chartTheme.setBaselinePaint(Color.WHITE);
		chartTheme.setCrosshairPaint(Color.BLUE);// 不确定含义
		chartTheme.setAxisLabelPaint(new Color(51, 51, 51));// 坐标轴标题文字颜色
		chartTheme.setTickLabelPaint(new Color(15, 21, 248));// 刻度数字
		chartTheme.setBarPainter(new StandardBarPainter());// 设置柱状图渲染
		chartTheme.setXYBarPainter(new StandardXYBarPainter());// XYBar 渲染

		chartTheme.setItemLabelPaint(Color.black);
		chartTheme.setThermometerPaint(Color.white);// 温度计

		ChartFactory.setChartTheme(chartTheme);
	}

	/**
	 * 必须设置文本抗锯齿
	 */
	public static void setAntiAlias(JFreeChart chart) {
		chart.setTextAntiAlias(false);

	}

	/**
	 * 设置图例无边框,默认黑色边框
	 */
	public static void setLegendEmptyBorder(JFreeChart chart) {
		chart.getLegend().setFrame(new BlockBorder(Color.WHITE));

	}

	/**
	 * 创建类别数据集合
	 */
	public static DefaultCategoryDataset createDefaultCategoryDataset(
			Vector<Serie> series, String[] categories) {
		DefaultCategoryDataset dataset = new DefaultCategoryDataset();

		for (Serie serie : series) {
			String name = serie.getName();
			System.out.println(name);
			Vector<Object> data = serie.getData();
			if (data != null && categories != null
					&& data.size() == categories.length) {
				for (int index = 0; index < data.size(); index++) {
					String value = data.get(index) == null ? "" : data.get(
							index).toString();
					if (isPercent(value)) {
						value = value.substring(0, value.length() - 1);
					}
					if (isNumber(value)) {
						dataset.setValue(Double.parseDouble(value), name,
								categories[index]);
					}
				}
			}

		}
		return dataset;

	}

	/**
	 * 创建饼图数据集合
	 */
	public static DefaultPieDataset createDefaultPieDataset(
			String[] categories, Object[] datas) {
		DefaultPieDataset dataset = new DefaultPieDataset();
		for (int i = 0; i < categories.length && categories != null; i++) {
			String value = datas[i].toString();
			if (isPercent(value)) {
				value = value.substring(0, value.length() - 1);
			}
			if (isNumber(value)) {
				dataset.setValue(categories[i], Double.valueOf(value));
			}
		}
		return dataset;

	}

	/**
	 * 创建时间序列数据
	 *
	 * @param category
	 *            类别
	 * @param dateValues
	 *            日期-值 数组
	 * @return
	 */
	public static TimeSeries createTimeseries(String category,
			Vector<Object[]> dateValues) {
		TimeSeries timeseries = new TimeSeries(category);

		if (dateValues != null) {
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
			for (Object[] objects : dateValues) {
				Date date = null;
				try {
					date = dateFormat.parse(objects[0].toString());
				} catch (ParseException e) {
				}
				String sValue = objects[1].toString();
				double dValue = 0;
				if (date != null && isNumber(sValue)) {
					dValue = Double.parseDouble(sValue);
					timeseries.add(new Day(date), dValue);
				}
			}
		}

		return timeseries;
	}

	/**
	 * 设置 折线图样式
	 *
	 * @param plot
	 * @param isShowDataLabels
	 *            是否显示数据标签 默认不显示节点形状
	 */
	public static void setLineRender(CategoryPlot plot, boolean isShowDataLabels) {
		setLineRender(plot, isShowDataLabels, false);
	}

	/**
	 * 设置折线图样式
	 *
	 * @param plot
	 * @param isShowDataLabels
	 *            是否显示数据标签
	 */
	@SuppressWarnings("deprecation")
	public static void setLineRender(CategoryPlot plot,
			boolean isShowDataLabels, boolean isShapesVisible) {
		plot.setNoDataMessage(NO_DATA_MSG);
		plot.setInsets(new RectangleInsets(10, 10, 0, 10), false);
		LineAndShapeRenderer renderer = (LineAndShapeRenderer) plot
				.getRenderer();

		renderer.setStroke(new BasicStroke(1.5F));
		if (isShowDataLabels) {
			renderer.setBaseItemLabelsVisible(true);
			renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator(
					StandardCategoryItemLabelGenerator.DEFAULT_LABEL_FORMAT_STRING,
					NumberFormat.getInstance()));
			renderer.setBasePositiveItemLabelPosition(new ItemLabelPosition(
					ItemLabelAnchor.OUTSIDE1, TextAnchor.BOTTOM_CENTER));// weizhi
		}
		renderer.setBaseShapesVisible(isShapesVisible);// 数据点绘制形状
		setXAixs(plot);
		setYAixs(plot);

	}

	/**
	 * 设置时间序列图样式
	 *
	 * @param plot
	 * @param isShowData
	 *            是否显示数据
	 * @param isShapesVisible
	 *            是否显示数据节点形状
	 */
	public static void setTimeSeriesRender(Plot plot, boolean isShowData,
			boolean isShapesVisible) {

		XYPlot xyplot = (XYPlot) plot;
		xyplot.setNoDataMessage(NO_DATA_MSG);
		xyplot.setInsets(new RectangleInsets(10, 10, 5, 10));

		XYLineAndShapeRenderer xyRenderer = (XYLineAndShapeRenderer) xyplot
				.getRenderer();

		xyRenderer
				.setBaseItemLabelGenerator(new StandardXYItemLabelGenerator());
		xyRenderer.setBaseShapesVisible(false);
		if (isShowData) {
			xyRenderer.setBaseItemLabelsVisible(true);
			xyRenderer
					.setBaseItemLabelGenerator(new StandardXYItemLabelGenerator());
			xyRenderer.setBasePositiveItemLabelPosition(new ItemLabelPosition(
					ItemLabelAnchor.OUTSIDE1, TextAnchor.BOTTOM_CENTER));// weizhi
		}
		xyRenderer.setBaseShapesVisible(isShapesVisible);// 数据点绘制形状

		DateAxis domainAxis = (DateAxis) xyplot.getDomainAxis();
		domainAxis.setAutoTickUnitSelection(false);
		DateTickUnit dateTickUnit = new DateTickUnit(1, 1,
				new SimpleDateFormat("yyyy-MM")); // 第二个参数是时间轴间距
		domainAxis.setTickUnit(dateTickUnit);

		StandardXYToolTipGenerator xyTooltipGenerator = new StandardXYToolTipGenerator(
				"{1}:{2}", new SimpleDateFormat("yyyy-MM-dd"),
				new DecimalFormat("0"));
		xyRenderer.setBaseToolTipGenerator(xyTooltipGenerator);

		setXY_XAixs(xyplot);
		setXY_YAixs(xyplot);

	}

	/**
	 * 设置时间序列图样式 -默认不显示数据节点形状
	 *
	 * @param plot
	 * @param isShowData
	 *            是否显示数据
	 */

	public static void setTimeSeriesRender(Plot plot, boolean isShowData) {
		setTimeSeriesRender(plot, isShowData, false);
	}

	/**
	 * 设置时间序列图渲染:但是存在一个问题:如果timeseries里面的日期是按照天组织, 那么柱子的宽度会非常小,和直线一样粗细
	 *
	 * @param plot
	 * @param isShowDataLabels
	 */

	public static void setTimeSeriesBarRender(Plot plot,
			boolean isShowDataLabels) {

		XYPlot xyplot = (XYPlot) plot;
		xyplot.setNoDataMessage(NO_DATA_MSG);

		XYBarRenderer xyRenderer = new XYBarRenderer(0.1D);
		xyRenderer
				.setBaseItemLabelGenerator(new StandardXYItemLabelGenerator());

		if (isShowDataLabels) {
			xyRenderer.setBaseItemLabelsVisible(true);
			xyRenderer
					.setBaseItemLabelGenerator(new StandardXYItemLabelGenerator());
		}

		StandardXYToolTipGenerator xyTooltipGenerator = new StandardXYToolTipGenerator(
				"{1}:{2}", new SimpleDateFormat("yyyy-MM-dd"),
				new DecimalFormat("0"));
		xyRenderer.setBaseToolTipGenerator(xyTooltipGenerator);
		setXY_XAixs(xyplot);
		setXY_YAixs(xyplot);

	}

	/**
	 * 设置柱状图渲染
	 *
	 * @param plot
	 * @param isShowDataLabels
	 */
	public static void setBarRenderer(CategoryPlot plot,
			boolean isShowDataLabels) {

		plot.setNoDataMessage(NO_DATA_MSG);
		plot.setInsets(new RectangleInsets(10, 10, 5, 10));
		BarRenderer renderer = (BarRenderer) plot.getRenderer();
		renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
		renderer.setMaximumBarWidth(0.075);// 设置柱子最大宽度

		if (isShowDataLabels) {
			renderer.setBaseItemLabelsVisible(true);
		}

		setXAixs(plot);
		setYAixs(plot);
	}

	/**
	 * 设置堆积柱状图渲染
	 *
	 * @param plot
	 */

	public static void setStackBarRender(CategoryPlot plot) {
		plot.setNoDataMessage(NO_DATA_MSG);
		plot.setInsets(new RectangleInsets(10, 10, 5, 10));
		StackedBarRenderer renderer = (StackedBarRenderer) plot.getRenderer();
		renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
		plot.setRenderer(renderer);
		setXAixs(plot);
		setYAixs(plot);
	}

	/**
	 * 设置类别图表(CategoryPlot) X坐标轴线条颜色和样式
	 *
	 * @param
	 */
	public static void setXAixs(CategoryPlot plot) {
		Color lineColor = new Color(31, 121, 170);
		plot.getDomainAxis().setAxisLinePaint(lineColor);// X坐标轴颜色
		plot.getDomainAxis().setTickMarkPaint(lineColor);// X坐标轴标记|竖线颜色

	}

	/**
	 * 设置类别图表(CategoryPlot) Y坐标轴线条颜色和样式 同时防止数据无法显示
	 *
	 * @param
	 */
	public static void setYAixs(CategoryPlot plot) {
		Color lineColor = new Color(192, 208, 224);
		ValueAxis axis = plot.getRangeAxis();
		axis.setAxisLinePaint(lineColor);// Y坐标轴颜色
		axis.setTickMarkPaint(lineColor);// Y坐标轴标记|竖线颜色
		// 隐藏Y刻度
		axis.setAxisLineVisible(false);
		axis.setTickMarksVisible(false);
		// Y轴网格线条
		plot.setRangeGridlinePaint(new Color(192, 192, 192));
		plot.setRangeGridlineStroke(new BasicStroke(1));

		plot.getRangeAxis().setUpperMargin(0.1);// 设置顶部Y坐标轴间距,防止数据无法显示
		plot.getRangeAxis().setLowerMargin(0.1);// 设置底部Y坐标轴间距

	}

	/**
	 * 设置XY图表(XYPlot) X坐标轴线条颜色和样式
	 *
	 * @param
	 */
	public static void setXY_XAixs(XYPlot plot) {
		Color lineColor = new Color(31, 121, 170);
		plot.getDomainAxis().setAxisLinePaint(lineColor);// X坐标轴颜色
		plot.getDomainAxis().setTickMarkPaint(lineColor);// X坐标轴标记|竖线颜色

	}

	/**
	 * 设置XY图表(XYPlot) Y坐标轴线条颜色和样式 同时防止数据无法显示
	 *
	 * @param
	 */
	public static void setXY_YAixs(XYPlot plot) {
		Color lineColor = new Color(192, 208, 224);
		ValueAxis axis = plot.getRangeAxis();
		axis.setAxisLinePaint(lineColor);// X坐标轴颜色
		axis.setTickMarkPaint(lineColor);// X坐标轴标记|竖线颜色
		// 隐藏Y刻度
		axis.setAxisLineVisible(false);
		axis.setTickMarksVisible(false);
		// Y轴网格线条
		plot.setRangeGridlinePaint(new Color(192, 192, 192));
		plot.setRangeGridlineStroke(new BasicStroke(1));
		plot.setDomainGridlinesVisible(false);

		plot.getRangeAxis().setUpperMargin(0.12);// 设置顶部Y坐标轴间距,防止数据无法显示
		plot.getRangeAxis().setLowerMargin(0.12);// 设置底部Y坐标轴间距

	}

	/**
	 * 设置饼状图渲染
	 */
	public static void setPieRender(Plot plot) {

		plot.setNoDataMessage(NO_DATA_MSG);
		plot.setInsets(new RectangleInsets(10, 10, 5, 10));
		PiePlot piePlot = (PiePlot) plot;
		piePlot.setInsets(new RectangleInsets(0, 0, 0, 0));
		piePlot.setCircular(true);// 圆形

		// piePlot.setSimpleLabels(true);// 简单标签
		piePlot.setLabelGap(0.01);
		piePlot.setInteriorGap(0.05D);
		piePlot.setLegendItemShape(new Rectangle(10, 10));// 图例形状
		piePlot.setIgnoreNullValues(true);
		piePlot.setLabelBackgroundPaint(null);// 去掉背景色
		piePlot.setLabelShadowPaint(null);// 去掉阴影
		piePlot.setLabelOutlinePaint(null);// 去掉边框
		piePlot.setShadowPaint(null);
		// 0:category 1:value:2 :percentage
		piePlot.setLabelGenerator(new StandardPieSectionLabelGenerator(
				"{0}:{2}"));// 显示标签数据
	}

	/**
	 * 是不是一个%形式的百分比
	 *
	 * @param str
	 * @return
	 */
	public static boolean isPercent(String str) {
		return str != null ? str.endsWith("%")
				&& isNumber(str.substring(0, str.length() - 1)) : false;
	}

	/**
	 * 是不是一个数字
	 *
	 * @param str
	 * @return
	 */
	public static boolean isNumber(String str) {
		return str != null ? str
				.matches("^[-+]?(([0-9]+)((([.]{0})([0-9]*))|(([.]{1})([0-9]+))))$")
				: false;
	}

}

package com.example.demo.utils;


import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Paint;
import java.awt.Rectangle;
import java.io.File;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.Vector;

import cn.afterturn.easypoi.entity.ImageEntity;
import com.example.demo.entity.Serie;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.StandardChartTheme;
import org.jfree.chart.axis.AxisLocation;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.CategoryLabelPositions;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.block.BlockBorder;
import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;
import org.jfree.chart.labels.StandardPieSectionLabelGenerator;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.DefaultDrawingSupplier;
import org.jfree.chart.plot.PieLabelLinkStyle;
import org.jfree.chart.plot.PiePlot;
import org.jfree.chart.plot.Plot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.XYPlot;
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.renderer.category.StandardBarPainter;
import org.jfree.chart.renderer.xy.StandardXYBarPainter;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.general.DatasetUtilities;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.ui.RectangleInsets;

import static org.jfree.chart.axis.AxisLocation.*;

/**
* @Description:绘制图表(折线图/饼图)
 */
@SuppressWarnings("rawtypes")
public class ChartUtilsAbandon {

	private static String NO_DATA_MSG = "暂无数据";
	private static Font FONT = new Font("宋体", Font.PLAIN, 20);
	public static Color[] CHART_COLORS = {
			new Color(31, 129, 188), new Color(92, 92, 97), new Color(144, 237, 125), new Color(255, 188, 117),
			new Color(153, 158, 255), new Color(255, 117, 153), new Color(253, 236, 109), new Color(128, 133, 232),
			new Color(158, 90, 102), new Color(255, 204, 102)};// 颜色

	static {
		setChartTheme();
	}

	/**
	 * 中文主题样式 解决乱码
	 */
	public static void setChartTheme() {
		// 设置中文主题样式 解决乱码
		StandardChartTheme chartTheme = new StandardChartTheme("CN");
		// 设置标题字体
		chartTheme.setExtraLargeFont(FONT);
		// 设置图例的字体
		chartTheme.setRegularFont(FONT);
		// 设置轴向的字体
		chartTheme.setLargeFont(FONT);
//		chartTheme.setSmallFont(FONT);
		chartTheme.setTitlePaint(new Color(51, 51, 51));
		chartTheme.setSubtitlePaint(new Color(85, 85, 85));

		chartTheme.setLegendBackgroundPaint(Color.WHITE);// 设置标注
		chartTheme.setLegendItemPaint(Color.BLACK);//
		chartTheme.setChartBackgroundPaint(Color.WHITE);
		// 绘制颜色绘制颜色.轮廓供应商
		// paintSequence,outlinePaintSequence,strokeSequence,outlineStrokeSequence,shapeSequence

		Paint[] OUTLINE_PAINT_SEQUENCE = new Paint[]{Color.WHITE};
		// 绘制器颜色源
		DefaultDrawingSupplier drawingSupplier = new DefaultDrawingSupplier(CHART_COLORS, CHART_COLORS, OUTLINE_PAINT_SEQUENCE,
				DefaultDrawingSupplier.DEFAULT_STROKE_SEQUENCE, DefaultDrawingSupplier.DEFAULT_OUTLINE_STROKE_SEQUENCE,
				DefaultDrawingSupplier.DEFAULT_SHAPE_SEQUENCE);
		chartTheme.setDrawingSupplier(drawingSupplier);

		chartTheme.setPlotBackgroundPaint(Color.WHITE);// 绘制区域
		chartTheme.setPlotOutlinePaint(Color.WHITE);// 绘制区域外边框
		chartTheme.setLabelLinkPaint(new Color(8, 55, 114));// 链接标签颜色
		chartTheme.setLabelLinkStyle(PieLabelLinkStyle.CUBIC_CURVE);

		chartTheme.setAxisOffset(new org.jfree.ui.RectangleInsets(5, 12, 5, 12));
		chartTheme.setDomainGridlinePaint(new Color(192, 208, 224));// X坐标轴垂直网格颜色
		chartTheme.setRangeGridlinePaint(new Color(192, 192, 192));// Y坐标轴水平网格颜色

//		chartTheme.setBaselinePaint(Color.WHITE);
		chartTheme.setCrosshairPaint(Color.BLUE);// 不确定含义
		chartTheme.setAxisLabelPaint(new Color(51, 51, 51));// 坐标轴标题文字颜色
		chartTheme.setTickLabelPaint(new Color(67, 67, 72));// 刻度数字
		chartTheme.setBarPainter(new StandardBarPainter());// 设置柱状图渲染
		chartTheme.setXYBarPainter(new StandardXYBarPainter());// XYBar 渲染

		chartTheme.setItemLabelPaint(Color.black);
		chartTheme.setThermometerPaint(Color.white);// 温度计

		ChartFactory.setChartTheme(chartTheme);
	}

	public ChartUtilsAbandon() {
	}


	/**
	 * 必须设置文本抗锯齿
	 */
	public static void setAntiAlias(JFreeChart chart) {
		chart.setTextAntiAlias(false);

	}

	/**
	 * 设置图例无边框,默认黑色边框
	 */
	public static void setLegendEmptyBorder(JFreeChart chart) {
		chart.getLegend().setFrame(new BlockBorder(Color.WHITE));

	}

	/**
	 * 提供静态方法:获取报表图形1:饼状图
	 *
	 * @param title 标题
	 * @param datas 数据
	 */
	public static ImageEntity createPiePort(String title, Map<String, Double> datas, String url) {
		try {
			// 如果不使用Font,中文将显示不出来
			DefaultPieDataset pds = new DefaultPieDataset();

			// 获取迭代器:
			Set<Entry<String, Double>> set = datas.entrySet();
			Iterator iterator = (Iterator) set.iterator();
			Entry entry = null;
			while (iterator.hasNext()) {
				entry = (Entry) iterator.next();
				pds.setValue(entry.getKey().toString(), Double.parseDouble(entry.getValue().toString()));
			}
			/**
			 * 生成一个饼图的图表
			 * 分别是:显示图表的标题、需要提供对应图表的DateSet对象、是否显示图例、是否生成贴士以及是否生成URL链接
			 */
			JFreeChart chart = ChartFactory.createPieChart(title, pds, true, false, true);
			setPieRender((PiePlot) chart.getPlot());

			//将内存中的图片写到本地硬盘
			org.jfree.chart.ChartUtils.saveChartAsPNG(new File(url), chart, 560, 360);

			ImageEntity imageEntity=new ImageEntity(ImgConversion.imgToByte(url),560,360);
			return imageEntity;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 提供静态方法:获取报表图形2:柱状图
	 *
	 * @param title 标题
	 * @param datas 数据
	 */
	public static ImageEntity createHistogram(String title, Map<String, Double> datas, String url) {
		try {
			// 如果不使用Font,中文将显示不出来
			DefaultCategoryDataset pds = new DefaultCategoryDataset();

			// 获取迭代器:
			Set<Entry<String, Double>> set = datas.entrySet();
			Iterator iterator = (Iterator) set.iterator();
			Entry entry = null;
			while (iterator.hasNext()) {
				entry = (Entry) iterator.next();
				pds.setValue(454,"西安","苹果");
				pds.setValue(478,"西安","香蕉");
			}
			/**
			 * 生成一个柱状的图表
			 * ChartFactory.createBarChart("柱状图表",null, null,pds, PlotOrientation.VERTICAL,false,false,false);
			 * 								标题		,x轴下显示的字,y轴显示的字,数据,PlotOrientation.VERTICAL横向显示(HORIZONTAL纵向显示),后面三个boolean不知道
			 */
			JFreeChart chart = ChartFactory.createBarChart("柱状图表",null, null,pds, PlotOrientation.VERTICAL,false,false,false);
			CategoryPlot plot =(CategoryPlot) chart.getPlot();
			setBarRenderer(plot,true);
			//将内存中的图片写到本地硬盘
			org.jfree.chart.ChartUtils.saveChartAsPNG(new File(url), chart, 560, 360);

			ImageEntity imageEntity=new ImageEntity(ImgConversion.imgToByte(url),560,360);
			return imageEntity;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}


	/**
	 * 提供静态方法:获取报表图形3:折线图
	 *
	 * @param title  标题
	 * @param datas  数据
	 */
	public static ImageEntity createLinePort(String title, Map<String, Double> datas, String xName, String yName, String url) {
		try {
			//种类数据集
			DefaultCategoryDataset dataset = new DefaultCategoryDataset();
			//获取迭代器:
			Set<Entry<String, Double>> set = datas.entrySet();
			Iterator iterator = (Iterator) set.iterator();
			Entry entry = null;
			while (iterator.hasNext()) {
				entry = (Entry) iterator.next();
				dataset.setValue(Double.parseDouble(entry.getValue().toString()),//y
						title,                         //名称
						entry.getKey().toString());      //x
			}
			//创建折线图,折线图分水平显示和垂直显示两种
			JFreeChart chart = ChartFactory.createLineChart(title, xName, yName, dataset,//2D折线图
					PlotOrientation.VERTICAL,
					false, // 是否显示图例(对于简单的柱状图必须是false)
					true, // 是否生成工具
					false);// 是否生成URL链接
			//得到绘图区
			setLineRender((CategoryPlot) chart.getPlot(), true, true);
			org.jfree.chart.ChartUtils.saveChartAsPNG(new File(url), chart, 1000, 600);
			ImageEntity imageEntity=new ImageEntity(ImgConversion.imgToByte(url),560,360);
			return imageEntity;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 设置折线图样式
	 *
	 * @param plot
	 * @param isShowDataLabels 是否显示数据标签
	 */
	public static void setLineRender(CategoryPlot plot, boolean isShowDataLabels, boolean isShapesVisible) {
		plot.setNoDataMessage(NO_DATA_MSG);
		plot.setInsets(new
RectangleInsets(10, 10, 0, 10), false);
		LineAndShapeRenderer renderer = (LineAndShapeRenderer) plot.getRenderer();
//		renderer.setDefaultStroke(new BasicStroke(1.5F));

		if (isShowDataLabels) {
//			renderer.setDefaultItemLabelsVisible(true);
//			renderer.setDefaultItemLabelGenerator(new StandardCategoryItemLabelGenerator(StandardCategoryItemLabelGenerator.DEFAULT_LABEL_FORMAT_STRING,
//					NumberFormat.getInstance()));
//			renderer.setDefaultPositiveItemLabelPosition(new ItemLabelPosition(ItemLabelAnchor.OUTSIDE1, TextAnchor.BOTTOM_CENTER));// weizhi
		}
//		renderer.setDefaultShapesVisible(isShapesVisible);// 数据点绘制形状
		renderer.setBaseShapesFilled(true);
//		setDisplaySeriesLines(boolean flag)

		setXAixs(plot);
		setYAixs(plot);

	}

	/**
	 * 设置饼状图渲染
	 */
	public static void setPieRender(Plot plot) {

		plot.setNoDataMessage(NO_DATA_MSG);
		plot.setInsets(new org.jfree.ui.RectangleInsets(10, 10, 5, 10));
		PiePlot piePlot = (PiePlot) plot;
		piePlot.setInsets(new org.jfree.ui.RectangleInsets(0, 0, 0, 0));
		piePlot.setCircular(true);// 圆形

		// piePlot.setSimpleLabels(true);// 简单标签
		piePlot.setLabelGap(0.01);
		piePlot.setInteriorGap(0.05D);
		piePlot.setLegendItemShape(new Rectangle(10, 10));// 图例形状
		piePlot.setIgnoreNullValues(true);
		piePlot.setLabelBackgroundPaint(null);// 去掉背景色
		piePlot.setLabelShadowPaint(null);// 去掉阴影
		piePlot.setLabelOutlinePaint(null);// 去掉边框
		piePlot.setShadowPaint(null);
		// 0:category 1:value:2 :percentage
		piePlot.setLabelGenerator(new StandardPieSectionLabelGenerator("{0}:{2}"));// 显示标签数据
	}

	/**
	 * 设置类别图表(CategoryPlot) X坐标轴线条颜色和样式
	 *
	 * @param
	 */
	public static void setXAixs(CategoryPlot plot) {
		Color lineColor = new Color(31, 121, 170);
		plot.getDomainAxis().setCategoryLabelPositions(CategoryLabelPositions.UP_45);
		plot.getDomainAxis().setAxisLinePaint(lineColor);// X坐标轴颜色
		plot.getDomainAxis().setTickMarkPaint(lineColor);// X坐标轴标记|竖线颜色
//		plot.setDomainAxis();
//		plot.setOrientation(PlotOrientation.HORIZONTAL);//图表旋转
		CategoryAxis domainAxis = plot.getDomainAxis();
		domainAxis.setCategoryLabelPositions(CategoryLabelPositions.STANDARD);//x轴的种类标签旋转


	}

	/**
	 * 设置类别图表(CategoryPlot) Y坐标轴线条颜色和样式 同时防止数据无法显示
	 *
	 * @param
	 */
	public static void setYAixs(CategoryPlot plot) {
//		Color lineColor = new Color(192, 208, 224);
		Color lineColor = new Color(31, 121, 170);
		ValueAxis axis = plot.getRangeAxis();
		axis.setAxisLinePaint(lineColor);// Y坐标轴颜色
		axis.setTickMarkPaint(lineColor);// Y坐标轴标记|竖线颜色
		// false隐藏Y刻度
		axis.setAxisLineVisible(true);
		axis.setTickMarksVisible(true);
		// Y轴网格线条
		plot.setRangeGridlinePaint(new Color(114, 113, 113));
		plot.setRangeGridlineStroke(new BasicStroke(1));

		plot.getRangeAxis().setUpperMargin(0.1);// 设置顶部Y坐标轴间距,防止数据无法显示
		plot.getRangeAxis().setLowerMargin(0.1);// 设置底部Y坐标轴间距

	}

	/**
	 * 设置XY图表(XYPlot) X坐标轴线条颜色和样式
	 *
	 * @param
	 */
	public static void setXY_XAixs(XYPlot plot) {
		Color lineColor = new Color(31, 121, 170);
		plot.getDomainAxis().setAxisLinePaint(lineColor);// X坐标轴颜色
		plot.getDomainAxis().setTickMarkPaint(lineColor);// X坐标轴标记|竖线颜色

	}

	/**
	 * 设置XY图表(XYPlot) Y坐标轴线条颜色和样式 同时防止数据无法显示
	 *
	 * @param
	 */
	public static void setXY_YAixs(XYPlot plot) {
		Color lineColor = new Color(192, 208, 224);
		ValueAxis axis = plot.getRangeAxis();
		axis.setAxisLinePaint(lineColor);// X坐标轴颜色
		axis.setTickMarkPaint(lineColor);// X坐标轴标记|竖线颜色
		// 隐藏Y刻度
		axis.setAxisLineVisible(false);
		axis.setTickMarksVisible(false);
		// Y轴网格线条
		plot.setRangeGridlinePaint(new Color(192, 192, 192));
		plot.setRangeGridlineStroke(new BasicStroke(1));
		plot.setDomainGridlinesVisible(false);

		plot.getRangeAxis().setUpperMargin(0.12);// 设置顶部Y坐标轴间距,防止数据无法显示
		plot.getRangeAxis().setLowerMargin(0.12);// 设置底部Y坐标轴间距

	}


	  /**
     * 设置柱状图渲染
     *
     * @param plot
     * @param isShowDataLabels
     */
    public static void setBarRenderer(CategoryPlot plot, boolean isShowDataLabels) {

        plot.setNoDataMessage(NO_DATA_MSG);
        plot.setInsets(new RectangleInsets(10, 10, 5, 10));

        BarRenderer renderer = (BarRenderer) plot.getRenderer();
        renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
        renderer.setMaximumBarWidth(0.075);// 设置柱子最大宽度

        if (isShowDataLabels) {
            renderer.setBaseItemLabelsVisible(true);
        }

        setXAixs(plot);
        setYAixs(plot);
    }

    /**
	 * 设置堆积柱状图渲染
	 *
	 * @param plot
	 */

	public static void setStackBarRender(CategoryPlot plot) {
		plot.setNoDataMessage(NO_DATA_MSG);
		plot.setInsets(new RectangleInsets(10, 10, 5, 10));
		StackedBarRenderer renderer = (StackedBarRenderer) plot.getRenderer();
		renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
		plot.setRenderer(renderer);
		setXAixs(plot);
		setYAixs(plot);
	}
}
package com.example.demo.utils;

import cn.hutool.core.date.format.FastDateFormat;
import com.alibaba.excel.util.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.streaming.SXSSFCell;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;

import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * @Description: excel 处理工具类
 */
public class Excel{

  private static final Pattern NUMBER_PATTERN = Pattern.compile("[-]?[\\d.]+");
  private static final FastDateFormat FDF = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss");
  private static final DecimalFormat DF = new DecimalFormat("0.00");


  public static SXSSFWorkbook createWorkBook(String sheetName, List<String> titles,
                                             List<List> contents) throws Exception {

    SXSSFWorkbook wb = new SXSSFWorkbook();
    SXSSFSheet sheet = null;

    // 对每个表生成一个新的sheet,并以表名命名
    if (sheetName == null) {
      sheetName = "sheet1";
    }
    sheet = wb.createSheet(sheetName);
    sheet.setDefaultColumnWidth(10 * 256);
    // 设置表头的说明
    SXSSFRow topRow = sheet.createRow(0);
    for (int i = 0; i < titles.size(); i++) {
      setCellGBKValue(topRow.createCell(i), titles.get(i));
      sheet.setColumnWidth(i, titles.get(i).getBytes().length * 258);
    }

    XSSFCellStyle wrapStyle = (XSSFCellStyle) wb.createCellStyle();
    // 设置单元格内容是否自动换行
    wrapStyle.setWrapText(true);

    Map columnWidth = new HashMap<Integer, Integer>();
    for (int i = 0; i < contents.size(); i++) {
      List one = contents.get(i);
      SXSSFRow row = sheet.createRow(i + 1);
      // 行高
      int height = 1;
      for (int j = 0; j < titles.size(); j++) {
        Object cellValue = one.get(j);
        /**
         * 数字按照数字样式处理 2018/1/18 王斌
         */
        if (cellValue == null) {
          setCellGBKValue(row.createCell(j), "");
        } else {
          String cellStringValue = cellValue.toString();
          SXSSFCell cell = row.createCell(j);
          /*if (NUMBER_PATTERN.matcher(cellStringValue).matches()
              && cellStringValue.length() < 11) {// 非11位的数字、设置数字格式
            setCellGBKValue(cell, Double.valueOf(cellStringValue));
          } else {
            setCellGBKValue(cell, cellStringValue);
          }*/
          setCellGBKValue(cell, cellStringValue);
          if (cellStringValue.length() > 4) {// 内容长度大于4做自适应处理
            int width = (cellStringValue.getBytes().length + 4) * 256;
            sheet.setColumnWidth(j, width < 3000 ? 3000 : width < 255 * 256 ? width : 6000);
            int old = columnWidth.get(j) != null ? (int) columnWidth.get(j) : 0;
            if (width > old) {
              columnWidth.put(j, width);
              sheet.setColumnWidth(j, width < 3000 ? 3000 : width < 255 * 256 ? width : 60000);
            }
          }
          if (cellStringValue.contains("\n")) {
            cell.setCellStyle(wrapStyle);
            int newH = StringUtils.countMatches(cellStringValue, "\n") + 1;
            if (height < newH) {
              height = newH;
            }
          }
        }
        if (height != 1) {
          row.setHeightInPoints(height * 20);
        }
      }
    }
    return wb;
  }

  /**
   * excel导出
   *
   * @param fileNamePath 导出的文件名称
   * @param sheetName 导出的sheet名称
   * @param titles 第一行表头
   * @param contents 数据集合
   */
  public static <T> File export(String fileNamePath, String sheetName, List<String> titles,
                                List<List> contents)
      throws Exception {

    SXSSFWorkbook wb = createWorkBook(sheetName, titles, contents);
    File file = null;
    OutputStream os = null;
    file = new File(fileNamePath);
    try {
      os = new FileOutputStream(file);
      wb.write(os);
    } catch (Exception e) {
      throw new Exception("write excel file error!", e);
    } finally {
      if (null != os) {
        os.flush();
        os.close();
      }
    }
    return file;
  }

  public static void export(Workbook wb, String fileName, List<String> titles,
                            HttpServletResponse response) throws Exception {
    try {
      if(!CollectionUtils.isEmpty(titles)){
        wb = appendTitles(wb, titles);
      }
      ByteArrayOutputStream baos = new ByteArrayOutputStream();
      wb.write(baos);
      baos.flush();
      byte[] aa = baos.toByteArray();
      response.addHeader("Content-Disposition",
          "attachment;filename*=utf-8'zh_cn'" + fileName);
      response.setHeader("Content-Type", "application/vnd.ms-excel");
      response.setCharacterEncoding("UTF-8");
      response.getOutputStream().write(aa);
      response.setContentLength(aa.length);
    } catch (Exception e) {
      e.printStackTrace();
      throw new Exception("write excel to stream error!", e);
    } finally {
      if (response.getOutputStream() != null) {
        response.getOutputStream().flush();
      }
    }
  }

  private static Workbook appendTitles(Workbook wb, List<String> titles) throws Exception {

    Sheet sheet = wb.getSheetAt(0);
    // 设置表头的说明
    Row topRow = sheet.getRow(1);
    for (int i = 0; i < titles.size(); i++) {
      Cell cell = topRow.createCell(i + 6);
//      cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
      cell.setCellValue(titles.get(i));
      sheet.setColumnWidth( i + 6, titles.get(i).getBytes().length * 258);
    }
    return wb;
  }

  private static void setCellGBKValue(SXSSFCell cell, String value) {
//    cell.setCellType(HSSFCell.CELL_TYPE_STRING);
    cell.setCellValue(value);
  }

  private static void setCellGBKValue(SXSSFCell cell, double value) {
//    cell.setCellType(HSSFCell.CELL_TYPE_NUMERIC);
    cell.setCellValue(value);
  }

}
package com.example.demo.utils;

import lombok.extern.slf4j.Slf4j;

import java.io.*;

/**
 * //jfreechart-1.5.0.jar  (能解决新版本的乱码问题)
 //jcommon-1.0.24.jar
 */
@Slf4j
public class ImgConversion {

    private static String tempImgPath="E:\\b.png";
    private static ChartUtilsAbandon ChartUtilities;

    /**
     * 将图片转化为字节数组
     * @return 字节数组
     */
    public static byte[] imgToByte(String tempImgPath){
        File file = new File(tempImgPath);
        byte[] buffer = null;
        try {
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
            byte[] b = new byte[1000];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        } catch (IOException e) {
            log.error(e.getMessage());
        }
        //删除临时文件
        file.delete();
        return buffer;
    }
}
package com.example.demo.utils;

import com.itextpdf.html2pdf.ConverterProperties;
import com.itextpdf.html2pdf.HtmlConverter;
import com.itextpdf.html2pdf.attach.impl.OutlineHandler;
import com.itextpdf.kernel.events.PdfDocumentEvent;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.WriterProperties;
import com.itextpdf.layout.font.FontProvider;
import org.springframework.stereotype.Component;
@Component
public class ItextPdfUtils {

        /**
     * 生成pdf
     * @param html html内容
     * @param outputFile 输出的地址
     */
    public void generatePdf(String html,String outputFile){
        try {
            //outputFile也可以是输出流
            PdfWriter writer = new PdfWriter(outputFile, new WriterProperties().setFullCompressionMode(Boolean.TRUE));
            PdfDocument doc = new PdfDocument(writer);//获取到PDF的原生Document
            doc.getDefaultPageSize().applyMargins(20, 20, 20, 20, true);

            // 设置中文字体
            FontProvider fontProvider = new FontProvider();
            PdfFont pdfFont = PdfFontFactory.createFont("STSongStd-Light", "UniGB-UCS2-H", false);

            fontProvider.addFont(pdfFont.getFontProgram(), "UniGB-UCS2-H");
            // 水印
//            doc.addEventHandler(PdfDocumentEvent.END_PAGE,null);
            // 页眉
            //生成页眉
            doc.addEventHandler(PdfDocumentEvent.END_PAGE, new PageHeader());

            // 页码
            doc.addEventHandler(PdfDocumentEvent.END_PAGE, new PageMarker(pdfFont));

            ConverterProperties properties = new ConverterProperties();
            properties.setFontProvider(fontProvider);
            //PDF目录
            properties.setOutlineHandler(OutlineHandler.createStandardHandler());
            String replace = html.replace("[", "");
            HtmlConverter.convertToPdf(replace, doc, properties);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

}
package com.example.demo.utils;

import cn.hutool.core.io.IoUtil;
import com.itextpdf.io.image.ImageDataFactory;
import com.itextpdf.kernel.colors.DeviceRgb;
import com.itextpdf.kernel.events.Event;
import com.itextpdf.kernel.events.IEventHandler;
import com.itextpdf.kernel.events.PdfDocumentEvent;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.borders.Border;
import com.itextpdf.layout.borders.SolidBorder;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.property.HorizontalAlignment;
import com.itextpdf.layout.property.TextAlignment;
import com.itextpdf.layout.property.VerticalAlignment;
import lombok.SneakyThrows;

import java.awt.*;
import java.io.InputStream;


public class PageHeader implements IEventHandler {

    /**
     * 生成页眉
     */
    @SneakyThrows
    @Override
    public void handleEvent(Event event) {
        final PdfDocumentEvent docEvent = (PdfDocumentEvent) event;
        final PdfDocument pdfDoc = docEvent.getDocument();
        final Document doc = new Document(pdfDoc);
        final PdfPage page = docEvent.getPage();
        final Rectangle pageSize = page.getPageSize();
        final float pdfWidth = pageSize.getWidth();
        final float pdfHeight = pageSize.getHeight();
        final float tableWidth = pdfWidth - doc.getRightMargin() - doc.getLeftMargin();

        // 页眉
        final Table headerTable = new Table(2);
        headerTable.setFixedLayout();
        headerTable.setWidth(tableWidth);
        //设置字体,要不页眉乱码
        headerTable.setFont(PdfFontFactory.createFont("STSongStd-Light", "UniGB-UCS2-H", false));
        final Paragraph rightText = new Paragraph();//段落
        headerTable.setBorderBottom(new SolidBorder(new DeviceRgb(91,155,213),1f,2f));
        rightText.add("--- 锐服信 ---");//内容

        rightText.setFontColor(new DeviceRgb(Color.black));//设置字体颜色
        rightText.setPaddingLeft(-5);//设置字位置的paddingLeft

        // 设置图片
        InputStream is = this.getClass().getResourceAsStream("/img/adada.png");
        byte[] bytes = IoUtil.readBytes(is);
        com.itextpdf.layout.element.Image img = new com.itextpdf.layout.element.Image(ImageDataFactory.create(bytes));
        img.setHeight(20);
        img.setWidth(70);
        Paragraph imgParagraph = new Paragraph().add(img);
        imgParagraph.setMarginLeft(-20);//设置图片的marginLeft
        Cell imgCell = new Cell();
        imgCell.setBorder(Border.NO_BORDER);
        imgCell.setHorizontalAlignment(HorizontalAlignment.LEFT);
        imgCell.setVerticalAlignment(VerticalAlignment.BOTTOM);
        imgCell.setTextAlignment(TextAlignment.LEFT);
        imgCell.add(imgParagraph);
        imgCell.setPaddingLeft(15);
        headerTable.addCell(imgCell);

        final Cell rightCell = new Cell();
        rightCell.add(rightText);
        rightCell.setFontSize(12f);//字体大小
        rightCell.setMarginBottom(20);
        rightCell.setBorder(Border.NO_BORDER);
        rightCell.setTextAlignment(TextAlignment.RIGHT);
        headerTable.addCell(rightCell);// 将设置好的段落添加进数据中

//        table数据构建完成,传入pdf
        headerTable.setFixedPosition(doc.getLeftMargin(), pdfHeight-50, tableWidth-43);
        doc.add(headerTable);
    }
}
package com.example.demo.utils;

import com.itextpdf.kernel.colors.DeviceRgb;
import com.itextpdf.kernel.events.Event;
import com.itextpdf.kernel.events.IEventHandler;
import com.itextpdf.kernel.events.PdfDocumentEvent;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.layout.Canvas;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.property.TextAlignment;

import lombok.AllArgsConstructor;
import lombok.SneakyThrows;

import java.awt.*;

/**
 * 生成PDF页码
 */
@AllArgsConstructor
public class PageMarker implements IEventHandler {

    private PdfFont pdfFont;

    @SneakyThrows
    @Override
    public void handleEvent(Event event) {
        PdfDocumentEvent docEvent = (PdfDocumentEvent) event;
        PdfDocument pdf = docEvent.getDocument();
        PdfPage page = docEvent.getPage();
        Rectangle pageSize = page.getPageSize();
        PdfCanvas pdfCanvas = new PdfCanvas(
                page.getLastContentStream(), page.getResources(), pdf);
        Canvas canvas = new Canvas(pdfCanvas, pdf, pageSize);
        float x = (pageSize.getLeft() + pageSize.getRight()) / 2;
        float y = pageSize.getBottom() + 15;

        Paragraph p = new Paragraph("第" + pdf.getPageNumber(page) + "页")
                .setFont(pdfFont)//字体
                .setFontColor(new DeviceRgb(Color.black));//字体颜色

        canvas.showTextAligned(p, x, y, TextAlignment.CENTER);
        canvas.close();
    }

}
package com.example.demo.utils;

import cn.afterturn.easypoi.word.WordExportUtil;

import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.jfree.util.Configuration;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTPageSz;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTSectPr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STPageOrientation;
import org.springframework.util.Assert;

import java.io.*;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 */
public class WordUtil {
    /**
     * 导出word
     * <p>第一步生成替换后的word文件,只支持docx</p>
     * <p>第二步下载生成的文件</p>
     * <p>第三步删除生成的临时文件</p>
     * 模版变量中变量格式:{{foo}}
     *
     * @param templatePath word模板地址
     * @param temDir       生成临时文件存放地址
     * @param fileName     文件名
     * @param params       替换的参数
     */
    public static void exportWord(String templatePath, String temDir, String fileName, Map<String, Object> params) {
        Assert.notNull(templatePath, "模板路径不能为空");
        Assert.notNull(temDir, "临时文件路径不能为空");
        Assert.notNull(fileName, "导出文件名不能为空");
        Assert.isTrue(fileName.endsWith(".docx"), "word导出请使用docx格式");

        if (!temDir.endsWith("/")) {
            temDir = temDir + File.separator;
        }
        File dir = new File(temDir);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        try {
            XWPFDocument doc = WordExportUtil.exportWord07(templatePath, params);
            CTSectPr ctSectPr = doc.getDocument().getBody().addNewSectPr();
            CTPageSz pgSz = ctSectPr.addNewPgSz();
            //设置横板
            pgSz.setW(BigInteger.valueOf(15840));
            pgSz.setH(BigInteger.valueOf(11907));
            pgSz.setOrient(STPageOrientation.LANDSCAPE);//纸张方向为横向


            String tmpPath = temDir + fileName;
            FileOutputStream fos = new FileOutputStream(tmpPath);
            doc.write(fos);
            fos.flush();
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }



//    public static void exportWords(String templatePath, String temDir, String fileName, Map<String, Object> params) {
//        Assert.notNull(templatePath, "模板路径不能为空");
//        Assert.notNull(temDir, "临时文件路径不能为空");
//        Assert.notNull(fileName, "导出文件名不能为空");
//        Assert.isTrue(fileName.endsWith(".docx"), "word导出请使用docx格式");
//        if (!temDir.endsWith("/")) {
//            temDir = temDir + File.separator;
//        }
//        File dir = new File(temDir);
//        if (!dir.exists()) {
//            dir.mkdirs();
//        }
//        try {
//            XWPFDocument doc = WordExportUtil.exportWord07(templatePath, params);
//            String tmpPath = temDir + fileName;
//            FileOutputStream fos = new FileOutputStream(tmpPath);
//            doc.write(fos);
//            fos.flush();
//            fos.close();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }





}
package com.example.demo;

import cn.afterturn.easypoi.entity.ImageEntity;

import com.example.demo.entity.Serie;
import com.example.demo.utils.ChartUtilsAbandon;
import com.example.demo.utils.ImgConversion;
import com.example.demo.utils.WordUtil;


import java.awt.Font;
import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import java.util.List;

import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import org.apache.poi.xwpf.usermodel.*;
import org.jfree.chart.*;

import org.jfree.chart.labels.StandardPieSectionLabelGenerator;

import org.jfree.chart.plot.PiePlot;
import org.jfree.data.general.DefaultPieDataset;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import com.itextpdf.text.*;

import static com.example.demo.utils.ChartUtilsAbandon.*;


import com.example.demo.entity.usera;
import com.example.demo.entity.userSon;
import com.example.demo.utils.ItextPdfUtils;
import com.example.demo.utils.base64;
import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Autowired;
import java.nio.file.Paths;
import java.util.ArrayList;

@SpringBootTest
class DemoApplicationTests {

    @Autowired
    private base64 base;

    @Autowired
    private ItextPdfUtils itextPdfUtils;

    @Test
    void contextLoads() {
    }

    /**
     * 导出为pdf
     * @throws IOException
     * @throws DocumentException
     */
    @Test
    public void A() throws IOException, DocumentException {
      // 第一步,实例化一个document对象
	  Document document = new Document();
	  // 第二步,设置要到出的路径
	  FileOutputStream out = new FileOutputStream("E:/TestLegerPDF.pdf");
      //如果是浏览器通过request请求需要在浏览器中输出则使用下面方式
      //OutputStream out = response.getOutputStream();
	  // 第三步,设置字符
	  BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", false);
	  Font fontZH = new Font("STSong-Light", 12, 0);
	  // 第四步,将pdf文件输出到磁盘
      PdfWriter writer = PdfWriter.getInstance(document,out);
      // 第五步,打开生成的pdf文件
      document.open();
      // 第六步,设置内容
      String title = "标题";
      document.add(new Paragraph(new Chunk(title).setLocalDestination(title)));
      document.add(new Paragraph("\n"));
      // 创建table,注意这里的2是两列的意思,下面通过table.addCell添加的时候必须添加整行内容的所有列
      PdfPTable table = new PdfPTable(2);
      table.setWidthPercentage(100.0F);
      table.setHeaderRows(1);
      table.getDefaultCell().setHorizontalAlignment(1);
      table.addCell(new Paragraph("Ip"));
      table.addCell(new Paragraph("状态"));
      table.addCell(new Paragraph("127.0.0.1"));
      table.addCell(new Paragraph("良好"));
      document.add(table);
      document.add(new Paragraph("\n"));
      // 第七步,关闭document
      document.close();

      System.out.println("导出pdf成功~");

    }

    /**
     * 导出为word
     * @throws IOException
     */
    @Test
    public void B() throws IOException {
        XWPFDocument document = new XWPFDocument();//操作word的入口
        XWPFParagraph paragraph = document.createParagraph();//段落
        paragraph.setAlignment(ParagraphAlignment.CENTER);//居中
        XWPFRun run = paragraph.createRun();
        run.setBold(true);
        run.setText("资产台账");
        XWPFParagraph p1= document.createParagraph();//段落
        p1.setAlignment(ParagraphAlignment.CENTER);//居中

        FileOutputStream out = new FileOutputStream("E:/B.docx");
        document.write(out);
        out.close();


    }

    @Test
    public void C(){

        DefaultPieDataset dataset = new DefaultPieDataset();

        dataset.setValue("技术部",180);
        dataset.setValue("销售部",20);
        dataset.setValue("人事部",10);

        //设置语言
        StandardChartTheme chartTheme = new StandardChartTheme("CN");
//        //设置标题字体
//        chartTheme.setExtraLargeFont(new Font(Font.BOLD,20));
//        //设置图例字体
//        chartTheme.setRegularFont(new Font("华文宋体",Font.BOLD,15));
//        //设置轴向的字体 x,y轴
//        chartTheme.setLargeFont(new Font("华文宋体", Font.BOLD,20));
        //应用主题样式
        ChartFactory.setChartTheme(chartTheme);


        //String title          大标题
        // PieDataset dataset   数据集
        // boolean legend       是否显示图例
        // boolean tooltips     是否显示提示
        // boolean urls         是否跳转
        //平面图

        //3D图
//        org.jfree.chart.JFreeChart chart = ChartFactory.createPieChart3D("各部门人数", dataset, true, false, false);




        HashMap<String, Object> map = new HashMap<>(4);

        //模拟饼状图数据
        HashMap<String, Integer> datas = new HashMap<>(3);
        datas.put("一号",10);
        datas.put("二号",20);
        datas.put("三号",40);
        datas.put("四号",20);
        datas.put("五号",40);
//        ImageEntity imageEntity = JfreeUtil.pieChart("测试",datas, 500, 300);
//        org.jfree.chart.JFreeChart chart = ChartFactory.createPieChart("各部门人数", dataset, true, false, false);
//        map.put("picture", imageEntity);

//        //模拟其它普通数据
//        map.put("username", "张三");
//        map.put("date", "2019-10-10");
//        map.put("desc", "测试");
//        map.put("boo", true);
//
//        //模拟表格数据
//        ArrayList<HashMap<String, String>> list = new ArrayList<>(2);
//        HashMap<String, String> temp = new HashMap<>(3);
//        temp.put("sn","1");
//        temp.put("name","第一个人");
//        temp.put("age","23");
//        list.add(temp);
//        temp = new HashMap<>(3);
//        temp.put("sn","2");
//        temp.put("name","第二个人");
//        temp.put("age","24");
//        list.add(temp);
//        map.put("personlist",list);
        //word模板相对路径、word生成路径、word生成的文件名称、数据源
//       WordUtil.exportWord("templates/demo1.docx", "E:/", "生成文件.docx", map);

    }

    @Test
    public void D() throws IOException {
        //需求: 统计每个部门的人员
        //1.准备数据: 技术部 180; 销售部  20; 人事部 10人
        DefaultPieDataset dataset = new DefaultPieDataset();

        dataset.setValue("技术部",180);
        dataset.setValue("销售部",20);
        dataset.setValue("人事部",10);

        //设置语言
        StandardChartTheme chartTheme = new StandardChartTheme("CN");
//        //设置标题字体
//        chartTheme.setExtraLargeFont(new Font(Font.BOLD,20));
//        //设置图例字体
//        chartTheme.setRegularFont(new Font("华文宋体",Font.BOLD,15));
//        //设置轴向的字体 x,y轴
//        chartTheme.setLargeFont(new Font("华文宋体", Font.BOLD,20));
        //应用主题样式
        ChartFactory.setChartTheme(chartTheme);


        //String title          大标题
        // PieDataset dataset   数据集
        // boolean legend       是否显示图例
        // boolean tooltips     是否显示提示
        // boolean urls         是否跳转
        //平面图
        org.jfree.chart.JFreeChart chart = ChartFactory.createPieChart("各部门人数", dataset, true, false, false);
//        chart.getLegend().setFrame(new BlockBorder(Color.white));
//                 chart.getLegend().setFrame(new BlockBorder(Color.WHITE));//设置饼图右边文字边框为白色,就可以达到隐藏边框的效果
        //3D图
//        org.jfree.chart.JFreeChart chart = ChartFactory.createPieChart3D("各部门人数", dataset, true, false, false);

        ChartUtils.saveChartAsPNG(new File("E:\\chart1.png"),chart,400,300);


    }

    @Test
    public void d(){

            HashMap<String, Object> map = new HashMap<>(4);

            //模拟饼状图数据
            HashMap<String, Integer> datas = new HashMap<>(3);
            datas.put("2名",10);
            datas.put("56名",90);
            //FileOutputStream ss = JfreeUtil.pieChart("班级排名", datas, 200, 200);
//            WordUtil.exportWord("templates/demo1.docx", "E:/", "生成文件.docx", map);


        //模拟其它普通数据
//            map.put("username", "张三");
//            map.put("date", "2019-10-10");
//            map.put("desc", "测试");
//            map.put("boo", true);
//
//            //模拟表格数据
//            ArrayList<HashMap<String, String>> list = new ArrayList<>(2);
//            HashMap<String, String> temp = new HashMap<>(3);
//            temp.put("sn","1");
//            temp.put("name","第一个人");
//            temp.put("age","23");
//            list.add(temp);
//            temp = new HashMap<>(3);
//            temp.put("sn","2");
//            temp.put("name","第二个人");
//            temp.put("age","24");
//            list.add(temp);
//            map.put("personlist",list);
            //word模板相对路径、word生成路径、word生成的文件名称、数据源

    }

    @Test
    public void g(){
        DefaultPieDataset pds = new DefaultPieDataset();
        pds.setValue("00点-04点", 100);
        pds.setValue("04点-08点", 200);
        pds.setValue("08点-12点", 300);
        pds.setValue("12点-16点", 400);
        pds.setValue("16点-20点", 500);
        pds.setValue("20点-24点", 600);
        String filePath = "E:/pie.jpg";
        createPieChart(pds,filePath);

    }
    public static void createPieChart(DefaultPieDataset pds, String filePath){
        try {
            // 分别是:显示图表的标题、需要提供对应图表的DateSet对象、是否显示图例、是否生成贴士以及是否生成URL链接
            JFreeChart chart = ChartFactory.createPieChart("今日放屁次数:时间段分布图", pds, false, false, true);
            // 如果不使用Font,中文将显示不出来
            Font font = new Font("宋体",Font.BOLD,12);
            // 设置图片标题的字体
            chart.getTitle().setFont(font);
            // 得到图块,准备设置标签的字体
            PiePlot plot = (PiePlot) chart.getPlot();
            // 设置标签字体
            plot.setLabelFont(font);
            plot.setStartAngle(new Float(3.14f / 2f));
            // 设置plot的前景色透明度
            plot.setForegroundAlpha(0.7f);
            // 设置plot的背景色透明度
            plot.setBackgroundAlpha(0.0f);
            // 设置标签生成器(默认{0})
            // {0}:key {1}:value {2}:百分比 {3}:sum
            plot.setLabelGenerator(new StandardPieSectionLabelGenerator("{0}({1}占{2})"));

            // 将内存中的图片写到本地硬盘
            ChartUtilities.saveChartAsJPEG(new File(filePath), chart, 600, 300);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @throws IOException
     */
    @Test
    public void statementTest() throws IOException {
        HashMap<String, Double> map = new HashMap<>();
        //构建饼图数据
        HashMap<String, Object> maps = new HashMap<>();
        map.put("Map", (double) 1000);
        map.put("List", (double) 700);
        map.put("String", (double) 600);
        map.put("Long", (double) 400);
        ImageEntity piePort = createPiePort("类型投票结果", map,"E:\\b.png");
        ArrayList<HashMap<String, String>> objects = new ArrayList<>();
        HashMap<String, String> temp = new HashMap<>();
        //构建表格数据
        temp.put("sn","1");
        temp.put("name","张三");
        temp.put("age","18");
        objects.add(temp);
        temp =new HashMap<>();
        temp.put("sn","2");
        temp.put("name","里斯");
        temp.put("age","20");
        objects.add(temp);
        maps.put("picture",piePort);
        maps.put("personlist",objects);
        maps.put("title", "资产台账报表");
        //构建折线图数据
        Map<String, Double> datas=new HashMap<>();
        datas.put("Map", (double) 1000);
        datas.put("List", (double) 650);
        datas.put("String", (double) 600);
        datas.put("Long", (double) 432);
        ImageEntity linePort = ChartUtilsAbandon.createLinePort("类型折线图统计", datas, "年份", "月份", "E:\\c.png");
        maps.put("discounting",linePort);
        //构建柱状图数据
        Map<String, Double> datass=new HashMap<>();
        datass.put("Map", (double) 1000);
        datass.put("List", (double) 650);
        datass.put("String", (double) 600);
        datass.put("Long", (double) 432);
        //构建复杂的柱状图

        ImageEntity imageEntity = createHistogram("类型柱状图统计", datass, "E:\\hhh.png");
        maps.put("histogram",imageEntity);
        WordUtil.exportWord("templates/demo1.docx","E:/","生成文件.docx",maps);

    }

    @Test
    public void j(){
        HashMap<String, Object> maps = new HashMap<>();
        maps.put("username", "张三");
        maps.put("date","2019-10-10");
        maps.put("desc","测试");
        maps.put("boo",true);
        WordUtil.exportWord("templates/demo1.docx","E:/","生成文件.docx",maps);
    }


    /**
	 * 生成测试柱状图
	 *
	 * @throws Exception
	 */
	@Test
	public void testCreateBarChart() throws Exception {
	    //需要的参数:x轴(数组)、类别(String)、数据(Double[])
        Double[] x=new Double[]{1.2,3.2,2.3,53.2,66.1,77.2,11.2,44.2,55.1,66.8,2.3,98.8};

		// 标注类别
		String[] categories = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
				"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
		Vector<Serie> series = new Vector<Serie>();
        // 柱子名称:柱子所有的值集合
		series.add(new Serie("Tokyo", x));
		series.add(new Serie("New York", new Double[] { 83.6, 78.8, 98.5, 93.4,
				106.0, 84.5, 105.0, 104.3, 91.2, 83.5, 106.6, 92.3 }));
		series.add(new Serie("London", new Double[] { 48.9, 38.8, 39.3, 41.4,
				47.0, 48.3, 59.0, 59.6, 52.4, 65.2, 59.3, 51.2 }));
		String title = "生成柱状图";
		String categoryAxisLabel = "时间轴";
		String valueAxisLabel = "数量轴";
		JFreeChart chart = com.example.demo.utils.ChartFactory.createBarChart(title,
				categoryAxisLabel, valueAxisLabel, series, categories);
		File file = new File("E:\\柱状图.png");
		int width = 1024;
		int height = 420;
		ChartUtilities.saveChartAsPNG(file, chart, width, height);
		ImageEntity imageEntity=new ImageEntity(ImgConversion.imgToByte("E:\\柱状图.png"),850,420);
        ImageEntity imageEntity1 = this.testCreateLineChart();
        ImageEntity imageEntity2 = this.testCreatePieChart();
        ImageEntity imageEntity3 = this.testCreateStackedBarChart();
        Map<String, Object> maps=new HashMap<>();
        maps.put("title","漏洞统计报告");
        maps.put("picture",imageEntity);
        maps.put("discounting",imageEntity1);
        maps.put("histogram",imageEntity2);
        maps.put("complexFigure",imageEntity3);
        WordUtil.exportWord("templates/demo1.docx","E:/","生成文件.docx",maps);
	}



    /**
      * 测试饼图
      *
      * @throws Exception
      */
    @Test
     public ImageEntity testCreatePieChart() throws Exception {
         //类别(数组)、数据(一个数组)
      String[] categories = { "Ban", "Ki", "Mi nu", "Ora",
        "App", "Pe", "Cl", "Re",
        "Gra"};
      Object[] datas = { 8, 3, 1, 6, 8, 4, 4, 1, 1};
      String title = "生成饼图";
      JFreeChart chart = com.example.demo.utils.ChartFactory
        .createPieChart(title, categories, datas);
      File file = new File("E:\\饼图.png");
      int width = 400;
      int height = 250;
      ChartUtilities.saveChartAsPNG(file, chart, width, height);
      ImageEntity imageEntity=new ImageEntity(ImgConversion.imgToByte("E:\\饼图.png"),400,250);
      return imageEntity;
     }
     /**
      * 测试折线图
      *
      * @throws Exception
      */
     public ImageEntity testCreateLineChart() throws Exception {
      // 标注类别
      String[] categories = { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
        "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
      Vector<Serie> series = new Vector<Serie>();
      // 柱子名称:柱子所有的值集合
      series.add(new Serie("Tokyo", new Double[] { 49.9, 71.5, 106.4, 129.2,
        144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4 }));
      series.add(new Serie("New York", new Double[] { 83.6, 78.8, 98.5, 93.4,
        106.0, 84.5, 105.0, 104.3, 91.2, 83.5, 106.6, 92.3 }));
      series.add(new Serie("London", new Double[] { 48.9, 38.8, 39.3, 41.4,
        47.0, 48.3, 59.0, 59.6, 52.4, 65.2, 59.3, 51.2 }));
      series.add(new Serie("Berlin", new Double[] { 42.4, 33.2, 34.5, 39.7,
        52.6, 75.5, 57.4, 60.4, 47.6, 39.1, 46.8, 51.1 }));
      String title = "生成折线图";
      String categoryAxisLabel = "";
      String valueAxisLabel = "数量";
      JFreeChart chart = com.example.demo.utils.ChartFactory.createLineChart(title,
        categoryAxisLabel, valueAxisLabel, series, categories);
      File file = new File("E:\\折线图.png");
      int width = 1024;
      int height = 420;
      ChartUtilities.saveChartAsJPEG(file, chart, width, height);
      ImageEntity imageEntity=new ImageEntity(ImgConversion.imgToByte("E:\\折线图.png"),850,450);
      return imageEntity;
//      Map<String, Object> maps=new HashMap<>();
//      maps.put("picture",imageEntity);
//      WordUtil.exportWord("templates/demo1.docx","E:/","生成文件.docx",maps);


     }

     /**
      * 测试StackedBarChart
      *
      * @throws Exception
      */
     public ImageEntity testCreateStackedBarChart() throws Exception {
      // 标注类别
      String[] categories = { "J", "F", "M", "A", "M", "J",
        "J", "A", "Sp", "t", "ov", "Dc" };
      Vector<Serie> series = new Vector<Serie>();
      // 柱子名称:柱子所有的值集合
      series.add(new Serie("T", new Double[] { 49.9, 71.5, 106.4, 129.2,
        144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4 }));
      series.add(new Serie("N", new Double[] { 83.6, 78.8, 98.5, 93.4,
        106.0, 84.5, 105.0, 104.3, 91.2, 83.5, 106.6, 92.3 }));
      series.add(new Serie("L", new Double[] { 48.9, 38.8, 39.3, 41.4,
        47.0, 48.3, 59.0, 59.6, 52.4, 65.2, 59.3, 51.2 }));
      series.add(new Serie("B", new Double[] { 42.4, 33.2, 34.5, 39.7,
        52.6, 75.5, 57.4, 60.4, 47.6, 39.1, 46.8, 51.1 }));
      String title = "生成柱状图";
      String domainAxisLabel = "";
      String rangeAxisLabel = "Rainfall (mm)";
      JFreeChart chart = com.example.demo.utils.ChartFactory.createStackedBarChart(title,
        domainAxisLabel, rangeAxisLabel, series, categories);
      File file = new File("E:\\复杂的柱状图.png");
      int width = 400;
      int height = 250;
      ChartUtilities.saveChartAsPNG(file, chart, width, height);
      ImageEntity imageEntity=new ImageEntity(ImgConversion.imgToByte("E:\\复杂的柱状图.png"),400,250);
      return imageEntity;
     }


     /**
     * 将数据构造成html
     */
    @Test
    public void create() {
         BufferedInputStream in = null;
         FileWriter out = null;
         try {
             //模板文件
             File file = new File("C:/Users/aulus/Desktop/temaple.html");
             //构造输入流
             in = new BufferedInputStream(new FileInputStream(file));
             int len;
             byte[] bytes = new byte[1024];
             //模板内容
             StringBuilder content = new StringBuilder();
             while ((len = in.read(bytes)) != -1) {
                 content.append(new String(bytes, 0, len, "utf-8"));
            }

             //构造Configuration
             Configuration configuration = new Configuration(Configuration.VERSION_2_3_23);
             //构造StringTemplateLoader
             StringTemplateLoader loader = new StringTemplateLoader();
             //添加String模板
             loader.putTemplate("test", content.toString());
             //把StringTemplateLoader添加到Configuration中
             configuration.setTemplateLoader(loader);

             //构造Model
             usera users = new usera();
             users.setTitle("生成的HTML标题");
             //图片
             List<userSon> userSons = new ArrayList<>();
             userSon uS = new userSon("姓名","年龄","邮箱");
             userSons.add(uS);
             users.setColumnName(userSons);

             for (int i=0;i<100;i++){
                 userSon userSon = new userSon("张三"+i,"20"+i,"123fnajskl@qq.com");
                 userSon.setIiii("小小");
                 userSon.setCsnr("1997-3-4");
                 userSon.setOooo("不知道填什么");
                 userSon.setUuuu("不知道填什么");
                 userSon.setPppp("不知道填什么");
                 userSons.add(userSon);
                 users.setColumnName(userSons);

             }
             //获取模板
             Template template = configuration.getTemplate("test");
             //构造输出路
             out = new FileWriter("E:/result.html");


             //图片:
             // 标注类别
              String[] categories = { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
                "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
              Vector<Serie> series = new Vector<Serie>();
              // 柱子名称:柱子所有的值集合
              series.add(new Serie("Tokyo", new Double[] { 49.9, 71.5, 106.4, 129.2,
                144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4 }));
              series.add(new Serie("New York", new Double[] { 83.6, 78.8, 98.5, 93.4,
                106.0, 84.5, 105.0, 104.3, 91.2, 83.5, 106.6, 92.3 }));
              series.add(new Serie("London", new Double[] { 48.9, 38.8, 39.3, 41.4,
                47.0, 48.3, 59.0, 59.6, 52.4, 65.2, 59.3, 51.2 }));
              series.add(new Serie("Berlin", new Double[] { 42.4, 33.2, 34.5, 39.7,
                52.6, 75.5, 57.4, 60.4, 47.6, 39.1, 46.8, 51.1 }));
              String title = "生成折线图";
              String categoryAxisLabel = "";
              String valueAxisLabel = "数量";
              JFreeChart chart = com.example.demo.utils.ChartFactory.createLineChart(title,
                categoryAxisLabel, valueAxisLabel, series, categories);
              File fsile = new File("E:\\折线图.png");
              int width = 850;
              int height = 450;
              ChartUtilities.saveChartAsJPEG(fsile, chart, width, height);


             String imgStr = base.getImgStr("E:\\折线图.png");

             users.setPath("data:image/png;base64,"+imgStr);
             //生成HTML
             template.process(users, out);
        } catch (FileNotFoundException e) {
             e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
             e.printStackTrace();
        } catch (IOException e) {
             e.printStackTrace();
        } catch (TemplateException e) {
             e.printStackTrace();
        } finally {
             if (null != in) {
                 try {
                     in.close();
                } catch (IOException e) {
                     e.printStackTrace();
                }
            }
             if (null != out) {
                 try {
                     out.close();
                } catch (IOException e) {
                     e.printStackTrace();
                }
            }
        }
    }

    /**
     * 将HTML转为PDF
     * @throws IOException
     */
    @Test
    public void main() throws IOException {
        File file = new File("C:/Users/aulus/Desktop/");
        file.mkdirs();//判断有没有父路径,没有就创建
        String s = Files.readString(Paths.get("E:\\result.html"));
        itextPdfUtils.generatePdf(s,"C:/Users/aulus/Desktop/stest-01.pdf");


    }
}



 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,您想了解关于使用iTextFreeMarker生成HTML并将其转换为Word文档的内容。首先,您需要了解几个概念: 1. iText是一个用于生成PDF文档的Java库,但它也可以用于生成其他类型的文档,例如Word文档。 2. FreeMarker是一个用于生成动态内容的Java模板引擎,它可以将数据模型与模板文件结合使用生成静态文本文件。 接下来,您可以按照以下步骤来实现HTML转换为Word文档: 1. 创建一个FreeMarker模板文件,其中包含您要生成HTML内容,并将其保存为.ftl文件。 2. 在Java代码中,使用FreeMarker来读取.ftl文件并将数据模型填充到模板中,生成HTML字符串。 3. 使用iTextHTML字符串转换为Word文档。您可以使用iText的XMLWorkerHelper类来实现此功能。 以下是一个简单的示例代码,用于将HTML字符串转换为Word文档: ``` // Step 1: Load the FreeMarker template Configuration cfg = new Configuration(Configuration.VERSION_2_3_28); cfg.setDirectoryForTemplateLoading(new File("templates")); Template template = cfg.getTemplate("my_template.ftl"); // Step 2: Generate HTML string from the template and data model Map<String, Object> data = new HashMap<>(); data.put("name", "John Doe"); StringWriter out = new StringWriter(); template.process(data, out); String html = out.getBuffer().toString(); // Step 3: Convert HTML to Word document using iText ByteArrayOutputStream baos = new ByteArrayOutputStream(); Document document = new Document(); PdfWriter writer = PdfWriter.getInstance(document, baos); document.open(); XMLWorkerHelper.getInstance().parseXHtml(writer, document, new ByteArrayInputStream(html.getBytes())); document.close(); // Save the Word document to file FileOutputStream fos = new FileOutputStream("output.docx"); fos.write(baos.toByteArray()); fos.close(); ``` 请注意,此示例代码仅用于说明概念,并且可能需要进行修改以适合您的特定需求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值