Java PDF Tester Demo
PDF Tester and Gson usage demo
package zztj.ecs.img;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.stream.JsonReader;
import com.newCompany.hippo.core.junit.HippoJunitTest;
import com.newCompany.iobs.sdk.repkg.com.google.gson.reflect.TypeToken;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.beetl.core.resource.ClasspathResourceLoader;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import zztj.ecs.entirety.evaluate.bean.EcsAnswerScoreT;
import zztj.ecs.entirety.evaluate.bean.vo.*;
import zztj.ecs.entirety.evaluate.service.EcsAnswerUserReportService;
import zztj.ecs.entirety.evaluate.service.EcsAnswerUserReportServiceImpl;
import zztj.ecs.exam.common.constant.ExamConstant;
import zztj.ecs.exam.common.constant.ExamStatusConstant;
import zztj.ecs.exam.common.util.AESEncryptor;
import zztj.ecs.exam.common.util.UUIDHexGenerator;
import zztj.ecs.exam.common.util.UrlToBase64Util;
import zztj.ecs.exam.core.bean.EcsExamT;
import zztj.ecs.proxy.tale.query.TalebaseTQuery;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.math.BigDecimal;
import java.util.*;
import java.util.List;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import org.beetl.core.Configuration;
import org.beetl.core.GroupTemplate;
import org.beetl.core.Template;
import org.beetl.core.resource.ClasspathResourceLoader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.xhtmlrenderer.pdf.ITextRenderer;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.ImmutableMap;
import com.lowagie.text.DocumentException;
import com.lowagie.text.pdf.BaseFont;
import zztj.ecs.core.api.report.bean.ReportDetail;
import zztj.ecs.core.api.report.bean.ReportExportFile;
import zztj.ecs.core.api.report.bean.ResponseReport;
import zztj.ecs.exam.common.constant.BaseScoreLineConstant;
import zztj.ecs.exam.common.constant.CuteReportStatusConstant;
import zztj.ecs.exam.common.constant.ThreeSixZoreConstant;
import zztj.ecs.exam.core.bean.EcsExamT;
import zztj.ecs.exam.core.service.EcsExamDetailTService;
import zztj.ecs.exam.core.service.EcsExamTService;
public class PDFTester {
private static final Logger logger = LoggerFactory.getLogger(PDFTester.class);
private static GroupTemplate gt;
public static void main(String args[]) throws Exception {
String jsonString = "{\"examId\":\"4FC39543306749DF9B2CF0256C402FCF\",\"version\":\"4\",\"userList\":[{\"roleId\":\"1\",\"roleName\":\"被评估对象\",\"answerUserId\":\"5B1A4C7E330740BCB70617012C4AEC7A\",\"userUm\":\"XIELIYING001\",\"userName\":\"谢立英\"},{\"roleId\":\"3\",\"roleName\":\"上级\",\"answerUserId\":\"F96706DC7C9241BA80806227F3DD0F14\",\"userUm\":\"YINWENJUN001\",\"userName\":\"尹文军\"},{\"roleId\":\"4\",\"roleName\":\"平级\",\"answerUserId\":\"A2B8C5D798694903AF59FBB710802CFC\",\"userUm\":\"SONGJING01\",\"userName\":\"宋菁\"}],\"percentageList\":[{\"roleId\":\"3\",\"roleName\":\"上级\",\"percentage\":70},{\"roleId\":\"4\",\"roleName\":\"平级\",\"percentage\":30}]}";
AnswerUserReportVO vo = new Gson().fromJson(jsonString, new TypeToken<AnswerUserReportVO>() {
}.getType());
System.err.println("vo = " + vo);
// generateLineChartImg();
}
private static void PDFGene() throws IOException {
ClasspathResourceLoader classLoader = new ClasspathResourceLoader();
Configuration cfg = Configuration.defaultConfiguration();
gt = new GroupTemplate(classLoader, cfg);
logger.info("create360PDF start");
long startTime = System.currentTimeMillis();
ReportExportFile exportFile = new ReportExportFile();
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
Template t = null;
t = gt.getTemplate("/template/report360PDF2.html");
String fileName = "D:\\jsonString.txt";
JsonReader reader = new JsonReader(new FileReader(fileName));
HashMap<String, Object> data = new Gson().fromJson(reader, new TypeToken<HashMap<String, Object>>() {
}.getType());
t.binding(ImmutableMap.of("responseReport", data));
ITextRenderer renderer = new ITextRenderer();
renderer.setDocumentFromString(t.render());
renderer.layout();
try {
renderer.createPDF(byteArrayOutputStream);
} catch (DocumentException e) {
}
gt.close();
}
private static void generateLineChartImg() throws IOException {
String fileName = "D:\\jsonString.txt";
JsonReader reader = new JsonReader(new FileReader(fileName));
ArrayList<EcsAnswerScoreT> scoreTList = new Gson().fromJson(reader, new TypeToken<ArrayList<EcsAnswerScoreT>>() {
}.getType());
File imageF = new File("D:\\cutpng\\tagcpgs.png");
logger.info("获取报告json:{}", "a");
BufferedImage image = ImageIO.read(imageF);
logger.info("imageF:{},{}", image.getWidth(), image.getHeight());//2530 3580
int w = image.getWidth();
int h = image.getHeight();
Graphics2D g = image.createGraphics();
int baseImageX = 153;
int baseImageY = 289;
int xd = 23;//除以2是因为有0.5,所以x轴间距减半
int yd = 69;
int r = 6;
Float width = 3F;
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g.setFont(new Font("微软雅黑", Font.PLAIN, 40));
g.setStroke(new BasicStroke(width));
g.setColor(Color.BLACK);
Color color = Color.RED;
for (int i = 0; i < scoreTList.size(); i++) {
g.setColor(color);
int xdTimesNext = 0;
String score = scoreTList.get(i).getScore();
int xdTimes = 20 - (int) (Double.parseDouble(score) * 2);
if (i < scoreTList.size() - 1) {
String scoreNext = scoreTList.get(i + 1).getScore();
System.err.println("score = " + score + ", \"scoreNext\": " + scoreNext);
xdTimesNext = 20 - (int) (Double.parseDouble(scoreNext) * 2);
}
int upLimit = 0;
if (i >= 0 && i < 8) {// group 1
drawGroupDogLegLine(g, baseImageX, baseImageY, xd, yd, r, color, i, xdTimesNext, xdTimes, upLimit);
}
if (i >= 8 && i < 16) {// group 2
upLimit = 8;
baseImageX = 840;
drawGroupDogLegLine(g, baseImageX, baseImageY, xd, yd, r, color, i, xdTimesNext, xdTimes, upLimit);
} else if (i >= 16) {// group 3
upLimit = 16;
baseImageX = 1521;
drawGroupDogLegLine(g, baseImageX, baseImageY, xd, yd, r, color, i, xdTimesNext, xdTimes, upLimit);
}
}
logger.info("xd:{}, yd:{}", xd, yd);
g.dispose();
File outPUtFile = new File("D:\\testImg.png");
ImageIO.write(image, "png", outPUtFile);
}
private static void drawGroupDogLegLine(Graphics2D g, int baseImageX, int baseImageY, int xd, int yd, int r, Color color, int i, int xdTimesNext, int xdTimes, int upLimit) {
int j = i - upLimit;
int x1 = baseImageX + xd * xdTimes;
int y1 = baseImageY + yd * (j);
int x2 = baseImageX + xd * xdTimesNext;
int y2 = baseImageY + yd * (j + 1);
if (j < 7) {
g.drawLine(x1, y1, x2, y2);
}
//先画白底圆心
g.setColor(Color.white);
g.fillOval(x1 - r, y1 - r, 2 * r, 2 * r);
//再画圆框
g.setColor(color);
g.drawOval(x1 - r, y1 - r, 2 * r, 2 * r);
}
private static void GsonDemo() throws IOException {
List<EcsExamT> list = new ArrayList<>();
EcsExamT ecsExamT = new EcsExamT();
ecsExamT.setId(UUIDHexGenerator.getUUID());
ecsExamT.setUserName("托尔斯泰");
ecsExamT.setUserId("dfadsfd");
ecsExamT.setDeptId("test");
ecsExamT.setAppId(ExamConstant.SYSTEM_APP_ID);
list.add(ecsExamT);
String fileName = jsonStringToFile(list);
JsonReader reader = new JsonReader(new FileReader(fileName));
ArrayList<EcsExamT> list2 = new Gson().fromJson(reader, new TypeToken<ArrayList<EcsExamT>>() {
}.getType());
System.err.println("list2 = " + list2);
}
private static String jsonStringToFile(List<EcsExamT> list) throws IOException {
String fileName = "D:\\jsonString2.txt";
FileWriter writer = new FileWriter(fileName);
Gson gson = new GsonBuilder().create();
gson.toJson(list, writer);
writer.close();
return fileName;
}
@Autowired
private EcsAnswerUserReportService ecsAnswerUserReportService;
@Test
public void drawCodeBaseTeaser() throws Exception {
String version = "4";
String jsonString = "{\"examId\":\"FEA72C94DF034BB186E060E9C4D0298A\",\"version\":\"4\",\"userList\":[{\"roleId\":\"1\",\"roleName\":\"被评估对象\",\"answerUserId\":\"CB319FF9D83B4D6993259DC8AC11E5E3\",\"userUm\":\"CHENPENGYU001\",\"userName\":\"陈鹏宇\"},{\"roleId\":\"2\",\"roleName\":\"执行官\",\"answerUserId\":\"42693EDEFF0E49899964BA2837A033E1\",\"userUm\":\"NIUXIUYING001\",\"userName\":\"牛秀英\"},{\"roleId\":\"2\",\"roleName\":\"执行官\",\"answerUserId\":\"B0CA42C9C8D9479C8DE5344C04E883ED\",\"userUm\":\"ZENGQINGBING001\",\"userName\":\"曾庆兵\"},{\"roleId\":\"3\",\"roleName\":\"上级\",\"answerUserId\":\"8C305145914A4A7A8C49689AEA8AD7FF\",\"userUm\":\"WANYAO001\",\"userName\":\"万瑶\"},{\"roleId\":\"3\",\"roleName\":\"上级\",\"answerUserId\":\"42DD9B8C5C514B85BD805451AFE02388\",\"userUm\":\"YANGWANJUN001\",\"userName\":\"杨万平\"},{\"roleId\":\"9\",\"roleName\":\"人事\",\"answerUserId\":\"8FBF8127014A4F88AA3715DB7C6476B8\",\"userUm\":\"ZHANGKAI021\",\"userName\":\"张凯\"},{\"roleId\":\"4\",\"roleName\":\"平级\",\"answerUserId\":\"B94517D5D4264590A9175A290B7DEF79\",\"userUm\":\"MANING012\",\"userName\":\"马宁\"}],\"percentageList\":[{\"roleId\":\"2\",\"roleName\":\"执行官\",\"percentage\":35},{\"roleId\":\"3\",\"roleName\":\"上级\",\"percentage\":35},{\"roleId\":\"9\",\"roleName\":\"人事\",\"percentage\":0},{\"roleId\":\"4\",\"roleName\":\"平级\",\"percentage\":30}]}";
AnswerUserReportVO vo = new Gson().fromJson(jsonString, new TypeToken<AnswerUserReportVO>() {
}.getType());
String examId = "FEA72C94DF034BB186E060E9C4D0298A";
ReportDownload reportDownload = ecsAnswerUserReportService.generateReportAndUpload(examId, vo, version);
System.err.println("reportDownload = " + reportDownload);
}
public static void drawCodeBase() throws IOException {
EcsAnswerUserReportServiceImpl ecsAnswerUserReportService = new EcsAnswerUserReportServiceImpl();
List<Map<String, List<EcsAnswerScoreT>>> listMap = new ArrayList<>();
HashMap<String, List<EcsAnswerScoreT>> stringListHashMap = new HashMap<>();
listMap.add(stringListHashMap);
byte[] bytes = ecsAnswerUserReportService.drawPdfCpgs(listMap);
}
public static String multiPercentRound(String score, int percent) {
if (StringUtils.isBlank(score)) {
return "0";
}
BigDecimal bgScore = new BigDecimal(score);
BigDecimal bgPercent = new BigDecimal(percent);
bgScore = bgScore.multiply(bgPercent).divide(new BigDecimal(100)).setScale(1, BigDecimal.ROUND_HALF_UP);
return bgScore.toString();
}
public static void draw() {
String username = "Xt0SEnB0tZ2SC6clzgQ+ZA==";
String password = "WmYJgCX3KZlK4/9OQ+epgw==";
List<String> list = new ArrayList<>();
TalebaseTQuery talebaseTQuery = new TalebaseTQuery();
list.add(username);
list.add(password);
username = AESEncryptor.decode(username, "1qwas#@14reWQAS%", "67fjkf@#$SDdsKIo");
password = AESEncryptor.decode(password, "1qwas#@14reWQAS%", "67fjkf@#$SDdsKIo");
System.out.println(username);
System.out.println(password);
logger.info("获取报告json:{}", "a");
try {
long start = System.currentTimeMillis();
File imageF = new File("D:\\cutpng\\cpgs.png");
File imageBla = new File("D:\\cutpng\\bla.png");
File imageYel = new File("D:\\cutpng\\yel.png");
logger.info("获取报告json:{}", "a");
BufferedImage image = ImageIO.read(imageF);
BufferedImage bla = ImageIO.read(imageBla);
BufferedImage yel = ImageIO.read(imageYel);
logger.info("imageF:{},{}", image.getWidth(), image.getHeight());//2530 3580
int w = image.getWidth();
int h = image.getHeight();
Graphics2D g = image.createGraphics();
int xnum = 11;
int ynum = 24;
int xd = 150;
int yd = 123;
int r = 9;
Float width = 4.5F;
int x = 579;
int y = 562;
//设置文字抗锯齿
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g.setFont(new Font("微软雅黑", Font.PLAIN, 40));
g.setStroke(new BasicStroke(width));
g.setColor(Color.BLACK);
//设置画图抗锯齿
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
for (int j = 0; j < 24; j++) {
g.setColor(new Color(227, 108, 12));
if (j < 23) {
int x1 = x + xd * (j % xnum);
int y1 = y + yd * j;
int x2 = x + xd * ((j + 1) % xnum);
int y2 = y + yd * (j + 1);
System.err.println("x1 = " + x1 + ", \"y1\": " + y1 + ", \"x2\": " + x2 + ", \"y2\": " + y2);
g.drawLine(x1, y1, x2, y2);
}
//先画圆心
// g.setColor(Color.green);
// g.fillOval(x+xd*(j%xnum)-r,y+yd*j-r,2*r,2*r);
// //再画圆框
// g.setColor(new Color(227,108,12));
// g.drawOval(x+xd*(j%xnum)-r,y+yd*j-r,2*r,2*r);
}
logger.info("xd:{}, yd:{}", xd, yd);
g.dispose();
File outPUtFile = new File("D:\\testImg.png");
ImageIO.write(image, "png", outPUtFile);
// GraphicsEnvironment e = GraphicsEnvironment.getLocalGraphicsEnvironment();
// String[] fontName = e.getAvailableFontFamilyNames();
// for (int i = 0; i < fontName.length; i++) {
// System.out.println(fontName[i]);
// }
long end = System.currentTimeMillis();
logger.info("costs{}ms", (end - start));
} catch (Exception e) {
logger.error(e.getMessage(), e);
}
System.out.println(multiPercentRound("100.01", 60));
}
public static void testFile() {
File file = new File("D:\\test.xlsx");
if (file.canExecute()) {
logger.info("1");
}
if (file.canWrite()) {
logger.info("2");
}
}
public static void download() throws IOException {
String path = "D:\\test.pdf";
FileOutputStream fos = new FileOutputStream(new File(path));
byte[] fileBytes = UrlToBase64Util.getImageFromNetByUrl("http://iobs-lf.example.com/download/zztj-hrx-dmz-prd/2c99722f69e327b1016a00d9f1e60128");
IOUtils.write(fileBytes, fos);
}
public static void TEST(int n) throws IOException {
List<Integer> list1 = new ArrayList<>();
for (int i = 0; i <= n; i++) {
int temp = 2 << i;
if (temp <= n) {
list1.add(temp);
}
}
}
public static void TESTImage() throws IOException {
File imageF = new File("D:\\mail_logo.jpg");
FileInputStream fis = new FileInputStream(imageF);
BufferedImage image = ImageIO.read(imageF);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int count = -1;
while ((count = fis.read(buf)) > -1) {
bos.write(buf, 0, count);
}
byte[] fileByte = bos.toByteArray();
bos.close();
logger.info("fileByte size is:{}", fileByte.length);
logger.info("data:image/jpg;base64," + org.apache.commons.codec.binary.Base64.encodeBase64String(fileByte));
}
public static void testString() {
String str = "http://stg.iobs-lf.example.com/download/zztj-hrx-dmz-stg/8a34fff563bed7160163bed716d80000";
String str2 = "http://vt.example.com/user-center-web/profile/avatar/vzU96a86e0nO2";
logger.info(str);
logger.info(str2);
}
}
Picture process and Data process
// picture data processing
public static final String base64ImgPre = "data:image/pdf;base64,";
reportData.put("abilityChart", base64ImgPre + Base64.encodeBase64String(abilityChart));
// normal data processing
Map<String, Object> baseInfo = get360ReportBaseInfo(examId);
reportData.put("baseInfo", baseInfo);
Basically, Picture is stored as byte[] stream, or Data processing
网友评论