1. import com.alibaba.fastjson.JSONObject;
  2. import com.aliyun.oss.OSSClient;
  3. import com.itextpdf.text.pdf.*;
  4. import com.swetake.util.Qrcode;
  5. import com.titifootball.common.base.BaseController;
  6. import com.titifootball.presentation.common.constant.PresentationConstants;
  7. import com.titifootball.presentation.dao.model.*;
  8. import com.titifootball.presentation.rpc.api.UresultAttributeService;
  9. import com.titifootball.presentation.rpc.api.UresultPresentationService;
  10. import com.titifootball.presentation.rpc.api.UresultTypeService;
  11. import io.swagger.annotations.ApiOperation;
  12. import org.apache.batik.transcoder.TranscoderException;
  13. import org.apache.batik.transcoder.TranscoderInput;
  14. import org.apache.batik.transcoder.TranscoderOutput;
  15. import org.apache.batik.transcoder.image.JPEGTranscoder;
  16. import org.apache.http.HttpEntity;
  17. import org.apache.http.client.methods.CloseableHttpResponse;
  18. import org.apache.http.client.methods.HttpGet;
  19. import org.apache.http.impl.client.CloseableHttpClient;
  20. import org.apache.http.impl.client.HttpClientBuilder;
  21. import org.slf4j.Logger;
  22. import org.slf4j.LoggerFactory;
  23. import org.springframework.beans.factory.annotation.Autowired;
  24. import org.springframework.stereotype.Controller;
  25. import org.springframework.web.bind.annotation.RequestMapping;
  26. import org.springframework.web.bind.annotation.RequestMethod;
  27. import org.springframework.web.bind.annotation.RequestParam;
  28. import org.springframework.web.bind.annotation.ResponseBody;
  29. import org.springframework.web.context.request.RequestContextHolder;
  30. import org.springframework.web.context.request.ServletRequestAttributes;
  31.  
  32. import javax.imageio.ImageIO;
  33. import javax.servlet.http.HttpServletRequest;
  34. import javax.servlet.http.HttpSession;
  35. import java.awt.*;
  36. import java.awt.image.BufferedImage;
  37. import java.io.*;
  38. import java.net.MalformedURLException;
  39. import java.net.URI;
  40. import java.net.URL;
  41. import java.text.SimpleDateFormat;
  42. import java.util.*;
  43. import java.util.List;
  44.  
  45. /**
  46. * PdfExportController
  47. * @author jianhun
  48. * @date 2018/08/29
  49. */
  50.  
  51. @Controller
  52. @RequestMapping("/manage/pdf/v1")
  53. public class PlayerReportExportController extends BaseController {
  54. private final String TEAM_PLAYER_URL="http://localhost:6664/api/v1/upms/team/player/list?teamIds=*";
  55. private final String PLAYER_URL="http://localhost:6664/api/v1/upms/player/list?playerIds=*";
  56. private static final Logger LOGGER = LoggerFactory.getLogger(PlayerReportExportController.class);
  57.  
  58. @Autowired
  59. private UresultPresentationService uresultPresentationService;
  60. @Autowired
  61. private UresultAttributeService uresultAttributeService;
  62.  
  63. @Autowired
  64. private UresultTypeService uresultTypeService;
  65.  
  66. @Autowired
  67. HttpServletRequest request;
  68.  
  69. String SvgPngPath = "";
  70. String Path = "";
  71.  
  72. @RequestMapping(value = "/index", method = RequestMethod.GET)
  73. public String index() {
  74.  
  75. return "/manage/PDF/index.jsp";
  76. }
  77. @ApiOperation(value = "Svg转Png")
  78. @RequestMapping(value = "/svgPng", method = RequestMethod.POST)
  79. @ResponseBody
  80. public Map svgPng(@RequestParam(value = "svg") String svg) throws Exception {
  81. Map resultMap=new HashMap();
  82. Boolean flag=false;
  83. String msg="";
  84. flag=true;
  85. resultMap.put("flag",flag);
  86. resultMap.put("message",msg);
  87. SvgPng(svg);
  88. return resultMap;
  89. }
  90.  
  91. public void SvgPng(String svg) throws Exception {
  92. String pathSvg = request.getSession().getServletContext().getRealPath( "/")+"\\pdf\\"+"img\\" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+"Radar"+ ".svg";
  93. String pathPng = request.getSession().getServletContext().getRealPath( "/")+"\\pdf\\"+"img\\" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+"Radar"+ ".png";
  94. FileWriter fw = null;
  95. File f = new File(pathSvg);
  96. try {
  97. if (!f.exists()) {
  98. f.createNewFile();
  99. }
  100. fw = new FileWriter(f);
  101. BufferedWriter out = new BufferedWriter(fw);
  102. out.write(svg, 0, svg.length());
  103. out.close();
  104.  
  105. } catch (IOException e) {
  106. e.printStackTrace();
  107. }
  108. changeSvgToJpg(pathPng, pathSvg);
  109. }
  110. private void changeSvgToJpg(String pistrPngFile, String pistrSvgPath) {
  111. Date date = new Date();
  112. long timeBegin = date.getTime();
  113. String strSvgURI;// svg文件路径
  114. OutputStream ostream = null;
  115. File fileSvg = null;
  116. try {
  117. fileSvg = new File(pistrSvgPath);
  118. URI uri = fileSvg.toURI();// 构造一个表示此抽象路径名的 file:URI
  119. URL url = uri.toURL();// 根据此 URI 构造一个 URL
  120. strSvgURI = url.toString();
  121. TranscoderInput input = new TranscoderInput(strSvgURI);// 定义一个通用的转码器的输入
  122.  
  123. ostream = new FileOutputStream(pistrPngFile);
  124. TranscoderOutput output = new TranscoderOutput(ostream);// 定义单路输出的转码器
  125. JPEGTranscoder transcoder = new JPEGTranscoder();// 构造一个新的转码器,产生JPEG图像
  126. transcoder.addTranscodingHint(JPEGTranscoder.KEY_QUALITY, new Float(0.8));// 设置一个转码过程,JPEGTranscoder.KEY_QUALITY设置输出png的画质精度,0-1之间
  127. transcoder.transcode(input, output);// 转换svg文件为png
  128. } catch (MalformedURLException e) {
  129. e.printStackTrace();
  130. } catch (FileNotFoundException e) {
  131. e.printStackTrace();
  132. } catch (TranscoderException e) {
  133. e.printStackTrace();
  134. } finally {
  135. try {
  136. ostream.flush();
  137. ostream.close();
  138. } catch (IOException e) {
  139. e.printStackTrace();
  140. }
  141. }
  142. request.getSession().setAttribute("png",pistrPngFile);
  143.  
  144. fileSvg.delete();// 删除svg文件
  145.  
  146. }
  147.  
  148. @RequestMapping(value = "/exportPdf", method = RequestMethod.GET)
  149. @ResponseBody
  150. public Map exportPdf(@RequestParam(value = "assessPlayerId") Long assessPlayerId, HttpServletRequest request) throws Exception {
  151. Map resultMap=new HashMap();
  152. Boolean flag=false;
  153. String msg="";
  154. Map<String, String> reportData = new HashMap<>(16);
  155. Long teamId=0L;
  156. Long playerId=0L;
  157. try {
  158. HttpGet requestTeamPlayer = new HttpGet(TEAM_PLAYER_URL.replace("*",assessPlayerId.toString()));
  159. CloseableHttpResponse response = null;
  160. CloseableHttpClient httpClient = HttpClientBuilder.create().build();
  161. response = httpClient.execute(requestTeamPlayer);//执行HttpGet请求
  162. HttpEntity httpEntity = response.getEntity();//获得实体
  163. if (httpEntity != null) {
  164. InputStream instreams = httpEntity.getContent();
  165. JSONObject jsonObject=JSONObject.parseObject(convertStreamToString(instreams));
  166. if(jsonObject.getInteger("code")==1){
  167. teamId=jsonObject.getJSONArray("data").getJSONObject(0).getLong("teamId");
  168. playerId=jsonObject.getJSONArray("data").getJSONObject(0).getLong("playerId");
  169. }
  170. }
  171.  
  172. String basePath = request.getSession().getServletContext().getRealPath( "/")+"\\pdf\\";
  173. String basePathImg = request.getSession().getServletContext().getRealPath( "/")+"\\pdf\\"+"img\\" + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+ ".png";
  174. HttpSession session= ((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getRequest().getSession();
  175. getQrCodeImg("titifootball.com",basePathImg);
  176. Date date = new Date();
  177. SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd");
  178. String time = sdf.format(date);
  179.  
  180. reportData.put("reportDate",time);
  181. reportData.put("reportDate1",time);
  182. reportData.put("reportDate2",time);
  183. reportData.put("reportDate3",time);
  184. reportData.put("reportDate4",time);
  185. reportData.put("reportDate5",time);
  186. reportData.put("qrcode",basePathImg);
  187. reportData.put("qrcode2",basePathImg);
  188. reportData.put("qrcode3",basePathImg);
  189. reportData.put("qrcode4",basePathImg);
  190. reportData.put("qrcode5",basePathImg);
  191. reportData.put("qrcode6",basePathImg);
  192. reportData.put("PI15","D:\\A.jpeg");
  193. reportData.put("Radarchart",(String) session.getAttribute("png"));
  194. System.out.println(reportData);
  195. List<Long> uresultTypeIdList = new ArrayList<>();
  196. UresultTypeExample uresultTypeExample = new UresultTypeExample();
  197. uresultTypeExample.createCriteria()
  198. .andIsDeletedEqualTo(PresentationConstants.NO);
  199. uresultTypeExample.setOrderByClause("id desc");
  200. List<UresultType> uresultTypeList = uresultTypeService.selectByExample(uresultTypeExample);
  201. if(null != uresultTypeList && uresultTypeList.size() > 0) {
  202. for(UresultType uresultType : uresultTypeList) {
  203. uresultTypeIdList.add(uresultType.getId());
  204. }
  205. UresultPresentationExample uresultPresentationExample = new UresultPresentationExample();
  206. uresultPresentationExample.createCriteria()
  207. .andIsDeletedEqualTo(PresentationConstants.NO)
  208. .andAssessmentIdEqualTo(1L)
  209. .andAssessPlayerIdEqualTo(assessPlayerId)
  210. .andTypeIn(uresultTypeIdList)
  211. .andStateEqualTo(PresentationConstants.YES);
  212. uresultPresentationExample.setOrderByClause("id asc");
  213. List<UresultPresentationDetail> uresultPresentationDetailList =
  214. uresultPresentationService.selectUresultPresentationDetailByExampleForOffsetPage(
  215. uresultPresentationExample, 0, 10000);
  216. for(UresultPresentationDetail uresultPresentationDetail : uresultPresentationDetailList) {
  217. UresultAttribute uresultAttribute=uresultPresentationDetail.getUresultAttribute();
  218. if(null!=uresultAttribute){
  219. String key = uresultPresentationDetail.getUresultAttribute().getCode();
  220. String value = uresultPresentationDetail.getAttrValue();
  221. if (null!=value){
  222. value+=" "+(null!=uresultPresentationDetail.getUresultAttribute().getUnit()?uresultPresentationDetail.getUresultAttribute().getUnit():"");
  223. }
  224. reportData.put(key, value);
  225. }
  226. }
  227. }
  228. String Name = "1";
  229. String identification = "2";
  230.  
  231. for (String key : reportData.keySet()) {
  232. Path = reportData.get("qrcode");
  233. SvgPngPath = reportData.get("Radarchart");
  234. Name = reportData.get("PI06");
  235. identification = reportData.get("PI12");
  236. }
  237. String newPdfName= /*Name+"-"+identification+*/"1.pdf";
  238. reportData=generalPdf(basePath+"template/pdf-template.pdf",basePath+"data/"+newPdfName,reportData);
  239.  
  240. 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);
  241. String fileUrl="http://"+ com.titifootball.presentation.web.PresentationConstants.ALIYUN_OSS_BUCKNAME+"."+ com.titifootball.presentation.web.PresentationConstants.ALIYUN_OSS_ENDPOINT+"/user-report/"+newPdfName;
  242. client.putObject(com.titifootball.presentation.web.PresentationConstants.ALIYUN_OSS_BUCKNAME, "user-report/"+newPdfName, new File(basePath+"data/"+newPdfName));
  243. client.shutdown();
  244. File pdfFile=new File(basePath+"data/"+newPdfName);
  245. if (pdfFile.exists()){
  246. pdfFile.deleteOnExit();
  247. }
  248. reportData.put("url",fileUrl);
  249. DeleteFile(SvgPngPath,Path);
  250. return reportData;
  251. }catch (Exception e){
  252. e.printStackTrace();
  253. msg=e.getLocalizedMessage();
  254. }
  255. resultMap.put("flag",flag);
  256. resultMap.put("message",msg);
  257. return resultMap;
  258. }
  259. public Map generalPdf(String templatePath,String newPdfPath,Map reportData){
  260. Map resultMap=new HashMap();
  261. Boolean flag=false;
  262. String msg="";
  263. PdfReader reader;
  264. FileOutputStream out;
  265. ByteArrayOutputStream bos;
  266. PdfStamper stamper;
  267. PdfImportedPage importedPage;
  268. try {
  269. out=new FileOutputStream(newPdfPath);
  270. reader=new PdfReader(templatePath);
  271. bos=new ByteArrayOutputStream();
  272. stamper=new PdfStamper(reader,bos);
  273. AcroFields form=stamper.getAcroFields();
  274. Iterator<String> iterator=form.getFields().keySet().iterator();
  275.  
  276. while (iterator.hasNext()){
  277. String name=iterator.next().toString();
  278. String value=(!reportData.containsKey(name))?"-":reportData.get(name).toString();
  279. System.out.println(name+"<------->"+value);
  280. form.setField(name,value);
  281. 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))){
  282. String imgpath = reportData.get(name).toString();
  283. System.out.println(form.getFieldPositions(name));
  284. int pageNo = form.getFieldPositions(name).get(0).page;
  285. System.out.println(pageNo);
  286. com.itextpdf.text.Rectangle Rectangle = form.getFieldPositions(name).get(0).position;
  287. float x = Rectangle.getLeft();
  288. float y = Rectangle.getBottom();
  289. float width = Rectangle.getWidth();
  290. float height = Rectangle.getHeight();
  291. // 读图片
  292. com.itextpdf.text.Image image = com.itextpdf.text.Image.getInstance(imgpath);
  293. // 获取操作的页面
  294. PdfContentByte pdfContentByte = stamper.getOverContent(pageNo);
  295. // 根据域的大小缩放图片
  296. image.scaleToFit(width, height);
  297. // 添加图片
  298. image.setAbsolutePosition(x, y);
  299. pdfContentByte.addImage(image);
  300. }
  301. }
  302. stamper.setFormFlattening(true);
  303. stamper.close();
  304. com.itextpdf.text.Document doc=new com.itextpdf.text.Document();
  305. PdfWriter pdfWriter = PdfWriter.getInstance(doc,bos);
  306. // 设置用户密码, 所有者密码,用户权限,所有者权限
  307. pdfWriter.setEncryption("123456".getBytes(), "123456".getBytes(), PdfWriter.ALLOW_COPY, PdfWriter.ENCRYPTION_AES_128);
  308.  
  309. PdfCopy copy=new PdfCopy(doc,out);
  310. doc.open();
  311. for (Integer i=1;i<=7;i++){
  312. importedPage=copy.getImportedPage(new PdfReader(bos.toByteArray()),i);
  313. copy.addPage(importedPage);
  314. }
  315. doc.close();
  316. flag=true;
  317. }catch (Exception e){
  318. e.printStackTrace();
  319. msg=e.getLocalizedMessage();
  320. }
  321. resultMap.put("flag",flag);
  322. resultMap.put("message",msg);
  323. return resultMap;
  324. }
  325. public static String convertStreamToString(InputStream is){
  326. BufferedReader reader = new BufferedReader(new InputStreamReader(is));
  327. StringBuilder sb = new StringBuilder();
  328. String line = null;
  329. try {
  330. while ((line = reader.readLine()) != null) {
  331. sb.append(line + "\n");
  332. }
  333. } catch (IOException e) {
  334. System.out.println("Error=" + e.toString());
  335. } finally {
  336. try {
  337. is.close();
  338. } catch (IOException e) {
  339. System.out.println("Error=" + e.toString());
  340. }
  341. }
  342. return sb.toString();
  343. }
  344.  
  345. public static void getQrCodeImg(String content, String imgPath) {
  346. int width = 80;// 图片宽
  347. int height =80;// 图片高
  348. Qrcode qrcode = new Qrcode();// 实例化一个qrcode对象
  349. qrcode.setQrcodeErrorCorrect('M');// 设置纠错级别(级别有:L(7%) M(15%) Q(25%) H(30%) )
  350. qrcode.setQrcodeEncodeMode('B');// 设置编码方式
  351. qrcode.setQrcodeVersion(7);// 设置二维码版本(版本有 1-40个,)
  352. BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);// 开始绘制图片start 1.设置图片大小(BufferedImage.TYPE_INT_RGB:利用三原色绘制二维码)
  353. Graphics2D gs = img.createGraphics();// 获取绘图工具start
  354. gs.setBackground(Color.WHITE);// 设置背景为白色
  355. gs.clearRect(0, 0, width, height);// 设置一个矩形(四个参数分别为:开始绘图的x坐标,y坐标,图片宽,图片高)
  356. gs.setColor(Color.black);// 设置二维码图片的颜色
  357. byte[] bt = null;
  358. try {
  359. bt = content.getBytes("UTF-8");
  360. } catch (UnsupportedEncodingException e) {
  361. e.printStackTrace();
  362. }
  363. int py = 2;// 偏移量
  364. boolean[][] code = qrcode.calQrcode(bt);// 开始准备画图
  365. for (int i = 0; i < code.length; i++) {
  366. for (int j = 0; j < code.length; j++) {
  367. if (code[j][i]) {
  368. gs.fillRect(j * 3 + py, i * 3 + py, 3, 3);// 四个参数(画图的起始x和y位置,每个小模块的宽和高(二维码是有一个一个的小模块构成的));
  369. }
  370. }
  371. }
  372. try {
  373. ImageIO.write(img, "png", new File(imgPath));
  374. } catch (IOException e) {
  375. // TODO Auto-generated catch block
  376. System.out.println("二维码异常。。。。。");
  377. e.printStackTrace();
  378. }
  379. }
  380.  
  381. public void DeleteFile(String pathPng1,String pathPng2){
  382. File file1 = new File(pathPng1);
  383. File file2 = new File(pathPng2);
  384. if(file1.exists()){
  385. file1.delete();
  386. }
  387. if(file2.exists()){
  388. file2.delete();
  389. }
  390. }
  391. }
  1. package com.titifootball.presentation.web.controller;
  2.  
  3. 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;
  4.  
  5. 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;
  6.  
  7. /**
    * PdfExportController
    * @author jianhun
    * @date 2018/08/29
    */
  8.  
  9. @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);
  10.  
  11. @Autowired
    private UresultPresentationService uresultPresentationService;
    @Autowired
    private UresultAttributeService uresultAttributeService;
  12.  
  13. @Autowired
    private UresultTypeService uresultTypeService;
  14.  
  15. @Autowired
    HttpServletRequest request;
  16.  
  17. String SvgPngPath = "";
    String Path = "";
  18.  
  19. @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index() {
  20.  
  21. 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;
    }
  22.  
  23. 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, , svg.length());
    out.close();
  24.  
  25. } 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);// 定义一个通用的转码器的输入
  26.  
  27. 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);
  28.  
  29. fileSvg.delete();// 删除svg文件
  30.  
  31. }
  32.  
  33. @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<>();
    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")==){
    teamId=jsonObject.getJSONArray("data").getJSONObject().getLong("teamId");
    playerId=jsonObject.getJSONArray("data").getJSONObject().getLong("playerId");
    }
    }
  34.  
  35. 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);
  36.  
  37. 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() > ) {
    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, , );
    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";
  38.  
  39. 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);
  40.  
  41. 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();
  42.  
  43. 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().page;
    System.out.println(pageNo);
    com.itextpdf.text.Rectangle Rectangle = form.getFieldPositions(name).get().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);*/
  44.  
  45. PdfCopy copy=new PdfCopy(doc,out);
    doc.open();
    for (Integer i=;i<=;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();
    }
  46.  
  47. public static void getQrCodeImg(String content, String imgPath) {
    int width = ;// 图片宽
    int height =;// 图片高
    Qrcode qrcode = new Qrcode();// 实例化一个qrcode对象
    qrcode.setQrcodeErrorCorrect('M');// 设置纠错级别(级别有:L(7%) M(15%) Q(25%) H(30%) )
    qrcode.setQrcodeEncodeMode('B');// 设置编码方式
    qrcode.setQrcodeVersion();// 设置二维码版本(版本有 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(, , width, height);// 设置一个矩形(四个参数分别为:开始绘图的x坐标,y坐标,图片宽,图片高)
    gs.setColor(Color.black);// 设置二维码图片的颜色
    byte[] bt = null;
    try {
    bt = content.getBytes("UTF-8");
    } catch (UnsupportedEncodingException e) {
    e.printStackTrace();
    }
    int py = ;// 偏移量
    boolean[][] code = qrcode.calQrcode(bt);// 开始准备画图
    for (int i = ; i < code.length; i++) {
    for (int j = ; j < code.length; j++) {
    if (code[j][i]) {
    gs.fillRect(j * 3 + py, i * 3 + py, , );// 四个参数(画图的起始x和y位置,每个小模块的宽和高(二维码是有一个一个的小模块构成的));
    }
    }
    }
    try {
    ImageIO.write(img, "png", new File(imgPath));
    } catch (IOException e) {
    // TODO Auto-generated catch block
    System.out.println("二维码异常。。。。。");
    e.printStackTrace();
    }
    }
  48.  
  49. 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();
    }
    }
    }

