import com.alibaba.fastjson.JSONObject; import com.aliyun.oss.OSSClient; import com.itextpdf.text.pdf.*; import com.swetake.util.Qrcode; import com.titifootball.common.base.BaseController; import com.titifootball.presentation.common.constant.PresentationConstants; import com.titifootball.presentation.dao.model.*; import com.titifootball.presentation.rpc.api.UresultAttributeService; import com.titifootball.presentation.rpc.api.UresultPresentationService; import com.titifootball.presentation.rpc.api.UresultTypeService; import io.swagger.annotations.ApiOperation; import org.apache.batik.transcoder.TranscoderException; import org.apache.batik.transcoder.TranscoderInput; import org.apache.batik.transcoder.TranscoderOutput; import org.apache.batik.transcoder.image.JPEGTranscoder; import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClientBuilder; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.imageio.ImageIO; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import java.awt.*; import java.awt.image.BufferedImage; import java.io.*; import java.net.MalformedURLException; import java.net.URI; import java.net.URL; import java.text.SimpleDateFormat; import java.util.*; import java.util.List; /** * PdfExportController * @author jianhun * @date 2018/08/29 */ @Controller @RequestMapping("/manage/pdf/v1") public class PlayerReportExportController extends BaseController { private final String TEAM_PLAYER_URL="http://localhost:6664/api/v1/upms/team/player/list?teamIds=*"; private final String PLAYER_URL="http://localhost:6664/api/v1/upms/player/list?playerIds=*"; private static final Logger LOGGER = LoggerFactory.getLogger(PlayerReportExportController.class); @Autowired private UresultPresentationService uresultPresentationService; @Autowired private UresultAttributeService uresultAttributeService; @Autowired private UresultTypeService uresultTypeService; @Autowired HttpServletRequest request; String SvgPngPath = ""; String Path = ""; @RequestMapping(value = "/index", method = RequestMethod.GET) public String index() { return "/manage/PDF/index.jsp"; } @ApiOperation(value = "Svg转Png") @RequestMapping(value = "/svgPng", method = RequestMethod.POST) @ResponseBody public Map svgPng(@RequestParam(value = "svg") String svg) throws Exception { Map resultMap=new HashMap(); Boolean flag=false; String msg=""; flag=true; resultMap.put("flag",flag); resultMap.put("message",msg); SvgPng(svg); return resultMap; } public void SvgPng(String svg) throws Exception { String pathSvg = request.getSession().getServletContext().getRealPath( "/")+"\\pdf\\"+"img\\" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+"Radar"+ ".svg"; String pathPng = request.getSession().getServletContext().getRealPath( "/")+"\\pdf\\"+"img\\" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+"Radar"+ ".png"; FileWriter fw = null; File f = new File(pathSvg); try { if (!f.exists()) { f.createNewFile(); } fw = new FileWriter(f); BufferedWriter out = new BufferedWriter(fw); out.write(svg, 0, svg.length()); out.close(); } catch (IOException e) { e.printStackTrace(); } changeSvgToJpg(pathPng, pathSvg); } private void changeSvgToJpg(String pistrPngFile, String pistrSvgPath) { Date date = new Date(); long timeBegin = date.getTime(); String strSvgURI;// svg文件路径 OutputStream ostream = null; File fileSvg = null; try { fileSvg = new File(pistrSvgPath); URI uri = fileSvg.toURI();// 构造一个表示此抽象路径名的 file:URI URL url = uri.toURL();// 根据此 URI 构造一个 URL strSvgURI = url.toString(); TranscoderInput input = new TranscoderInput(strSvgURI);// 定义一个通用的转码器的输入 ostream = new FileOutputStream(pistrPngFile); TranscoderOutput output = new TranscoderOutput(ostream);// 定义单路输出的转码器 JPEGTranscoder transcoder = new JPEGTranscoder();// 构造一个新的转码器,产生JPEG图像 transcoder.addTranscodingHint(JPEGTranscoder.KEY_QUALITY, new Float(0.8));// 设置一个转码过程,JPEGTranscoder.KEY_QUALITY设置输出png的画质精度,0-1之间 transcoder.transcode(input, output);// 转换svg文件为png } catch (MalformedURLException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (TranscoderException e) { e.printStackTrace(); } finally { try { ostream.flush(); ostream.close(); } catch (IOException e) { e.printStackTrace(); } } request.getSession().setAttribute("png",pistrPngFile); fileSvg.delete();// 删除svg文件 } @RequestMapping(value = "/exportPdf", method = RequestMethod.GET) @ResponseBody public Map exportPdf(@RequestParam(value = "assessPlayerId") Long assessPlayerId, HttpServletRequest request) throws Exception { Map resultMap=new HashMap(); Boolean flag=false; String msg=""; Map<String, String> reportData = new HashMap<>(16); Long teamId=0L; Long playerId=0L; try { HttpGet requestTeamPlayer = new HttpGet(TEAM_PLAYER_URL.replace("*",assessPlayerId.toString())); CloseableHttpResponse response = null; CloseableHttpClient httpClient = HttpClientBuilder.create().build(); response = httpClient.execute(requestTeamPlayer);//执行HttpGet请求 HttpEntity httpEntity = response.getEntity();//获得实体 if (httpEntity != null) { InputStream instreams = httpEntity.getContent(); JSONObject jsonObject=JSONObject.parseObject(convertStreamToString(instreams)); if(jsonObject.getInteger("code")==1){ teamId=jsonObject.getJSONArray("data").getJSONObject(0).getLong("teamId"); playerId=jsonObject.getJSONArray("data").getJSONObject(0).getLong("playerId"); } } String basePath = request.getSession().getServletContext().getRealPath( "/")+"\\pdf\\"; String basePathImg = request.getSession().getServletContext().getRealPath( "/")+"\\pdf\\"+"img\\" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+ ".png"; HttpSession session= ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest().getSession(); getQrCodeImg("titifootball.com",basePathImg); Date date = new Date(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd"); String time = sdf.format(date); reportData.put("reportDate",time); reportData.put("reportDate1",time); reportData.put("reportDate2",time); reportData.put("reportDate3",time); reportData.put("reportDate4",time); reportData.put("reportDate5",time); reportData.put("qrcode",basePathImg); reportData.put("qrcode2",basePathImg); reportData.put("qrcode3",basePathImg); reportData.put("qrcode4",basePathImg); reportData.put("qrcode5",basePathImg); reportData.put("qrcode6",basePathImg); reportData.put("PI15","D:\\A.jpeg"); reportData.put("Radarchart",(String) session.getAttribute("png")); System.out.println(reportData); List<Long> uresultTypeIdList = new ArrayList<>(); UresultTypeExample uresultTypeExample = new UresultTypeExample(); uresultTypeExample.createCriteria() .andIsDeletedEqualTo(PresentationConstants.NO); uresultTypeExample.setOrderByClause("id desc"); List<UresultType> uresultTypeList = uresultTypeService.selectByExample(uresultTypeExample); if(null != uresultTypeList && uresultTypeList.size() > 0) { for(UresultType uresultType : uresultTypeList) { uresultTypeIdList.add(uresultType.getId()); } UresultPresentationExample uresultPresentationExample = new UresultPresentationExample(); uresultPresentationExample.createCriteria() .andIsDeletedEqualTo(PresentationConstants.NO) .andAssessmentIdEqualTo(1L) .andAssessPlayerIdEqualTo(assessPlayerId) .andTypeIn(uresultTypeIdList) .andStateEqualTo(PresentationConstants.YES); uresultPresentationExample.setOrderByClause("id asc"); List<UresultPresentationDetail> uresultPresentationDetailList = uresultPresentationService.selectUresultPresentationDetailByExampleForOffsetPage( uresultPresentationExample, 0, 10000); for(UresultPresentationDetail uresultPresentationDetail : uresultPresentationDetailList) { UresultAttribute uresultAttribute=uresultPresentationDetail.getUresultAttribute(); if(null!=uresultAttribute){ String key = uresultPresentationDetail.getUresultAttribute().getCode(); String value = uresultPresentationDetail.getAttrValue(); if (null!=value){ value+=" "+(null!=uresultPresentationDetail.getUresultAttribute().getUnit()?uresultPresentationDetail.getUresultAttribute().getUnit():""); } reportData.put(key, value); } } } String Name = "1"; String identification = "2"; for (String key : reportData.keySet()) { Path = reportData.get("qrcode"); SvgPngPath = reportData.get("Radarchart"); Name = reportData.get("PI06"); identification = reportData.get("PI12"); } String newPdfName= /*Name+"-"+identification+*/"1.pdf"; reportData=generalPdf(basePath+"template/pdf-template.pdf",basePath+"data/"+newPdfName,reportData); OSSClient client = new OSSClient(com.titifootball.presentation.web.PresentationConstants.ALIYUN_OSS_ENDPOINT, com.titifootball.presentation.web.PresentationConstants.ALIYUN_OSS_ACCESSKEYID, com.titifootball.presentation.web.PresentationConstants.ALIYUN_OSS_ACCESSKEYSECRET); String fileUrl="http://"+ com.titifootball.presentation.web.PresentationConstants.ALIYUN_OSS_BUCKNAME+"."+ com.titifootball.presentation.web.PresentationConstants.ALIYUN_OSS_ENDPOINT+"/user-report/"+newPdfName; client.putObject(com.titifootball.presentation.web.PresentationConstants.ALIYUN_OSS_BUCKNAME, "user-report/"+newPdfName, new File(basePath+"data/"+newPdfName)); client.shutdown(); File pdfFile=new File(basePath+"data/"+newPdfName); if (pdfFile.exists()){ pdfFile.deleteOnExit(); } reportData.put("url",fileUrl); DeleteFile(SvgPngPath,Path); return reportData; }catch (Exception e){ e.printStackTrace(); msg=e.getLocalizedMessage(); } resultMap.put("flag",flag); resultMap.put("message",msg); return resultMap; } public Map generalPdf(String templatePath,String newPdfPath,Map reportData){ Map resultMap=new HashMap(); Boolean flag=false; String msg=""; PdfReader reader; FileOutputStream out; ByteArrayOutputStream bos; PdfStamper stamper; PdfImportedPage importedPage; try { out=new FileOutputStream(newPdfPath); reader=new PdfReader(templatePath); bos=new ByteArrayOutputStream(); stamper=new PdfStamper(reader,bos); AcroFields form=stamper.getAcroFields(); Iterator<String> iterator=form.getFields().keySet().iterator(); while (iterator.hasNext()){ String name=iterator.next().toString(); String value=(!reportData.containsKey(name))?"-":reportData.get(name).toString(); System.out.println(name+"<------->"+value); form.setField(name,value); if(("PI15".equals(name)) || ("Radarchart".equals(name))||("qrcode".equals(name)) || ("qrcode2".equals(name)) ||("qrcode3".equals(name)) || ("qrcode4".equals(name)) || ("qrcode5".equals(name)) || ("qrcode6".equals(name))){ String imgpath = reportData.get(name).toString(); System.out.println(form.getFieldPositions(name)); int pageNo = form.getFieldPositions(name).get(0).page; System.out.println(pageNo); com.itextpdf.text.Rectangle Rectangle = form.getFieldPositions(name).get(0).position; float x = Rectangle.getLeft(); float y = Rectangle.getBottom(); float width = Rectangle.getWidth(); float height = Rectangle.getHeight(); // 读图片 com.itextpdf.text.Image image = com.itextpdf.text.Image.getInstance(imgpath); // 获取操作的页面 PdfContentByte pdfContentByte = stamper.getOverContent(pageNo); // 根据域的大小缩放图片 image.scaleToFit(width, height); // 添加图片 image.setAbsolutePosition(x, y); pdfContentByte.addImage(image); } } stamper.setFormFlattening(true); stamper.close(); com.itextpdf.text.Document doc=new com.itextpdf.text.Document(); PdfWriter pdfWriter = PdfWriter.getInstance(doc,bos); // 设置用户密码, 所有者密码,用户权限,所有者权限 pdfWriter.setEncryption("123456".getBytes(), "123456".getBytes(), PdfWriter.ALLOW_COPY, PdfWriter.ENCRYPTION_AES_128); PdfCopy copy=new PdfCopy(doc,out); doc.open(); for (Integer i=1;i<=7;i++){ importedPage=copy.getImportedPage(new PdfReader(bos.toByteArray()),i); copy.addPage(importedPage); } doc.close(); flag=true; }catch (Exception e){ e.printStackTrace(); msg=e.getLocalizedMessage(); } resultMap.put("flag",flag); resultMap.put("message",msg); return resultMap; } public static String convertStreamToString(InputStream is){ BufferedReader reader = new BufferedReader(new InputStreamReader(is)); StringBuilder sb = new StringBuilder(); String line = null; try { while ((line = reader.readLine()) != null) { sb.append(line + "\n"); } } catch (IOException e) { System.out.println("Error=" + e.toString()); } finally { try { is.close(); } catch (IOException e) { System.out.println("Error=" + e.toString()); } } return sb.toString(); } public static void getQrCodeImg(String content, String imgPath) { int width = 80;// 图片宽 int height =80;// 图片高 Qrcode qrcode = new Qrcode();// 实例化一个qrcode对象 qrcode.setQrcodeErrorCorrect('M');// 设置纠错级别(级别有:L(7%) M(15%) Q(25%) H(30%) ) qrcode.setQrcodeEncodeMode('B');// 设置编码方式 qrcode.setQrcodeVersion(7);// 设置二维码版本(版本有 1-40个,) BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);// 开始绘制图片start 1.设置图片大小(BufferedImage.TYPE_INT_RGB:利用三原色绘制二维码) Graphics2D gs = img.createGraphics();// 获取绘图工具start gs.setBackground(Color.WHITE);// 设置背景为白色 gs.clearRect(0, 0, width, height);// 设置一个矩形(四个参数分别为:开始绘图的x坐标,y坐标,图片宽,图片高) gs.setColor(Color.black);// 设置二维码图片的颜色 byte[] bt = null; try { bt = content.getBytes("UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } int py = 2;// 偏移量 boolean[][] code = qrcode.calQrcode(bt);// 开始准备画图 for (int i = 0; i < code.length; i++) { for (int j = 0; j < code.length; j++) { if (code[j][i]) { gs.fillRect(j * 3 + py, i * 3 + py, 3, 3);// 四个参数(画图的起始x和y位置,每个小模块的宽和高(二维码是有一个一个的小模块构成的)); } } } try { ImageIO.write(img, "png", new File(imgPath)); } catch (IOException e) { // TODO Auto-generated catch block System.out.println("二维码异常。。。。。"); e.printStackTrace(); } } public void DeleteFile(String pathPng1,String pathPng2){ File file1 = new File(pathPng1); File file2 = new File(pathPng2); if(file1.exists()){ file1.delete(); } if(file2.exists()){ file2.delete(); } } }
package com.titifootball.presentation.web.controller;
import com.alibaba.fastjson.JSONObject;
import com.aliyun.oss.OSSClient;
import com.itextpdf.text.pdf.*;
import com.swetake.util.Qrcode;
import com.titifootball.common.base.BaseController;
import com.titifootball.presentation.common.constant.PresentationConstants;
import com.titifootball.presentation.dao.model.*;
import com.titifootball.presentation.rpc.api.UresultAttributeService;
import com.titifootball.presentation.rpc.api.UresultPresentationService;
import com.titifootball.presentation.rpc.api.UresultTypeService;
import io.swagger.annotations.ApiOperation;
import org.apache.batik.transcoder.TranscoderException;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.batik.transcoder.image.JPEGTranscoder;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.List;
/**
* PdfExportController
* @author jianhun
* @date 2018/08/29
*/
@Controller
@RequestMapping("/manage/pdf/v1")
public class PlayerReportExportController extends BaseController {
private final String TEAM_PLAYER_URL="http://localhost:6664/api/v1/upms/team/player/list?teamIds=*";
private final String PLAYER_URL="http://localhost:6664/api/v1/upms/player/list?playerIds=*";
private static final Logger LOGGER = LoggerFactory.getLogger(PlayerReportExportController.class);
@Autowired
private UresultPresentationService uresultPresentationService;
@Autowired
private UresultAttributeService uresultAttributeService;
@Autowired
private UresultTypeService uresultTypeService;
@Autowired
HttpServletRequest request;
String SvgPngPath = "";
String Path = "";
@RequestMapping(value = "/index", method = RequestMethod.GET)
public String index() {
return "/manage/PDF/index.jsp";
}
@ApiOperation(value = "Svg转Png")
@RequestMapping(value = "/svgPng", method = RequestMethod.POST)
@ResponseBody
public Map svgPng(@RequestParam(value = "svg") String svg) throws Exception {
Map resultMap=new HashMap();
Boolean flag=false;
String msg="";
flag=true;
resultMap.put("flag",flag);
resultMap.put("message",msg);
SvgPng(svg);
return resultMap;
}
public void SvgPng(String svg) throws Exception {
String pathSvg = request.getSession().getServletContext().getRealPath( "/")+"\\pdf\\"+"img\\" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+"Radar"+ ".svg";
String pathPng = request.getSession().getServletContext().getRealPath( "/")+"\\pdf\\"+"img\\" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+"Radar"+ ".png";
FileWriter fw = null;
File f = new File(pathSvg);
try {
if (!f.exists()) {
f.createNewFile();
}
fw = new FileWriter(f);
BufferedWriter out = new BufferedWriter(fw);
out.write(svg, 0, svg.length());
out.close();
} catch (IOException e) {
e.printStackTrace();
}
changeSvgToJpg(pathPng, pathSvg);
}
private void changeSvgToJpg(String pistrPngFile, String pistrSvgPath) {
Date date = new Date();
long timeBegin = date.getTime();
String strSvgURI;// svg文件路径
OutputStream ostream = null;
File fileSvg = null;
try {
fileSvg = new File(pistrSvgPath);
URI uri = fileSvg.toURI();// 构造一个表示此抽象路径名的 file:URI
URL url = uri.toURL();// 根据此 URI 构造一个 URL
strSvgURI = url.toString();
TranscoderInput input = new TranscoderInput(strSvgURI);// 定义一个通用的转码器的输入
ostream = new FileOutputStream(pistrPngFile);
TranscoderOutput output = new TranscoderOutput(ostream);// 定义单路输出的转码器
JPEGTranscoder transcoder = new JPEGTranscoder();// 构造一个新的转码器,产生JPEG图像
transcoder.addTranscodingHint(JPEGTranscoder.KEY_QUALITY, new Float(0.8));// 设置一个转码过程,JPEGTranscoder.KEY_QUALITY设置输出png的画质精度,0-1之间
transcoder.transcode(input, output);// 转换svg文件为png
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (TranscoderException e) {
e.printStackTrace();
} finally {
try {
ostream.flush();
ostream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
request.getSession().setAttribute("png",pistrPngFile);
fileSvg.delete();// 删除svg文件
}
@RequestMapping(value = "/exportPdf", method = RequestMethod.GET)
@ResponseBody
public Map exportPdf(@RequestParam(value = "assessPlayerId") Long assessPlayerId, HttpServletRequest request) throws Exception {
Map resultMap=new HashMap();
Boolean flag=false;
String msg="";
Map<String, String> reportData = new HashMap<>(16);
Long teamId=0L;
Long playerId=0L;
try {
HttpGet requestTeamPlayer = new HttpGet(TEAM_PLAYER_URL.replace("*",assessPlayerId.toString()));
CloseableHttpResponse response = null;
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
response = httpClient.execute(requestTeamPlayer);//执行HttpGet请求
HttpEntity httpEntity = response.getEntity();//获得实体
if (httpEntity != null) {
InputStream instreams = httpEntity.getContent();
JSONObject jsonObject=JSONObject.parseObject(convertStreamToString(instreams));
if(jsonObject.getInteger("code")==1){
teamId=jsonObject.getJSONArray("data").getJSONObject(0).getLong("teamId");
playerId=jsonObject.getJSONArray("data").getJSONObject(0).getLong("playerId");
}
}
String basePath = request.getSession().getServletContext().getRealPath( "/")+"\\pdf\\";
String basePathImg = request.getSession().getServletContext().getRealPath( "/")+"\\pdf\\"+"img\\" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+ ".png";
HttpSession session= ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest().getSession();
getQrCodeImg("titifootball.com",basePathImg);
Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd");
String time = sdf.format(date);
reportData.put("reportDate",time);
reportData.put("reportDate1",time);
reportData.put("reportDate2",time);
reportData.put("reportDate3",time);
reportData.put("reportDate4",time);
reportData.put("reportDate5",time);
reportData.put("qrcode",basePathImg);
reportData.put("qrcode2",basePathImg);
reportData.put("qrcode3",basePathImg);
reportData.put("qrcode4",basePathImg);
reportData.put("qrcode5",basePathImg);
reportData.put("qrcode6",basePathImg);
reportData.put("PI15","D:\\A.jpeg");
reportData.put("Radarchart",(String) session.getAttribute("png"));
System.out.println(reportData);
List<Long> uresultTypeIdList = new ArrayList<>();
UresultTypeExample uresultTypeExample = new UresultTypeExample();
uresultTypeExample.createCriteria()
.andIsDeletedEqualTo(PresentationConstants.NO);
uresultTypeExample.setOrderByClause("id desc");
List<UresultType> uresultTypeList = uresultTypeService.selectByExample(uresultTypeExample);
if(null != uresultTypeList && uresultTypeList.size() > 0) {
for(UresultType uresultType : uresultTypeList) {
uresultTypeIdList.add(uresultType.getId());
}
UresultPresentationExample uresultPresentationExample = new UresultPresentationExample();
uresultPresentationExample.createCriteria()
.andIsDeletedEqualTo(PresentationConstants.NO)
.andAssessmentIdEqualTo(1L)
.andAssessPlayerIdEqualTo(assessPlayerId)
.andTypeIn(uresultTypeIdList)
.andStateEqualTo(PresentationConstants.YES);
uresultPresentationExample.setOrderByClause("id asc");
List<UresultPresentationDetail> uresultPresentationDetailList =
uresultPresentationService.selectUresultPresentationDetailByExampleForOffsetPage(
uresultPresentationExample, 0, 10000);
for(UresultPresentationDetail uresultPresentationDetail : uresultPresentationDetailList) {
UresultAttribute uresultAttribute=uresultPresentationDetail.getUresultAttribute();
if(null!=uresultAttribute){
String key = uresultPresentationDetail.getUresultAttribute().getCode();
String value = uresultPresentationDetail.getAttrValue();
if (null!=value){
value+=" "+(null!=uresultPresentationDetail.getUresultAttribute().getUnit()?uresultPresentationDetail.getUresultAttribute().getUnit():"");
}
reportData.put(key, value);
}
}
}
String Name = "1";
String identification = "2";
for (String key : reportData.keySet()) {
Path = reportData.get("qrcode");
SvgPngPath = reportData.get("Radarchart");
Name = reportData.get("PI06");
identification = reportData.get("PI12");
}
String newPdfName= /*Name+"-"+identification+*/"1.pdf";
reportData=generalPdf(basePath+"template/pdf-template.pdf",basePath+"data/"+newPdfName,reportData);
OSSClient client = new OSSClient(com.titifootball.presentation.web.PresentationConstants.ALIYUN_OSS_ENDPOINT, com.titifootball.presentation.web.PresentationConstants.ALIYUN_OSS_ACCESSKEYID, com.titifootball.presentation.web.PresentationConstants.ALIYUN_OSS_ACCESSKEYSECRET);
String fileUrl="http://"+ com.titifootball.presentation.web.PresentationConstants.ALIYUN_OSS_BUCKNAME+"."+ com.titifootball.presentation.web.PresentationConstants.ALIYUN_OSS_ENDPOINT+"/user-report/"+newPdfName;
client.putObject(com.titifootball.presentation.web.PresentationConstants.ALIYUN_OSS_BUCKNAME, "user-report/"+newPdfName, new File(basePath+"data/"+newPdfName));
client.shutdown();
File pdfFile=new File(basePath+"data/"+newPdfName);
if (pdfFile.exists()){
pdfFile.deleteOnExit();
}
reportData.put("url",fileUrl);
DeleteFile(SvgPngPath,Path);
return reportData;
}catch (Exception e){
e.printStackTrace();
msg=e.getLocalizedMessage();
}
resultMap.put("flag",flag);
resultMap.put("message",msg);
return resultMap;
}
public Map generalPdf(String templatePath,String newPdfPath,Map reportData){
Map resultMap=new HashMap();
Boolean flag=false;
String msg="";
PdfReader reader;
FileOutputStream out;
ByteArrayOutputStream bos;
PdfStamper stamper;
PdfImportedPage importedPage;
try {
out=new FileOutputStream(newPdfPath);
reader=new PdfReader(templatePath);
bos=new ByteArrayOutputStream();
stamper=new PdfStamper(reader,bos);
AcroFields form=stamper.getAcroFields();
Iterator<String> iterator=form.getFields().keySet().iterator();
while (iterator.hasNext()){
String name=iterator.next().toString();
String value=(!reportData.containsKey(name))?"-":reportData.get(name).toString();
System.out.println(name+"<------->"+value);
form.setField(name,value);
if(("PI15".equals(name)) || ("Radarchart".equals(name))||("qrcode".equals(name)) || ("qrcode2".equals(name)) ||("qrcode3".equals(name)) || ("qrcode4".equals(name)) || ("qrcode5".equals(name)) || ("qrcode6".equals(name))){
String imgpath = reportData.get(name).toString();
System.out.println(form.getFieldPositions(name));
int pageNo = form.getFieldPositions(name).get(0).page;
System.out.println(pageNo);
com.itextpdf.text.Rectangle Rectangle = form.getFieldPositions(name).get(0).position;
float x = Rectangle.getLeft();
float y = Rectangle.getBottom();
float width = Rectangle.getWidth();
float height = Rectangle.getHeight();
// 读图片
com.itextpdf.text.Image image = com.itextpdf.text.Image.getInstance(imgpath);
// 获取操作的页面
PdfContentByte pdfContentByte = stamper.getOverContent(pageNo);
// 根据域的大小缩放图片
image.scaleToFit(width, height);
// 添加图片
image.setAbsolutePosition(x, y);
pdfContentByte.addImage(image);
}
}
stamper.setFormFlattening(true);
stamper.close();
com.itextpdf.text.Document doc=new com.itextpdf.text.Document();
/* PdfWriter pdfWriter = PdfWriter.getInstance(doc,bos);
// 设置用户密码, 所有者密码,用户权限,所有者权限
pdfWriter.setEncryption("123456".getBytes(), "123456".getBytes(), PdfWriter.ALLOW_COPY, PdfWriter.ENCRYPTION_AES_128);*/
PdfCopy copy=new PdfCopy(doc,out);
doc.open();
for (Integer i=1;i<=7;i++){
importedPage=copy.getImportedPage(new PdfReader(bos.toByteArray()),i);
copy.addPage(importedPage);
}
doc.close();
flag=true;
}catch (Exception e){
e.printStackTrace();
msg=e.getLocalizedMessage();
}
resultMap.put("flag",flag);
resultMap.put("message",msg);
return resultMap;
}
public static String convertStreamToString(InputStream is){
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
System.out.println("Error=" + e.toString());
} finally {
try {
is.close();
} catch (IOException e) {
System.out.println("Error=" + e.toString());
}
}
return sb.toString();
}
public static void getQrCodeImg(String content, String imgPath) {
int width = 80;// 图片宽
int height =80;// 图片高
Qrcode qrcode = new Qrcode();// 实例化一个qrcode对象
qrcode.setQrcodeErrorCorrect('M');// 设置纠错级别(级别有:L(7%) M(15%) Q(25%) H(30%) )
qrcode.setQrcodeEncodeMode('B');// 设置编码方式
qrcode.setQrcodeVersion(7);// 设置二维码版本(版本有 1-40个,)
BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);// 开始绘制图片start 1.设置图片大小(BufferedImage.TYPE_INT_RGB:利用三原色绘制二维码)
Graphics2D gs = img.createGraphics();// 获取绘图工具start
gs.setBackground(Color.WHITE);// 设置背景为白色
gs.clearRect(0, 0, width, height);// 设置一个矩形(四个参数分别为:开始绘图的x坐标,y坐标,图片宽,图片高)
gs.setColor(Color.black);// 设置二维码图片的颜色
byte[] bt = null;
try {
bt = content.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
int py = 2;// 偏移量
boolean[][] code = qrcode.calQrcode(bt);// 开始准备画图
for (int i = 0; i < code.length; i++) {
for (int j = 0; j < code.length; j++) {
if (code[j][i]) {
gs.fillRect(j * 3 + py, i * 3 + py, 3, 3);// 四个参数(画图的起始x和y位置,每个小模块的宽和高(二维码是有一个一个的小模块构成的));
}
}
}
try {
ImageIO.write(img, "png", new File(imgPath));
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("二维码异常。。。。。");
e.printStackTrace();
}
}
public void DeleteFile(String pathPng1,String pathPng2){
File file1 = new File(pathPng1);
File file2 = new File(pathPng2);
if(file1.exists()){
file1.delete();
}
if(file2.exists()){
file2.delete();
}
}
}
只有当你忍痛前行后,你猜能知道,所谓的痛不过尔尔!