jsp 转为pdf
package com.bonc.demo.controller.scorepay;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.imageio.ImageIO;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSON;
import net.sf.json.JSONSerializer;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.IOUtils;
import org.jasig.cas.client.Client;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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 com.bonc.demo.domain.downPPT.PPTExportLog;
import com.bonc.demo.mapper.scorepay.downPPT.DownPPTMapper;
import com.bonc.security.client.SecurityRestClient;
import com.lowagie.text.Document;
import com.lowagie.text.Image;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.PdfWriter;
/**
* 整体新发展情况
*
* @author heqihui
*
*/
@Controller
@RequestMapping("/downPPT")
public class DownPPTController {
static int id = 1;
public final static String FTP_IP = "192.168.20.3";
public final static int FTP_PORT = 21;
public final static String FTP_USER = "noren";
public final static String FTP_PASSWORD = "noren.123";
public final static String FTP_PATH = "/data01/soft/noren";
@Autowired
private DownPPTMapper downPPTMapper;
private Client client;
private String export_id;
private String regionId;
private String monthId;
private String loginId;
private int imageNum = 0;
private int tempNum = 0;
@RequestMapping(value = "/downPPT")
public @ResponseBody JSON down(@RequestParam Map<String, Object> param,
Model model, HttpServletRequest request) {
id = id + 1;
// 获得数据
String pageNames = param.get("pageNames").toString();
String monthIdTemp = param.get("monthId").toString();
String monthId = param.get("monthId").toString().replace("-", "");
String regionId = param.get("regionId").toString();
String export_id = Integer.toString(id);
SecurityRestClient securityRestClient = new SecurityRestClient();
String loginId = securityRestClient.findCurrentLoginId(request);
//日期转换
Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd ");
String nowDate = dateFormat.format(date );
PPTExportLog ppt = new PPTExportLog();
ppt.setExport_id(id);
ppt.setExport_no(export_id);
ppt.setLogin_id(loginId);
ppt.setMonth_id(monthId);
ppt.setArea_no(regionId);
ppt.setExport_date(nowDate);
ppt.setExport_state("0");
ppt.setExport_name(null);
downPPTMapper.addPPTExportLog(ppt);
String pdfName = export_id + "_" + regionId + "_" + monthId + "_"+ loginId;
List<String> array = new ArrayList<String>();
array.add(pdfName);
JSON jsonArray = (JSON) JSONSerializer.toJSON(array);
return jsonArray;
}
// 生成图片
@RequestMapping(value = "/createImg")
public @ResponseBody JSON createImg(
@RequestParam Map<String, Object> param, Model model,
HttpServletRequest request, HttpServletResponse respone) {
String data = param.get("data").toString();
String fileName = param.get("ImgName").toString();
String pdfName = param.get("pdfName").toString();
/*String pdfName = export_id + "_" + regionId + "_" + monthId + "_"
+ loginId;*/
String localPath =getTmpPath()+"/"+ pdfName + "/";
boolean flag = false;
boolean pdfFlag = false;
String imgFilePath = localPath + fileName + ".jpg";
String pageNames = "begin_middle_monnewdev_middle3_newdev_end_end2";
String[] pageList = pageNames.split("_");
tempNum++;
File rootPath = new File(localPath);
if (!rootPath.exists() && !rootPath.isDirectory()) {
rootPath.mkdir();
}
Base64 base64 = new Base64();
try {
// 注意点:实际的图片数据是从 data:image/jpeg;base64, 后开始的
byte[] bytes = base64.decode(data.substring(
"data:image/jpeg;base64,".length()).getBytes());
for (int i = 0; i < bytes.length; ++i) {
if (bytes[i] < 0) {// 调整异常数据
bytes[i] += 256;
}
}
// 生成jpeg图片
OutputStream out = new FileOutputStream(imgFilePath);
out.write(bytes);
out.flush();
out.close();
imageNum++;
if ((tempNum % 7 == 0) && (imageNum % 7==0) ) {
System.out.println("=========================" + imageNum);
System.out.println("==========================createAllImg-success");
int width = 0;
int height = 0;
BufferedImage bufferedImage;
try {
bufferedImage = ImageIO.read(new File(imgFilePath));
width = bufferedImage.getWidth();
height = bufferedImage.getHeight();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Thread.sleep(500);
boolean createFlag = createPdf(localPath, pdfName + ".pdf", pageList, width, height);
if (createFlag) {
System.out.println("==========================createPdf-success");
pdfFlag = true;
}
}
} catch (Exception e) {
System.out.println("==========createImg"+fileName+" fail");
e.printStackTrace();
}
if((tempNum % 7 == 0) && (imageNum % 7==0)){
flag = true;
}else {
flag = false;
}
List<Object> array = new ArrayList<Object>();
array.add(pdfFlag);
array.add(tempNum);
array.add( pdfName);
JSON jsonArray = (JSON) JSONSerializer.toJSON(array);
if(tempNum >= 7){
tempNum = 0;
imageNum = 0;
}
return jsonArray;
}
// 生成pdf
public boolean createPdf(String path, String pdfName,
String[] pngs, int width, int height) {
System.out.println("=============path:"+path+"========pdfName:"+pdfName);
boolean createpdf = false;
try {
OutputStream file = new FileOutputStream(new File(path, pdfName));
Document document = new Document();
PdfWriter.getInstance(document, file);
document.setPageSize(new Rectangle(width, height));
document.open();
document.addAuthor("norten");
document.addCreationDate();
document.addCreator("norten");
document.addTitle(pdfName);
document.addSubject("经营日报");
document.addKeywords("内部资料 注意保密");
for (int i = 0; i < pngs.length; i++) {
String png = pngs[i];
System.out.println("--------------------------" + path
+ pngs[i] + ".jpg");
Thread.sleep(1000);
File pnfFile = new File(path + png + ".jpg");
if (pnfFile.exists()) {
System.out.println(pngs[i] + ".jpg" + " existence");
Image image = Image.getInstance(path + png + ".jpg");
image.setAbsolutePosition(0, 0);
if (i > 0) {
document.newPage();
}
document.add(image);
} else {
System.out.println(pngs[i] + ".jpg" + " not -existence");
}
}
document.close();
file.close();
createpdf = true;
} catch (Exception e) {
System.out.println("==============createPdf" + "fail");
e.printStackTrace();
}
return createpdf;
}
@RequestMapping(value = "/downLoad")
public void download(@RequestParam Map<String, Object> param, Model model,
HttpServletRequest request, HttpServletResponse respone) {
String pdfName =param.get("fileName").toString();
String localPath =getTmpPath() +"/" + pdfName + "/";
String path = localPath+pdfName+".pdf";
String export_no = pdfName.substring(0,pdfName.indexOf("_"));
HttpServletResponse response = respone;
// 1.获取File
File file = new File(path);
if(!file.exists()){
String pageNames = "begin_middle_monnewdev_middle3_newdev_end_end2";
String[] pageList = pageNames.split("_");
boolean flag= createPdf(localPath, pdfName+".pdf",pageList, 800 , 680);
}
// 2.获取outputStream
// 2.1 把文件放到buffer中(流格式)
try {
InputStream fis = new BufferedInputStream(new FileInputStream(path));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
// 2.2 初始化输出流
// 清空response
response.reset();
// 设置response的Header
response.setHeader("content-type", "application/octet-stream");
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename="
+ new String(file.getName().getBytes()));
// response.addHeader("Content-Disposition", "attachment;filename="
// + file.getName());
response.addHeader("Content-Length", "" + file.length());
OutputStream toClient = new BufferedOutputStream(
response.getOutputStream());
// response.setContentType("application/octet-stream;charset=gb2312");
// 3.输出到浏览器
toClient.write(buffer);
toClient.flush();
toClient.close();
System.out.println("===============downLoad"+path+" success");
updateState(pdfName,export_no);
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("===============downLoad"+path+" fail");
e.printStackTrace();
} finally {
File deletePath = new File(localPath);
boolean flag=deleteDir(deletePath);
}
}
//删除存放截图和pdf的目录
private boolean deleteDir(File dir) {
System.out.println("==================="+dir+" delete -start ");
if (dir.isDirectory()) {
String[] children = dir.list();
//递归删除目录中的子目录下
for (int i=0; i<children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
System.out.println("==================="+children[i]+" delete -fail ");
return false;
}else{
System.out.println("==================="+children[i]+" delete -sucess ");
}
}
}
// 目录此时为空,可以删除
return dir.delete();
}
//更新状态
public void updateState( String pdfName , String export_no){
//日期转换
Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd ");
String nowDate = dateFormat.format(date );
PPTExportLog ppt = new PPTExportLog();
ppt.setExport_id(id);
ppt.setExport_no(export_no);
ppt.setLogin_id(loginId);
ppt.setMonth_id(monthId);
ppt.setArea_no(regionId);
ppt.setExport_date(nowDate);
ppt.setExport_state("1");
ppt.setExport_name(pdfName+".pdf");
downPPTMapper.updatePPTExportLog(ppt);
}
//生成临时文件并存放
public String getTmpPath() {
String path = "/tmp";
File file = new File(path);
if (!file.exists() || file.isDirectory()) {
file.mkdir();
}
return path;
}
}
//截图
function down( pdfName ){
var name = $("#inputTitle").val();
html2canvas($("#downDiv"),{
onrendered:function(canvas){
canvas.id = canvas;
var image = canvas.toDataURL("image/jpeg");
$.ajax({
url : path()+"/downPPT/createImg",
type:"POST",
data : {"data":image,"ImgName":name,"pdfName":pdfName},
success:function(data){
if(data[0]||(data[1]%7==0)){
responseBackground(data[2]);
alert("下载成功");
}else if(!data[0] &&(data[1]%7==0) ){
alert("下载失败,请刷新页面重新下载");
}
}
})
}
});
}
package com.bonc.demo.controller.scorepay;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.imageio.ImageIO;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSON;
import net.sf.json.JSONSerializer;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.IOUtils;
import org.jasig.cas.client.Client;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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 com.bonc.demo.domain.downPPT.PPTExportLog;
import com.bonc.demo.mapper.scorepay.downPPT.DownPPTMapper;
import com.bonc.security.client.SecurityRestClient;
import com.lowagie.text.Document;
import com.lowagie.text.Image;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.PdfWriter;
/**
* 整体新发展情况
*
* @author heqihui
*
*/
@Controller
@RequestMapping("/downPPT")
public class DownPPTController {
static int id = 1;
public final static String FTP_IP = "192.168.20.3";
public final static int FTP_PORT = 21;
public final static String FTP_USER = "noren";
public final static String FTP_PASSWORD = "noren.123";
public final static String FTP_PATH = "/data01/soft/noren";
@Autowired
private DownPPTMapper downPPTMapper;
private Client client;
private String export_id;
private String regionId;
private String monthId;
private String loginId;
private int imageNum = 0;
private int tempNum = 0;
@RequestMapping(value = "/downPPT")
public @ResponseBody JSON down(@RequestParam Map<String, Object> param,
Model model, HttpServletRequest request) {
id = id + 1;
// 获得数据
String pageNames = param.get("pageNames").toString();
String monthIdTemp = param.get("monthId").toString();
String monthId = param.get("monthId").toString().replace("-", "");
String regionId = param.get("regionId").toString();
String export_id = Integer.toString(id);
SecurityRestClient securityRestClient = new SecurityRestClient();
String loginId = securityRestClient.findCurrentLoginId(request);
//日期转换
Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd ");
String nowDate = dateFormat.format(date );
PPTExportLog ppt = new PPTExportLog();
ppt.setExport_id(id);
ppt.setExport_no(export_id);
ppt.setLogin_id(loginId);
ppt.setMonth_id(monthId);
ppt.setArea_no(regionId);
ppt.setExport_date(nowDate);
ppt.setExport_state("0");
ppt.setExport_name(null);
downPPTMapper.addPPTExportLog(ppt);
String pdfName = export_id + "_" + regionId + "_" + monthId + "_"+ loginId;
List<String> array = new ArrayList<String>();
array.add(pdfName);
JSON jsonArray = (JSON) JSONSerializer.toJSON(array);
return jsonArray;
}
// 生成图片
@RequestMapping(value = "/createImg")
public @ResponseBody JSON createImg(
@RequestParam Map<String, Object> param, Model model,
HttpServletRequest request, HttpServletResponse respone) {
String data = param.get("data").toString();
String fileName = param.get("ImgName").toString();
String pdfName = param.get("pdfName").toString();
/*String pdfName = export_id + "_" + regionId + "_" + monthId + "_"
+ loginId;*/
String localPath =getTmpPath()+"/"+ pdfName + "/";
boolean flag = false;
boolean pdfFlag = false;
String imgFilePath = localPath + fileName + ".jpg";
String pageNames = "begin_middle_monnewdev_middle3_newdev_end_end2";
String[] pageList = pageNames.split("_");
tempNum++;
File rootPath = new File(localPath);
if (!rootPath.exists() && !rootPath.isDirectory()) {
rootPath.mkdir();
}
Base64 base64 = new Base64();
try {
// 注意点:实际的图片数据是从 data:image/jpeg;base64, 后开始的
byte[] bytes = base64.decode(data.substring(
"data:image/jpeg;base64,".length()).getBytes());
for (int i = 0; i < bytes.length; ++i) {
if (bytes[i] < 0) {// 调整异常数据
bytes[i] += 256;
}
}
// 生成jpeg图片
OutputStream out = new FileOutputStream(imgFilePath);
out.write(bytes);
out.flush();
out.close();
imageNum++;
if ((tempNum % 7 == 0) && (imageNum % 7==0) ) {
System.out.println("=========================" + imageNum);
System.out.println("==========================createAllImg-success");
int width = 0;
int height = 0;
BufferedImage bufferedImage;
try {
bufferedImage = ImageIO.read(new File(imgFilePath));
width = bufferedImage.getWidth();
height = bufferedImage.getHeight();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Thread.sleep(500);
boolean createFlag = createPdf(localPath, pdfName + ".pdf", pageList, width, height);
if (createFlag) {
System.out.println("==========================createPdf-success");
pdfFlag = true;
}
}
} catch (Exception e) {
System.out.println("==========createImg"+fileName+" fail");
e.printStackTrace();
}
if((tempNum % 7 == 0) && (imageNum % 7==0)){
flag = true;
}else {
flag = false;
}
List<Object> array = new ArrayList<Object>();
array.add(pdfFlag);
array.add(tempNum);
array.add( pdfName);
JSON jsonArray = (JSON) JSONSerializer.toJSON(array);
if(tempNum >= 7){
tempNum = 0;
imageNum = 0;
}
return jsonArray;
}
// 生成pdf
public boolean createPdf(String path, String pdfName,
String[] pngs, int width, int height) {
System.out.println("=============path:"+path+"========pdfName:"+pdfName);
boolean createpdf = false;
try {
OutputStream file = new FileOutputStream(new File(path, pdfName));
Document document = new Document();
PdfWriter.getInstance(document, file);
document.setPageSize(new Rectangle(width, height));
document.open();
document.addAuthor("norten");
document.addCreationDate();
document.addCreator("norten");
document.addTitle(pdfName);
document.addSubject("经营日报");
document.addKeywords("内部资料 注意保密");
for (int i = 0; i < pngs.length; i++) {
String png = pngs[i];
System.out.println("--------------------------" + path
+ pngs[i] + ".jpg");
Thread.sleep(1000);
File pnfFile = new File(path + png + ".jpg");
if (pnfFile.exists()) {
System.out.println(pngs[i] + ".jpg" + " existence");
Image image = Image.getInstance(path + png + ".jpg");
image.setAbsolutePosition(0, 0);
if (i > 0) {
document.newPage();
}
document.add(image);
} else {
System.out.println(pngs[i] + ".jpg" + " not -existence");
}
}
document.close();
file.close();
createpdf = true;
} catch (Exception e) {
System.out.println("==============createPdf" + "fail");
e.printStackTrace();
}
return createpdf;
}
@RequestMapping(value = "/downLoad")
public void download(@RequestParam Map<String, Object> param, Model model,
HttpServletRequest request, HttpServletResponse respone) {
String pdfName =param.get("fileName").toString();
String localPath =getTmpPath() +"/" + pdfName + "/";
String path = localPath+pdfName+".pdf";
String export_no = pdfName.substring(0,pdfName.indexOf("_"));
HttpServletResponse response = respone;
// 1.获取File
File file = new File(path);
if(!file.exists()){
String pageNames = "begin_middle_monnewdev_middle3_newdev_end_end2";
String[] pageList = pageNames.split("_");
boolean flag= createPdf(localPath, pdfName+".pdf",pageList, 800 , 680);
}
// 2.获取outputStream
// 2.1 把文件放到buffer中(流格式)
try {
InputStream fis = new BufferedInputStream(new FileInputStream(path));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
// 2.2 初始化输出流
// 清空response
response.reset();
// 设置response的Header
response.setHeader("content-type", "application/octet-stream");
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename="
+ new String(file.getName().getBytes()));
// response.addHeader("Content-Disposition", "attachment;filename="
// + file.getName());
response.addHeader("Content-Length", "" + file.length());
OutputStream toClient = new BufferedOutputStream(
response.getOutputStream());
// response.setContentType("application/octet-stream;charset=gb2312");
// 3.输出到浏览器
toClient.write(buffer);
toClient.flush();
toClient.close();
System.out.println("===============downLoad"+path+" success");
updateState(pdfName,export_no);
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("===============downLoad"+path+" fail");
e.printStackTrace();
} finally {
File deletePath = new File(localPath);
boolean flag=deleteDir(deletePath);
}
}
//删除存放截图和pdf的目录
private boolean deleteDir(File dir) {
System.out.println("==================="+dir+" delete -start ");
if (dir.isDirectory()) {
String[] children = dir.list();
//递归删除目录中的子目录下
for (int i=0; i<children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
System.out.println("==================="+children[i]+" delete -fail ");
return false;
}else{
System.out.println("==================="+children[i]+" delete -sucess ");
}
}
}
// 目录此时为空,可以删除
return dir.delete();
}
//更新状态
public void updateState( String pdfName , String export_no){
//日期转换
Date date = new Date();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd ");
String nowDate = dateFormat.format(date );
PPTExportLog ppt = new PPTExportLog();
ppt.setExport_id(id);
ppt.setExport_no(export_no);
ppt.setLogin_id(loginId);
ppt.setMonth_id(monthId);
ppt.setArea_no(regionId);
ppt.setExport_date(nowDate);
ppt.setExport_state("1");
ppt.setExport_name(pdfName+".pdf");
downPPTMapper.updatePPTExportLog(ppt);
}
//生成临时文件并存放
public String getTmpPath() {
String path = "/tmp";
File file = new File(path);
if (!file.exists() || file.isDirectory()) {
file.mkdir();
}
return path;
}
}
//截图
function down( pdfName ){
var name = $("#inputTitle").val();
html2canvas($("#downDiv"),{
onrendered:function(canvas){
canvas.id = canvas;
var image = canvas.toDataURL("image/jpeg");
$.ajax({
url : path()+"/downPPT/createImg",
type:"POST",
data : {"data":image,"ImgName":name,"pdfName":pdfName},
success:function(data){
if(data[0]||(data[1]%7==0)){
responseBackground(data[2]);
alert("下载成功");
}else if(!data[0] &&(data[1]%7==0) ){
alert("下载失败,请刷新页面重新下载");
}
}
})
}
});
}