时间:2022-11-20 10:13:01 | 栏目:JAVA代码 | 点击:次
由于从事的是支付行业,最近对接的一些第三方支付有时候需要我们这边提供用户的资料和交易信息,并且以图片的形式发送给他们,由于这是后台程序自动处理,然后直接发送给第三方支付公司,因此需要后台查出用户的相关信息,然后生成图片,调用第三方提供的接口,将图片链接以附件的形式发给他们,当用户发起dispute操作的时候,触发我方后台的自动处理机制。
1. 依赖的jar包(maven依赖)
<dependency> <groupId>com.github.xuwei-k</groupId> <artifactId>html2image</artifactId> <version>0.1.0</version> </dependency>
2. 代码
package com.generatePic; import gui.ava.html.image.generator.HtmlImageGenerator; public class TestGeneratePic { public static void main(String[] args) { generatePic(); } public static void generatePic() { HtmlImageGenerator htmlImageGenerator = new HtmlImageGenerator(); //format 表示html里的元素,比如表格 String format = "<table>\n" + " <tbody>\n" + " <tr>\n" + "\t<img src="https://static.msport.com/public/up/pocket/operator/msportlogo.png" />\n" + " </tr>\n" + " </tbody>\n" + "</table>\n" + "\n" + "\n" + "<table border =1>\n" + " <tbody>\n" + " <tr>\n" + " <td>User Account(user account number)</td>\n" + " <td>%s</td>\n" + " </tr>\n" + " <tr>\n" + " <td>user's email</td>\n" + " <td>%s</td>\n" + " </tr>\n" + "\t <tr>\n" + " <td>user's name</td>\n" + " <td>%s</td>\n" + " </tr>\n" + " </tbody>\n" + "</table>\n" + "</br>\n" + "\n" + "<table>\n" + " <tbody>\n" + " <tr>\n" + " <font size = "4">\n" + " <b>PAYMENT INFOMATION</b> \n" + " </font>\n" + " </tr>\n" + " </tbody>\n" + "</table>\n" + "\n" + "<table border =1>\n" + " <tbody>\n" + " <tr>\n" + " <td>Transaction Reference</td>\n" + " <td>%s</td>\n" + " </tr>\n" + " <tr>\n" + " <td>Transaction Amount</td>\n" + " <td>%s</td>\n" + " </tr>\n" + "\t<tr>\n" + " <td>Currency</td>\n" + " <td>%s</td>\n" + " </tr>\n" + "\t<tr>\n" + " <td>Transaction Status</td>\n" + " <td>%s</td>\n" + " </tr>\n" + "\t<tr>\n" + " <td>Transaction Date</td>\n" + " <td>%s</td>\n" + " </tr>\n" + "\t<tr>\n" + " <td>Payment Type</td>\n" + " <td>%s</td>\n" + " </tr>\n" + "\t<tr>\n" + " <td>Card Number</td>\n" + " <td>%s</td>\n" + " </tr>\n" + "\t<tr>\n" + " <td>Service Details</td>\n" + " <td>%s</td>\n" + " </tr>\n" + " </tbody> \n" + "</table>\n" + "<br/>\n" + "\n" + "<table>\n" + " <tbody>\n" + " <tr>\n" + " <font size = "4">\n" + " <b>SERVICE HISTORY</b> \n" + " </font>\n" + " </tr>\n" + " </tbody>\n" + "</table>\n" + "\n" + "<table border =1>\n" + "<thead>\n" + " <tr>\n" + " <th>DATE</th>\n" + " <th>DESCRIPTION</th>\n" + " <th>AMOUNT</th>\n" + " <th>BALANCE</th>\n" + " </tr>\n" + " </thead>\n" + " \n" + " <tbody>\n" + " <tr>\n" + " <td>%s</td>\n" + " <td>%s</td>\n" + " <td>%s</td>\n" + " <td>%s</td>\n" + " </tr>\n" + " <tr>\n" + " <td>%s</td>\n" + " <td>%s</td>\n" + " <td>%s</td>\n" + " <td>%s</td>\n" + " </tr>\n" + " </tbody>\n" + "</table>\n" + "\n" + "\n"; String finalHtml = "<html></body>" + format + "</body></html>"; htmlImageGenerator.loadHtml(finalHtml); //图片名 String fileName = "1" + ".png"; htmlImageGenerator.saveAsImage(fileName); } }
3. 生成的图片
生成的图片路径默认在项目路径下:
4. 实际应用的建议
可以通过 String.format() 函数, 拼接实际的数据,比如3中的%s就可以替换为实际的数据,最后生成自己想要的数据,如果你的前端技术足够好,那么你可以在后台画出更优美的图片。