关于根据模板生成pdf文档,差入图片和加密的更多相关文章

  1. JAVA使用itext根据模板生成PDF文档

    1.制作PDF模板 网址打开:https://www.pdfescape.com/open/ 我们这里先在线上把基础的内容用word文档做好,然后转成PDF模板,直接上传到网站上,这样方便点 假设我们 ...

  2. Spring Boot集成JasperReports生成PDF文档

    由于工作需要,要实现后端根据模板动态填充数据生成PDF文档,通过技术选型,使用Ireport5.6来设计模板,结合JasperReports5.6工具库来调用渲染生成PDF文档.本人文采欠缺,写作能力 ...

  3. 利用Java动态生成 PDF 文档

    利用Java动态生成 PDF 文档,则需要开源的API.首先我们先想象需求,在企业应用中,客户会提出一些复杂的需求,比如会针对具体的业务,构建比较典型的具备文档性质的内容,一般会导出PDF进行存档.那 ...

  4. 手把手教你使用 Java 在线生成 pdf 文档

    一.介绍 在实际的业务开发的时候,研发人员往往会碰到很多这样的一些场景,需要提供相关的电子凭证信息给用户,例如网银/支付宝/微信购物支付的电子发票.订单的库存打印单.各种电子签署合同等等,以方便用户查 ...

  5. Aspose.Words操作word生成PDF文档

    Aspose.Words操作word生成PDF文档 using Aspose.Words; using System; using System.Collections.Generic; using ...

  6. 如何从Windows Phone 生成PDF文档

    我需要从我的Windows Phone应用程序生成PDF. 遗憾的是没有标准的免费的PDF生成库在Windows Phone上运行. 我不得不自己生成PDF,通过直接写入到文件格式. 这竟然是真的很容 ...

  7. 使用PHP生成PDF文档

    原文:使用PHP生成PDF文档 实际工作中,我们要使用PHP动态的创建PDF文档,目前有许多开源的PHP创建PDF的类库,今天我给大家来介绍一款优秀的PDF库,它就是TCPDF,TCPDF是一个用于快 ...

  8. DocFX生成PDF文档

    使用DocFX生成PDF文档,将在线文档转换为PDF离线文档. 关于DocFX的简单介绍使用DocFX生成文档 使用docfx 命令 1.下载 https://github.com/dotnet/do ...

  9. qt 利用 HTML 生成PDF文档,不能显示jpg图片

    利用 QPrinter 和html 生成 pdf文档 其中用html语句有显示图片的语句 但只能显示png格式的图片,不能显示jpg格式图片. 经过排查:语法,文件路径等都正确,最终在stack ov ...

