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, , 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<>();
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");
}
} 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() > ) {
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"; 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().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);*/ 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();
} 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();
}
} 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. 把nginx当完全tcp端口转发器

    在nginx.conf里加入 stream {     server {         listen 18443;         proxy_pass 58.xxx.xxx.xxx:8443;   ...

  2. Grafana报警--通知渠道配置

    最近研究了prometheus+grafana的系统监控,使用grafana的报警功能,grafana支持很多种通知渠道,下文记录使用到的几种notification channels,分别是emai ...

  3. 关于新版oracle不支持wm_concat函数的解决办法

    oracle12G中不支持wm_concat,就改用:listagg(合并字段,'连接符号') within group (order by 字段) 来实现列转行

  4. 一千行ABAP代码实现Windows传统游戏扫雷

    *&---------------------------------------------------------------------* *& Report ZCHENH087 ...

  5. 如何使用wepy和 vant-weapp开发小程序

    这里记录一下  使用wepy框架和  vant-weapp库开发小程序废话 不多说 wepy文档: https://tencent.github.io/wepy/document.html#/ van ...

  6. Git命令解释

    pwd命令: Print Working Directory 显示工作目录的路径名称.

  7. Linux /etc/hosts文件

    均为转载 ———————— 1.主机名: 无论在局域网还是INTERNET上,每台主机都有一个IP地址,是为了区分此台主机和彼台主机,也就是说IP地址就是主机的门牌号. 公网:IP地址不方便记忆,所以 ...

  8. cat <<EOF

    1.cat >file记录的是键盘输入,相当于从键盘创建文件,并且只能创建新文件,不能编辑已有文件.>是数据重导向,会将你输入的文本内容输出到file中. 2.cat <<EO ...

  9. 递归可视化之汉诺塔的动画实现(turtle海龟)

    import turtle class Stack: def __init__(self): self.items = [] def isEmpty(self): def push(self, ite ...

  10. LAB6 SOAP

    有web服务的,需要Deploy一下才能跑 通过ls看所有文件的所在地,cd进入对应文件夹,才可以编译 javac 编译,Java是执行 URL必须是WSDL文件点进去里面的:http://local ...