/**
* 将后台传递回来的html代码使用pd4ml转pdf文件存放在特定的文件夹
* @param request
* @param response
* @return
* @throws Exception
*/
@RequestMapping(value="createPdf",method=RequestMethod.POST)
public void createPdf(HttpServletRequest request,HttpServletResponse response){
String html = request.getParameter("html");//获取前台body中的html内容
String name = request.getParameter("formId");//设置为pdf文件名
StringReader strReader = new StringReader(html);//
String file_separator =new Properties(System.getProperties()).getProperty("file.separator");
String paths=request.getSession().getServletContext().getRealPath("");
String pdfDir = paths+file_separator+"upload";
//String pdfDir=Global.getConfig("pdfDir");
File dir = new File(pdfDir);
if(!dir.exists()){
dir.mkdirs();
}
String path = pdfDir+file_separator+name+".pdf";
File pdfFile = new File(path);
if(pdfFile.exists() && pdfFile.isFile()){
pdfFile.delete();
}
//File pdfFile = new File("D:/test/表单测试.pdf");
FileOutputStream fos;
try {
fos = new FileOutputStream(pdfFile);
PD4ML pd4ml = new PD4ML();
pd4ml.setPageInsets(new Insets(20, 10, 10, 10));
pd4ml.setPageSize(PD4Constants.A4); //pd4ml.changePageOrientation 旋转90度
pd4ml.setHtmlWidth(800);
pd4ml.useTTF("java:fonts", true);
pd4ml.setDefaultTTFs("KaiTi_GB2312", "KaiTi_GB2312", "KaiTi_GB2312"); //中文 乱码 处理
pd4ml.enableDebugInfo();
pd4ml.render(strReader, fos);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}catch (InvalidParameterException e2) {
e2.printStackTrace();
}catch (IOException e3) {
e3.printStackTrace();
}
}
/**
* 将本地pdf文件展示在web页面
*/
@RequestMapping(value="openpdf")
public synchronized void openpdf(HttpServletRequest request,HttpServletResponse response) throws Exception{
String name = request.getParameter("formId");
String file_separator =new Properties(System.getProperties()).getProperty("file.separator");
String paths=request.getSession().getServletContext().getRealPath("");
String pdfDir = paths+file_separator+"upload";
String path = pdfDir+file_separator+name+".pdf";
File dir = new File(pdfDir);
if(!dir.exists()){
dir.mkdirs();
}
File file =new File(path);
if(!file.exists()){
return;
}
BufferedInputStream br = null;
OutputStream out = null;
try {
response.reset();
response.setContentType("application/pdf");//text/plain
response.setHeader("Content-Disposition", "inline;filename=" + name);
br = new BufferedInputStream(new FileInputStream(file));
out = response.getOutputStream();
byte[] b = new byte[1024];
int len = 0;
while ((len = br.read(b)) != -1) {
out.write(b, 0, len);
}
//TODO 延迟一百毫秒,不会write error
Thread.sleep(100);
out.flush();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} finally {
if(out != null){
out.close();
}
if(br != null){
br.close();
}
}
}