Java-BufferedImage动态生成一个表格图片

需求:一个word模板,里边有一个表格,需要根据需求动态填充数据,需要转成pdf,但是我发现转成pdf的方式并不方便,想着还不如将动态的部分生成图片,然后由前端整合其他部分用于展示,也满足了需求。

word生成png-效果图

需要生成图片部分的效果图

word生成png-结果图

生成完之后的图:(ps:字体大小和颜色啥的都可以自己变动,此仅仅是完成了功能)
生成完之后的图

核心代码

数据整合部分

public String actionExportReport(HttpServletRequest request, List<Map<String, String>> mapList,
      Double totalAmount) {
    //中间核心值
    ArrayList<List<String>> list = new ArrayList<>();
    mapList.stream().forEach(e -> {
      Collection<String> stringList = e.values();
      List<String> listString = new ArrayList<>(stringList);
      list.add(listString);
    });
    //表格第一行的名称
    ArrayList<List<String>> listNew = new ArrayList<>();
    List<String> titleList = new ArrayList<>();
    titleList.add("名称");
    titleList.add("规格");
    titleList.add("单位");
    titleList.add("单价");
    titleList.add("数量");
    titleList.add("金额(元)");
    titleList.add("备注");
    listNew.add(titleList);
    listNew.addAll(list);
    //编写最后一行的数值统计
    List<String> statisticsList = new ArrayList<>();
    statisticsList.add("合计");
    statisticsList.add("大写");
    String amount = String.format("%.2f", totalAmount);
    statisticsList.add(numberUppercase.toChinese(amount));
    statisticsList.add("");
    statisticsList.add("金额");
    String amountString = "¥" + amount + "元";
    statisticsList.add(amountString);
    listNew.add(statisticsList);
	//核心代码
    BufferedImage bufferedImage = ImageQrCoderShare.wordPngBase(listNew);
    String shareImageUrl;
    if (null != bufferedImage) {
      //存储服务器代码,忽略
      String urlPath = "/images/contract/info";
      shareImageUrl = getImageUrl(bufferedImage, request,111L, urlPath);
    } else {
      shareImageUrl = "";
    }
    return shareImageUrl;

  }

表格设置部分

public static BufferedImage wordPngBase(ArrayList<List<String>> list) {
    //封装了画图类 用于画图初始化,设置图标题、表格行列数
    BufferedImage bufferedImage = ImageQrCoderShare
        .drawImage("一、买卖物名称、数量、价款(货物采购计划单):", list.size());
    Graphics2D graphics2D = (Graphics2D) bufferedImage.getGraphics();
    //继续向初始化后的graphics2D,存储刚处理的数据内容
    Font font;
    int colwidth = ((ImageQrCoderShare.imageWidth - 20) / ImageQrCoderShare.totalcol);
    for (int n = 0; n < list.size(); n++) {
      for (int l = 0; l < list.get(n).size(); l++) {
      	//封装的字体类,可以直接new就行
        font = definedFontPF.deriveFont(Font.PLAIN, 16);
        graphics2D.setFont(font);
        graphics2D.setColor(Color.BLACK);
        //循环输出,根据表格设置的列设置宽度,也就是起始点
        graphics2D.drawString(
            String.valueOf(list.get(n).get(l)), ImageQrCoderShare.startWidth + colwidth * l + 5,
            ImageQrCoderShare.startHeight + ImageQrCoderShare.rowheight * (n + 2) - 10);
      }
    }
    return bufferedImage;
  }

数据动态生成部分

