JAVA如何后台导出带统计图PDF?

您所在的位置:网站首页 医学英语求职信范文10篇 JAVA如何后台导出带统计图PDF?

JAVA如何后台导出带统计图PDF?

2023-08-10 14:39| 来源: 网络整理| 查看: 265

JAVA如何后台导出带统计图PDF? 原创

?小恺恺 2021-09-11 11:12:07 ©著作权

文章标签 数据 坐标轴 折线图 图例 饼图 文章分类 代码人生

©著作权归作者所有:来自51CTO博客作者?小恺恺的原创作品,请联系作者获取转载授权,否则将追究法律责任 “ JAVA如何后台生成PDF?如何生成带统计图的PDF?” 01—JAVA如何生成PDFJAVA如何生成PDF:

java生成PDF文件有以下两个解决方案:

(1)使用easyPoi生成excel或者word在转成PDF。

(2)使用itextpdf直接生成PDF。

本文主要使用第二种办法,来实现这个需求。

操作步骤:(1)导入pom文件  com.itextpdf itextpdf 5.5.13 com.itextpdf itext-asian 5.2.0 (2)编写代码  public static void main(String[] args) { try { create(); System.out.println("生成成功"); } catch (Exception ex) { System.out.println("文件路径错误或者权限不够"); } } private static void create() throws Exception { String FILE_DIR = "/Users/zhoukai/Desktop/"; // 创建一个文档(默认大小A4,边距36, 36, 36, 36) Document document = new Document(); // 设置文档大小 document.setPageSize(PageSize.A4); // 设置边距,单位都是像素,换算大约1厘米=28.33像素 document.setMargins(50, 50, 50, 50); // 设置pdf生成的路径 FileOutputStream fileOutputStream = new FileOutputStream(FILE_DIR + "demo.pdf"); // 创建writer,通过writer将文档写入磁盘 PdfWriter writer = PdfWriter.getInstance(document, fileOutputStream); Font font = createFont(10, Font.NORMAL, BaseColor.BLACK); // demo String title = "监控中心XXX统计分析报告"; String content = "2021年3月,本企业共有XXX车辆上线,XXX车辆未上线,车辆上线率为x%,与去年同比下降XXX"; // 打开文档,只有打开后才能往里面加东西 document.open(); // 设置作者 document.addAuthor("casic"); // 设置创建者 document.addCreator("casic"); // 设置主题 document.addSubject(title); // 设置标题 document.addTitle(title); // 设置标题 Paragraph paragraphHead1 = createHead1(title); document.add(paragraphHead1); // 设置标题时间 Paragraph paragraphHeadTime = createHeadTime("2021-07-20"); document.add(paragraphHeadTime); document.add(new Paragraph(content + "\n\r", font)); // 增加一个段落 document.add(new Paragraph("一、XXX监控概况:\n\r", font)); // 创建表格,3列的表格 PdfPTable table = new PdfPTable(3); table.setTotalWidth(PageSize.A4.getWidth() - 100); table.setLockedWidth(true); // 创建头 String[] tableHeadStr = {"指标名称", "指标值", "环比值"}; createTableHead(table, tableHeadStr); // 创建每一行的值 List tableContentList = new ArrayList(10); VehicleIndex vehicleIndex = new VehicleIndex(); vehicleIndex.setIndexName("车辆在线率"); vehicleIndex.setIndexValue("86.7%"); vehicleIndex.setChainValue("-13%"); tableContentList.add(vehicleIndex); VehicleIndex vehicleIndex2 = new VehicleIndex(); vehicleIndex2.setIndexName("轨迹完整率"); vehicleIndex2.setIndexValue("58.37%"); vehicleIndex2.setChainValue("-0.3%"); tableContentList.add(vehicleIndex2); // 添加表格内容 createTableContent(table, tableContentList); document.add(table); // 关闭文档,才能输出 document.close(); writer.close(); } /** * 创建表格内容 * * @param table 表格对象 * @param tableContentList 表格内容对象 */ private static void createTableContent(PdfPTable table, List tableContentList) throws DocumentException, IOException { if (ObjectUtils.isEmpty(tableContentList)) { return; } for (VehicleIndex vehicleIndex : tableContentList) { //获取设置表格内容的字体与内容 table.addCell(createTableContent(vehicleIndex.getIndexName())); table.addCell(createTableContent(vehicleIndex.getIndexValue())); table.addCell(createTableContent(vehicleIndex.getChainValue())); } } /** * 根据传入的标题名称:批量设置标题值 * * @param table 创建的表格对象 * @param tableHeadStr 每个标题值按顺序来 */ private static void createTableHead(PdfPTable table, String[] tableHeadStr) throws DocumentException, IOException { if (ObjectUtils.isEmpty(tableHeadStr)) { return; } //获取设置表格标题的字体 Font font = createFont(10, Font.NORMAL, BaseColor.BLACK); for (String tableHead : tableHeadStr) { PdfPCell cell = new PdfPCell(new Phrase(tableHead, font)); cell.setBackgroundColor(new BaseColor(221, 221, 221)); cell.setMinimumHeight(20); cell.setUseAscender(true); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); table.addCell(cell); } } /** * 设置标题下的时间字段 * * @param time 时间 * @return 时间的段落 */ private static Paragraph createHeadTime(String time) throws DocumentException, IOException { Font font = createFont(14, Font.BOLD, BaseColor.BLACK); Paragraph paragraph = new Paragraph(time, font); paragraph.setAlignment(Element.ALIGN_CENTER); return paragraph; } /** * 设置一级标题 * * @param title 标题内容 * @return 标题段落 */ private static Paragraph createHead1(String title) throws DocumentException, IOException { Font font = createFont(22, Font.BOLD, BaseColor.BLACK); Paragraph paragraph = new Paragraph(title, font); paragraph.setAlignment(Element.ALIGN_CENTER); return paragraph; } /** * 设置表格内容 * * @param title 标题内容 * @return 表格标题内容 */ private static PdfPCell createTableContent(String title) throws DocumentException, IOException { Font font = createFont(10, Font.NORMAL, BaseColor.BLACK); PdfPCell cell = new PdfPCell(new Phrase(title, font)); cell.setMinimumHeight(20); cell.setUseAscender(true); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); return cell; } /** * 根据传入的参数生成PDF文档使用的字体 * * @param fontSize 字体大小 * @param fontMode 字体正常、加粗、下划线等 * @param fontColor 字体颜色 * @return 返回生成的字体 */ private static Font createFont(int fontSize, int fontMode, BaseColor fontColor) throws DocumentException, IOException { BaseFont bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED); return new Font(bfChinese, fontSize, fontMode, fontColor); } (3)输出结果‍

JAVA如何后台导出带统计图PDF?_折线图

 

如果你的需求只是导出文字、表格或图片插入的话,直接使用上述代码就可以直接完成,但是如果要导出统计图该怎么办呢?请看下一章节。

02—JAVA如何生成统计图并插入PDFJAVA如何生成统计图:

java生成统计图,我们这里主要使用一款老牌工具包jfreeChart。

官方网站:https://www.jfree.org/jfreechart

这里参考网上资料整理了一份生成条形图、折线图、饼图的工具类,有需要的小伙伴直接复制就可以了。

  public class JFreeChartUtils { private static final String NO_DATA_MSG = "暂无数据"; private static final 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 RectangleInsets(5, 12, 5, 12)); // X坐标轴垂直网格颜色 chartTheme.setDomainGridlinePaint(new Color(192, 208, 224)); // Y坐标轴水平网格颜色 chartTheme.setRangeGridlinePaint(new Color(192, 192, 192)); 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()); // XYBar 渲染 chartTheme.setXYBarPainter(new StandardXYBarPainter()); 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)); } /** * 设置折线图样式 * @param plot 折线图对象 * @param isShowDataLabels 是否显示数据标题 * @param isShapesVisible 是否显示数据点 */ 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)); } // 数据点绘制形状 renderer.setDefaultShapesVisible(isShapesVisible); setXAixs(plot); setYAixs(plot); } /** * 设置饼状图渲染 * @param plot 饼图对象 */ 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.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 plot 类别图表对象 */ public static void setXAixs(CategoryPlot plot) { Color lineColor = new Color(31, 121, 170); plot.getDomainAxis().setCategoryLabelPositions(CategoryLabelPositions.UP_45); // X坐标轴颜色 plot.getDomainAxis().setAxisLinePaint(lineColor); // X坐标轴标记|竖线颜色 plot.getDomainAxis().setTickMarkPaint(lineColor); } /** * 设置类别图表(CategoryPlot) Y坐标轴线条颜色和样式 同时防止数据无法显示 * @param plot 类别图表对象 */ public static void setYAixs(CategoryPlot plot) { Color lineColor = new Color(31, 121, 170); ValueAxis axis = plot.getRangeAxis(); // Y坐标轴颜色 axis.setAxisLinePaint(lineColor); // Y坐标轴标记|竖线颜色 axis.setTickMarkPaint(lineColor); // false隐藏Y刻度 axis.setAxisLineVisible(true); axis.setTickMarksVisible(true); // Y轴网格线条 plot.setRangeGridlinePaint(new Color(192, 192, 192)); plot.setRangeGridlineStroke(new BasicStroke(1)); // 设置顶部Y坐标轴间距,防止数据无法显示 plot.getRangeAxis().setUpperMargin(0.1); // 设置底部Y坐标轴间距 plot.getRangeAxis().setLowerMargin(0.1);    } /** * 提供静态方法:获取折线图 * * @param title 标题 * @param datas 数据 * @param xName x轴名字 * @param yName y轴名字 * @param url 输出文档地址 */ public static void createLinePort(String title, Map datas, String xName, String yName, String url) { try { //种类数据集 DefaultCategoryDataset dataset = new DefaultCategoryDataset(); //遍历map for (Map.Entry entry : datas.entrySet()) { dataset.setValue(Double.parseDouble(entry.getValue() + ""), title, entry.getKey()); } //创建2D折线图,折线图分水平显示和垂直显示两种 //legend:是否显示图例(对于简单的柱状图必须是false) //tooltips:是否生成工具 //urls:是否生成URL链接 JFreeChart chart = ChartFactory.createLineChart(title, xName, yName, dataset, PlotOrientation.VERTICAL, false, true, true); //得到绘图区 setLineRender((CategoryPlot) chart.getPlot(), true, true); org.jfree.chart.ChartUtils.saveChartAsPNG(new File(url), chart, 1000, 600); } catch (Exception e) { e.printStackTrace(); } } /** * 提供静态方法:获取报表图形:饼状图 * * @param title 标题 * @param datas 数据 * @param url 输出文档地址 */ public static void createPiePort(String title, Map datas, String url) { try { // 如果不使用Font,中文将显示不出来 DefaultPieDataset pds = new DefaultPieDataset(); //遍历map for (Map.Entry entry : datas.entrySet()) { pds.setValue(entry.getKey(), Double.parseDouble(entry.getValue().toString())); } /** * 生成一个饼图的图表 * 分别是:显示图表的标题、需要提供对应图表的DateSet对象、是否显示图例、是否生成贴士以及是否生成URL链接 */ JFreeChart chart = ChartFactory.createPieChart(title, pds, true, true, true); setPieRender(chart.getPlot()); //将内存中的图片写到本地硬盘 org.jfree.chart.ChartUtils.saveChartAsPNG(new File(url), chart, 800, 500); } catch (Exception e) { e.printStackTrace(); } } /** * 提供静态方法:获取报表图形:条形图 * * @param title 标题 * @param datas 数据 * @param url 输出文档地址 */ public static void createBarPort(String title, Map datas, String url) { try { // 如果不使用Font,中文将显示不出来 DefaultCategoryDataset pds = new DefaultCategoryDataset(); //遍历map for (Map.Entry entry : datas.entrySet()) { pds.setValue(Double.parseDouble(entry.getValue() + ""), entry.getKey(), entry.getKey()); } /** * 生成一个饼图的图表 * 分别是:显示图表的标题、需要提供对应图表的DateSet对象、是否显示图例、是否生成贴士以及是否生成URL链接 */ JFreeChart chart = ChartFactory.createBarChart(title, "分类", "数量", pds, PlotOrientation.VERTICAL, true, true, false); //将内存中的图片写到本地硬盘 org.jfree.chart.ChartUtils.saveChartAsPNG(new File(url), chart, 800, 500); } catch (Exception e) { e.printStackTrace(); } } /** * 生成折线图并返回byte数组 * * @param title 标题 * @param datas 数据 * @param xName X轴 * @param yName Y轴 * @return 生成的折线图byte数组 */ public static byte[] createLinePortByte(String title, Map datas, String xName, String yName) { try { //种类数据集 DefaultCategoryDataset dataset = new DefaultCategoryDataset(); //遍历map for (Map.Entry entry : datas.entrySet()) { dataset.setValue(Double.parseDouble(entry.getValue() + ""), title, entry.getKey()); } //创建2D折线图,折线图分水平显示和垂直显示两种 //legend:是否显示图例(对于简单的柱状图必须是false) //tooltips:是否生成工具 //urls:是否生成URL链接 JFreeChart chart = ChartFactory.createLineChart(title, xName, yName, dataset, PlotOrientation.VERTICAL, false, true, true); //得到绘图区 setLineRender((CategoryPlot) chart.getPlot(), true, true); ByteArrayOutputStream bas = new ByteArrayOutputStream(); ChartUtils.writeChartAsJPEG(bas, 1.0f, chart, 800, 500, null); return bas.toByteArray(); } catch (Exception e) { e.printStackTrace(); } return null; } /** * 生成饼图,并返回byte数组 * * @param title 标题 * @param datas 数据 * @return 返回生成的byte数组 */ public static byte[] createPiePortByte(String title, Map datas) { try { // 如果不使用Font,中文将显示不出来 DefaultPieDataset pds = new DefaultPieDataset(); //遍历map for (Map.Entry entry : datas.entrySet()) { pds.setValue(entry.getKey(), Double.parseDouble(entry.getValue().toString())); } /** * 生成一个饼图的图表 * 分别是:显示图表的标题、需要提供对应图表的DateSet对象、是否显示图例、是否生成贴士以及是否生成URL链接 */ JFreeChart chart = ChartFactory.createPieChart(title, pds, true, true, true); setPieRender(chart.getPlot()); ByteArrayOutputStream bas = new ByteArrayOutputStream(); ChartUtils.writeChartAsJPEG(bas, 1.0f, chart, 800, 500, null); return bas.toByteArray(); } catch (Exception e) { e.printStackTrace(); } return null; } /** * 生成条形图,并返回byte数组 * * @param title 标题 * @param datas 数据 * @return 返回生成的byte数组 */ public static byte[] createBarPortByte(String title, Map datas, String xName, String yName) { try { // 如果不使用Font,中文将显示不出来 DefaultCategoryDataset pds = new DefaultCategoryDataset(); //遍历map for (Map.Entry entry : datas.entrySet()) { pds.setValue(Double.parseDouble(entry.getValue() + ""), entry.getKey(), entry.getKey()); } /** * 生成一个饼图的图表 * 分别是:显示图表的标题、需要提供对应图表的DateSet对象、是否显示图例、是否生成贴士以及是否生成URL链接 */ JFreeChart chart = ChartFactory.createBarChart(title, xName, yName, pds, PlotOrientation.VERTICAL, true, true, false); ByteArrayOutputStream bas = new ByteArrayOutputStream(); ChartUtils.writeChartAsJPEG(bas, 1.0f, chart, 800, 500, null); return bas.toByteArray(); } catch (Exception e) { e.printStackTrace(); } return null; }} jfreeChart如何生成文件流,直接导入PDF:    ByteArrayOutputStream bas = new ByteArrayOutputStream(); ChartUtils.writeChartAsJPEG(bas, 1.0f, chart, 800, 500, null); return bas.toByteArray(); itextpdf如何使用jfreeChart生成的统计图:  在关闭文档之前添加: // 添加统计图 createTotal(document)   /** * 生成折线、饼图、条形图 * @param document * @throws DocumentException * @throws IOException */ private static void createTotal(Document document) throws DocumentException, IOException { //添加折线图 Map map = new HashMap(16); map.put("2021-07-22", (double) 10.1); map.put("2021-07-23", (double) 4.2); map.put("2021-07-24", (double) 12.8); map.put("2021-07-25", (double) 18.9); map.put("2021-07-26", (double) 20.3); map.put("2021-07-27", (double) 30.1); byte[] chartByte = JFreeChartUtils.createLinePortByte("车辆在线率统计", map, "时间", "在线率"); if (ObjectUtils.isEmpty(chartByte)) { return; } Image image = Image.getInstance(chartByte); image.setAlignment(Image.ALIGN_CENTER); image.scaleAbsolute(500, 300); document.add(image); byte[] chartByte1 = JFreeChartUtils.createPiePortByte("车辆在线率统计", map); if (ObjectUtils.isEmpty(chartByte1)) { return; } Image image1 = Image.getInstance(chartByte1); image1.setAlignment(Image.ALIGN_CENTER); image1.scaleAbsolute(500, 300); document.add(image1); byte[] chartByte2 = JFreeChartUtils.createBarPortByte("车辆在线率统计", map,"时间", "在线率"); if (ObjectUtils.isEmpty(chartByte2)) { return; } Image image2 = Image.getInstance(chartByte2); image2.setAlignment(Image.ALIGN_CENTER); image2.scaleAbsolute(500, 300); document.add(image2); }   参考内容:https://www.jianshu.com/p/f9a85de760f2

 

 

 

收藏 评论 分享 举报

上一篇:系统架构设计师32小时通关笔记:一、系统架构设计师概述

下一篇:如何设计王者荣耀角色转移服务避免系统崩溃(附服务架构方案)



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3