将html网页展示的图表,下载到PPT文档内,以图片的形式展示在PPT内

使用到的工具有:
开发工具:IDEA
报表开发工具:帆软10.0.19
1、针对帆软报表[普通报表]的设置
1.1首先选中在帆软里制作好的报表,选择模板web属性
在这里插入图片描述
1.2.选择数据分析模式,添加一个事件设置,该事件应该设置“加载结束”
在这里插入图片描述
1.3.在Js脚本里写这段代码:

var node = document.getElementsByClassName('x-table')[0].parentElement;
var message = {nodeId: '自定义一个别名',nodeInnerHTML: node.innerHTML
};
window.parent.postMessage(message, '*');

在这里插入图片描述
–绘制表格及如何将帆软报表展示到html不做过多赘述

给生成PPT方法添加一个按钮事件:

$("#DOWNLOAD").on("click", function () {//给每个表格设置一个新的IDupdateTableId();var timeBucket = $("#inqu_status-0-timeBucket").val();let orderYear = timeBucket.substring(0, 4)let orderMonth = timeBucket.substring(4, 6)let orderYearC = orderYear + '年'let orderMonthC = orderMonth + '月'var inInfo = new EiInfo();var promises = []; // 存储生成图片的 Promise//确保每个table都生成了BASE64编码document.querySelectorAll(".html2canvas table").forEach((v, k, p) => {var promise = html2canvas(document.querySelector('#' + v.id), {}).then((canvas) => {//根据当前id获取tr的数量。1tr假设等于11PX 从而计算出数据表格的高度let tableHeight = v.querySelectorAll("tr").length * 11;let src = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream"); // 将canvas转换成img的src流console.log(v.id, k)inInfo.set(v.id, src)inInfo.set(v.id + 'Height', tableHeight.toString())});promises.push(promise);})//所有报表的base64编码都在promises里后,调用后台服务Promise.all(promises).then(() => {inInfo.set("{{Year}}", `${orderYear}`)inInfo.set("{{Month}}", `${orderMonth}`)inInfo.set("{{YearC}}", `${orderYearC}`)inInfo.set("{{MonthC}}", `${orderMonthC}`)inInfo.set("{{YearMonth}}", `${orderYear}${orderMonth}`)inInfo.set("{{YearMonthC}}", `${orderYearC}${orderMonthC}`)var jsonEi = inInfo.toJSONString(true);console.log(jsonEi)post(IPLATUI.CONTEXT_PATH + "/DownloadAgree", {"temporaryId": "PM15", "jsonEi": jsonEi});// IPLAT.progress($("#result"), false);});IPLAT.progress($("#result"), false);})
function updateTableId() {var tables = document.querySelectorAll("table[class^='x-table']");for (var i = 0; i < tables.length; i++) {tables[i].setAttribute("id", "newTableId" + i);num = i;}
}

调用后台:DownloadAgree,通过该服务,去调用具体实现方法

package com.baosight.bgdsp.rp.pm;import com.baosight.iplat4j.core.ei.EiConstant;
import com.baosight.iplat4j.core.ei.EiInfo;
import com.baosight.iplat4j.core.service.soa.XLocalManager;import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;public class DownloadAgree extends HttpServlet{@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response) {EiInfo eiInfo = EiInfo.parseJSONString(request.getParameter("jsonEi"));String temporaryId = request.getParameter("temporaryId");if (temporaryId.equals("PM")) {eiInfo.set("response", response);eiInfo.set(EiConstant.serviceName, "RPPM07");eiInfo.set(EiConstant.methodName, "exportPPT");eiInfo = XLocalManager.callNewTx(eiInfo);}if (temporaryId.equals("PM15")) {eiInfo.set("response", response);eiInfo.set(EiConstant.serviceName, "RPPM15");eiInfo.set(EiConstant.methodName, "exportPPT");eiInfo = XLocalManager.callNewTx(eiInfo);}}protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{doGet(request, response);}
}

exportPPT方法:

public EiInfo exportPPT(EiInfo inInfo) throws IOException {HttpServletResponse response = (HttpServletResponse) inInfo.get("response");// 创建一个空的演示文稿String url = "";String os = System.getProperty("os.name").toLowerCase();boolean isMacOS = os.contains("mac");if (isMacOS) {url = PlatApplicationContext.getProperty("bgdsp." + projectEnv + ".share.template.mac");} else {url = PlatApplicationContext.getProperty("bgdsp." + projectEnv + ".share.template");}String tempName = PlatApplicationContext.getProperty("bgdsp." + projectEnv + ".share.template.rppm15");// 读取模板文件//InputStream resource = new ClassPathResource("/Users/apple/Desktop/-job/2022-development/iplat4j/渠道长龄库存压降情况汇报_template.pptx").getInputStream();FileInputStream inputStream = new FileInputStream(url + tempName);
//        FileInputStream inputStream = new FileInputStream("E://" + tempName);// 根据模板,创建一个新的ppt文档XMLSlideShow ppt = new XMLSlideShow(inputStream);// 读取模板PPTinputStream.close();Map<String, String> attr = inInfo.getAttr();attr.put("netPrice_2", getReportsToimage());//        List<XSLFSlide> slides = ppt.getSlides();// 得到每页pptXSLFSlide[] slides = ppt.getSlides().toArray(new XSLFSlide[0]);// 遍历ppt,填充模板for (XSLFSlide slide : slides) {
//            List<XSLFShape> shapes = slide.getShapes();XSLFShape[] shapes = slide.getShapes().toArray(new XSLFShape[0]);// 遍历每页ppt中待填充的形状组件for (XSLFShape shape : shapes) {if (shape instanceof XSLFTextShape) {// 替换文本XSLFTextShape textShape = (XSLFTextShape) shape;String textValue = textShape.getText();String shapeName = textShape.getShapeName();boolean flag = false;for (String text : extractContent(textValue)) {if (attr.containsKey(text)) {flag = true;//使用mustache语法替换文字 {{YearC}}营{{MonthC}}销预案会textValue = textValue.replace(text, attr.get(text));}}if (flag && StringUtils.isNotBlank(textValue)) {List<XSLFTextParagraph> paragraphs = textShape.getTextParagraphs();for (XSLFTextParagraph paragraph : paragraphs) {List<XSLFTextRun> textRuns = paragraph.getTextRuns();for (XSLFTextRun textRun : textRuns) {textRun.setText("");}}XSLFTextRun textRun2 = textShape.getTextParagraphs().get(0).getTextRuns().get(0);textRun2.setText(textValue);}} else if (shape instanceof XSLFPictureShape) {XSLFPictureShape pictureShape = (XSLFPictureShape) shape;XSLFPictureData pictureData = pictureShape.getPictureData();String imageName = pictureShape.getShapeName();String imageBase64 = attr.get(imageName);if (imageBase64 != null) {byte[] bt = Base64.getDecoder().decode(imageBase64.split(",")[1]);XSLFPictureData idx = ppt.addPicture(bt, PictureData.PictureType.PNG);XSLFPictureShape pic = slide.createPicture(idx);Rectangle2D anchor = pictureShape.getAnchor();//高度取决于数据表格的条数 宽度固定pic.setAnchor(new Rectangle2D.Double(anchor.getX(), anchor.getY(), anchor.getWidth(), anchor.getHeight()));pictureShape.setAnchor(new Rectangle2D.Double(10, 0, 0, 0));}}}}String fileName = "PPT名字" + DateUtils.curDateTimeStr14() + ".pptx";// 保存PPT文件//设置输出文件类型为pptx文件response.setContentType(CONTENT_TYPE_OF_PPT);response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, CHARSET_OF_UTF8));response.setHeader("Pragma", URLEncoder.encode(fileName, CHARSET_OF_UTF8));ServletOutputStream outputStream = response.getOutputStream();ppt.write(outputStream);outputStream.flush();outputStream.close();return new EiInfo();}

extractContent方法:

public static List<String> extractContent(String input) {List<String> contents = new ArrayList<>();int startIndex = input.indexOf("{{");while (startIndex != -1) {int endIndex = input.indexOf("}}", startIndex);if (endIndex != -1) {String content = input.substring(startIndex, endIndex + 2);contents.add(content);startIndex = input.indexOf("{{", endIndex);} else {break;}}return contents;}

getReportsToimage()方法:该方法针对的是:帆软报表的普通报表中,出现非表格报表的处理方法[即:柱状图、折线图等],通过直接访问帆软链接的方式去获取表格的base64编码。

private String getReportsToimage() throws IOException {String reportAddress = PlatApplicationContext.getProperty("bgdsp." + projectEnv + ".report.address");// 创建HttpClient对象CloseableHttpClient httpClient = HttpClients.createDefault();try {// 构造请求URLString apiUrl = reportAddress + "/rp/pm/netPrice_2.cpt&format=image&extype=JPG";// 创建HttpGet请求//HttpPost request = new HttpPost(apiUrl);System.out.println("apiUrl");System.out.println(apiUrl);HttpGet httpGet = new HttpGet(apiUrl);// 设置请求头部httpGet.addHeader("Content-Type", "text/html; charset=utf-8");// 发送请求并获取响应HttpResponse responsed = httpClient.execute(httpGet);// 解析响应数据HttpEntity entity = responsed.getEntity();// 检查响应是否成功if (responsed.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {// 获取Content-Type头部信息Header contentTypeHeader = entity.getContentType();String contentType = contentTypeHeader.getValue();// 获取输入流InputStream inStream = entity.getContent();ByteArrayOutputStream outputStream_u = new ByteArrayOutputStream();// 将图片裁剪为宽60px,高60pxBufferedImage originalImage = ImageIO.read(inStream);BufferedImage croppedImage = originalImage.getSubimage(0, 0, 3560, 1560);// 将裁剪后的图片转换成字节数组ByteArrayOutputStream outputStream_c = new ByteArrayOutputStream();ImageIO.write(croppedImage, "png", outputStream_c);byte[] croppedImageBytes = outputStream_c.toByteArray();// 将图片数据编码为base64格式String base64Image = Base64.getEncoder().encodeToString(croppedImageBytes);System.out.println(base64Image);String responseBody = EntityUtils.toString(entity);// 处理响应数据System.out.println(responseBody);// 关闭输入流和输出流inStream.close();outputStream_u.close();return "data:image/png;base64," + base64Image;} else {System.out.println("HTTP请求失败!");}} catch (PlatException e) {}return "";}

最后,在设置PPT模板的时候,将模板内的图片设置为修改后的别名:newTableIdi

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/757061.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【滑动窗口、矩阵】算法例题

目录 三、滑动窗口 30. 长度最小的子数组 ② 31. 无重复字符的最长子串 ② 32. 串联所有单词的子串 ③ 33. 最小覆盖子串 ③ 四、矩阵 34. 有效的数独 ② 35. 螺旋矩阵 ② 36. 旋转图像 ② 37. 矩阵置零 ② 38. 生命游戏 ② 三、滑动窗口 30. 长度最小的子数组 ② 给…

Pillow教程:翻转图像

在Pillow&#xff08;PIL的一个分支&#xff09;库中&#xff0c;Image.transpose() 方法用于翻转或旋转图像。这个方法接受一个参数&#xff0c;该参数是翻转或旋转操作的类型&#xff0c;以预定义的常量来表示。以下是一些可用的常量及其描述&#xff1a; 1.翻转图像&#x…

Android Studio配置buildTypes{}后,gradle中Tasks列表不显示assembleRelease。

打开Files → Settings → Experimental 取消选中 "Do not build Gradle task list during Grafle sync"

CentOS 7.9 常用环境配置

文章目录 环境准备安装docker安装Java安装maven安装git安装MYSQL安装Redis安装RabbitMq安装minio 环境准备 操作系统版本为centos 7.9&#xff0c;内核版本需要在3.10以上 sudo uname -rsudo cat /etc/redhat-release1.确认环境好后&#xff0c;安装工具包并设置仓库 sudo yum…

SpringBoot通过拦截器和JWT令牌实现登录验证

1. Jwt 工具类 引入依赖 <dependency><groupId>com.auth0</groupId><artifactId>java-jwt</artifactId><version>4.4.0</version> </dependency>JwtUtil 类包含了两个静态方法&#xff1a;generateToken() 用于生成 JWT&…

图书馆管理系统 2.后台系统管理模块编写

后端 1.实体类编写 用户实体类 package jkw.pojo;import com.baomidou.mybatisplus.annotation.TableField; import com.baomidou.mybatisplus.annotation.TableId; import lombok.Data;import java.io.Serializable; import java.util.List;/*** 用户*/ Data public class …

Redis高频八股文与解决策略

什么是Redis&#xff1f; Redis是一个高性能的非关系型的键值对数据库&#xff0c;使用C编写实现的。与传统的数据库不同的是Redis是存在内存中的&#xff0c;所以读写速度非常快&#xff0c;每秒可以处理超过10万次的读写操作&#xff0c;这也是Redis常常被用作缓存的原因。 什…

Unity Toggle处理状态变化事件

Toggle处理状态变化事件&#xff0c;有两个方法。 法一、通过Inspector面板设置 实现步骤&#xff1a; 在Inspector面板中找到Toggle组件的"On Value Changed"事件。单击""按钮添加一个新的监听器。拖动一个目标对象到"None (Object)"字段&am…

研究人员发现 OpenAI ChatGPT、Google Gemini 的漏洞

自 OpenAI 推出 ChatGPT 以来&#xff0c;生成式 AI 聊天机器人的数量及其在企业中的采用率在一年多时间里呈爆炸式增长&#xff0c;但网络安全专业人士的担忧也随之增加&#xff0c;他们不仅担心威胁组织对新兴技术的使用&#xff0c;还担心大型网络的安全性及模型&#xff08…

点云预处理——滤波、旋转和平移等处理

目录 一、环境配置 二、步骤 一、环境配置 安装好ubuntu系统和ROS环境 操作系统: Ubuntu 20.04 wget http://fishros.com/install -O fishros && . fishros 二、步骤 打开终端&#xff0c;并在终端命令行输入以下指令: git clone https://gitee.com/wccworld/…

MNN Session 创建执行器(六)

系列文章目录 MNN createFromBuffer&#xff08;一&#xff09; MNN createRuntime&#xff08;二&#xff09; MNN createSession 之 Schedule&#xff08;三&#xff09; MNN createSession 之创建流水线后端&#xff08;四&#xff09; MNN Session::resize 之流水线编码&am…

MFC界面美化第三篇----自绘按钮(重绘按钮)

1.前言 最近发现读者对我的mfc美化的专栏比较感兴趣&#xff0c;因此在这里进行续写&#xff0c;这里我会计划写几个连续的篇章&#xff0c;包括对MFC按钮的美化&#xff0c;菜单栏的美化&#xff0c;标题栏的美化&#xff0c;list列表的美化&#xff0c;直到最后形成一个完整…

中小企业Java/SpringBoot体系技术抽象沉淀

目录 1. 起因 2. 参考 3.总结&#xff1a; 1. 起因 企业开发的过程中会逐渐沉淀自己的一些公共starter&方法等&#xff1b;建议可以整合开源项目与自身沉淀的一些做一个统一的parent包 2. 参考 内容参考内容框架包&#xff0c;基础core包&#xff0c;统一返回&#x…

详解Redis的持久化RDB和AOF

Redis的持久化是将内存中的数据同步到硬盘的过程 具体来说&#xff0c;Redis支持两种主要的持久化方式&#xff1a;RDB 和 AOF。 RDB&#xff08;Redis Database&#xff09; 简介 默认持久化方式 RDB会将内存中的数据快照保存到磁盘上的一个二进制文件中。这个文件包含了…

创建React+Ts项目

1.创建脚手架 create-react-app 项目名称 --template typescript 2.配置路径别名 配置路径别名---React_h5 路径别名设置-CSDN博客 3.添加组件库 npm i antd --save App.tsx 文件 引用 ant design react import React from react;import { Button } from antd;function …

NLP---Bert分词

目录&#xff1a; Q&#xff1a;bert分词步骤1&#xff1a;构建N * N 的相关性矩阵&#xff0c;计算相邻两个字的相关性&#xff0c;低的话&#xff08;<阈值&#xff09;就切割。2&#xff1a;将A词进行mask计算出A的embedding&#xff0c;然后将AB两个词一起mask&#xff…

4.线性数据结构——3.栈及例题

标准库的栈 定义&#xff1a;stack<typename> myStack;大小&#xff1a;size()压栈&#xff1a;push()弹栈&#xff1a;pop()栈顶&#xff1a;top()判空&#xff1a;empty() #include <cstdio> #include <string> #include <map> #include <algor…

视觉信息处理和FPGA实现第5次作业-Matlab实现图像逆时针旋转90度

一、Matlab2022a安装 链接&#xff1a;https://pan.quark.cn/s/6e177bc7c11d 提取码&#xff1a;dKNN 二、Matlab使用 2.1 新建一个脚本文件&#xff08;.m文件&#xff09; 2.2 另存为到便于归档的地方 考虑到.m文件如果不是全英文路径&#xff0c;也有可能会出问题&#…

Linux 服务升级:MySQL 主从(半同步复制) 平滑升级

目录 一、实验 1.环境 2.Mysql-shell 检查工具兼容性 3.逻辑备份MySQL数据 4.备份MySQL 数据目录、安装目录、配置文件 5.MySQL 升级 6.master节点 使用systemd管理mysql8 7. slave1 节点升级 8. slave2 节点升级 9.半同步设置 二、问题 1.mysqldump备份报错 2.Inn…

Docker部署dart-frog服务

参考&#xff1a; dart-frog官网&#xff1a;https://dartfrog.vgv.dev/docs/overview 使用 Dart Frog 体验 Dart 服务端开发 - 简书 打包项目 按照demo新增项目后&#xff0c;执行&#xff1a; dart_frog build 等待build后生成 build 文件夹&#xff0c;这个文件夹就是需要…