//封装了画图类 用于画图初始化,设置图标题、表格行列数
public static BufferedImage drawImage(String title, int totalRow) {

    // 图片高度
    int imageHeight = totalRow * rowheight + 50;
    // 单元格宽度
    int colwidth = ((imageWidth - 20) / totalcol);

    BufferedImage bufferedImage = new BufferedImage(imageWidth, imageHeight,
        BufferedImage.TYPE_INT_RGB);

    Graphics2D graphics2D = (Graphics2D) bufferedImage.getGraphics();

    graphics2D.setColor(Color.WHITE);
    graphics2D.fillRect(0, 0, imageWidth, imageHeight);
    graphics2D.setColor(new Color(220, 240, 240));
    for (int j = 0; j < totalRow; j++) {
      graphics2D.setColor(Color.black);
      graphics2D
          .drawLine(startWidth, startHeight + (j + 1) * rowheight, startWidth + colwidth * totalcol,
              startHeight + (j + 1) * rowheight);
    }
    // 画竖线
    for (int k = 0; k < totalcol + 1; k++) {
      graphics2D.setColor(Color.black);
      graphics2D
          .drawLine(startWidth + k * colwidth, startHeight + rowheight, startWidth + k * colwidth,
              startHeight + rowheight * totalRow);
    }
    // 设置字体
    Font font = definedFontPF.deriveFont(Font.PLAIN, 24);
    graphics2D.setFont(font);
    graphics2D.setColor(Color.black);
    // 写标题
    graphics2D.drawString(title, startWidth, startHeight + rowheight - 10);
    return bufferedImage;
  }
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
你可以使用 iText 或者 Apache PDFBox 等 Java 的 PDF 库来生成包含图表表格的 PDF 文件。 iText 是一个广泛使用的 Java PDF 库,支持文本、表格、图像、图表等多种元素。你可以使用 iText 中的 PdfPTable 类来生成表格,使用 ChartFactory.createXXXChart() 等方法生成图表,然后将它们添加到 PDF 中。 以下是使用 iText 生成包含表格图表的 PDF 的示例代码: ```java Document document = new Document(); PdfWriter.getInstance(document, new FileOutputStream("output.pdf")); document.open(); // 添加表格 PdfPTable table = new PdfPTable(3); table.addCell("Header 1"); table.addCell("Header 2"); table.addCell("Header 3"); table.addCell("1.1"); table.addCell("1.2"); table.addCell("1.3"); table.addCell("2.1"); table.addCell("2.2"); table.addCell("2.3"); document.add(table); // 添加图表 JFreeChart chart = ChartFactory.createBarChart( "Chart Title", "X Axis", "Y Axis", dataset, PlotOrientation.VERTICAL, true, true, false ); PdfContentByte contentByte = writer.getDirectContent(); PdfTemplate template = contentByte.createTemplate(400, 300); Graphics2D graphics2D = template.createGraphics(400, 300, new DefaultFontMapper()); Rectangle2D rectangle2D = new Rectangle2D.Double(0, 0, 400, 300); chart.draw(graphics2D, rectangle2D); graphics2D.dispose(); contentByte.addTemplate(template, 0, 0); document.newPage(); document.close(); ``` Apache PDFBox 是另一个 Java PDF 库,它也支持多种元素的生成。你可以使用 PDFBox 中的 PDPageContentStream 类来添加表格图表。 以下是使用 PDFBox 生成包含表格图表的 PDF 的示例代码: ```java PDDocument document = new PDDocument(); PDPage page = new PDPage(); document.addPage(page); // 添加表格 PDPageContentStream contentStream = new PDPageContentStream(document, page); PDTable table = new PDTable(); PDPageContentStreamTableDrawer drawer = new PDPageContentStreamTableDrawer(contentStream, table); table.addCell(new PDCell().addParagraph(new PDParagraph("Header 1"))); table.addCell(new PDCell().addParagraph(new PDParagraph("Header 2"))); table.addCell(new PDCell().addParagraph(new PDParagraph("Header 3"))); table.addCell(new PDCell().addParagraph(new PDParagraph("1.1"))); table.addCell(new PDCell().addParagraph(new PDParagraph("1.2"))); table.addCell(new PDCell().addParagraph(new PDParagraph("1.3"))); table.addCell(new PDCell().addParagraph(new PDParagraph("2.1"))); table.addCell(new PDCell().addParagraph(new PDParagraph("2.2"))); table.addCell(new PDCell().addParagraph(new PDParagraph("2.3"))); drawer.drawTable(100, 700, 400, 0); // 添加图表 JFreeChart chart = ChartFactory.createBarChart( "Chart Title", "X Axis", "Y Axis", dataset, PlotOrientation.VERTICAL, true, true, false ); BufferedImage image = chart.createBufferedImage(400, 300); PDImageXObject ximage = LosslessFactory.createFromImage(document, image); contentStream.drawImage(ximage, 100, 400, 400, 300); contentStream.close(); document.save("output.pdf"); document.close(); ``` 这些示例代码仅供参考,具体实现方式还需要根据你的需求进行调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值