随机推荐

  1. find、which、whereis、locate和type之间的区别

    1.find find是最常用和最强大的查找命令.它能做到实时查找,精确查找,但速度慢. find的使用格式如下: #find [指定目录] [指定条件] [指定动作] 指定目录:是指所要搜索的目录和 ...

  2. matplotlib绘图基本用法-转自(http://blog.csdn.net/mao19931004/article/details/51915016)

    本文转载自http://blog.csdn.net/mao19931004/article/details/51915016 <!DOCTYPE html PUBLIC "-//W3C ...

  3. 解决IIS配置问题

    解决网站运行一段时间会变慢的问题 http://blog.csdn.net/rryqsh/article/details/8156558 1. IIS 7 应用程序池自动回收关闭的解决方案 如果你正在 ...

  4. Windows下javac不可用,java -version可以

    https://blog.csdn.net/kobedir/article/details/79709287

  5. tesseract的编译安装

    需要安装: <span style="font-family:'Microsoft YaHei';font-size:14px;">apt-get install au ...

  6. .NET Core 跨平台发布Linux和OSX

    跨平台发布 简单新建一个项目. mkdir dotnethello cd dotnethello dotnet new dotnet new之后 修改project.json 如下: { " ...

  7. redis 开机启动

    使用chkconfig开机启动redis. 把redis初始脚本拷贝到/etc/init.d/下面. #cd /usr/local/redis/redis-2.6.16/utils # cp redi ...

  8. Selenium+TestNG+Maven(2)

    转载自http://www.cnblogs.com/hustar0102/p/5885115.html selenium介绍和环境搭建 一.简单介绍 1.selenium:Selenium是一个用于W ...

  9. spring mvc 参数绑定

    基础类型 原始类型:id必须要传,否则报错. @RequestMapping("/test") @ResponseBody public ResponseData test(int ...

  10. Failed to execute goal org.apache.maven.plugins:maven-clean-plugin:2.4.1:clean (default-clean) on project

    在maven项目中 启动了2个tomcat,只能启动一个.