有时候项目需要导出pdf并且打成压缩包,这是运用框架的功能可能很难做到,上网找到了一种方式:生成html再转为pdf,下面是我写的例子:
生成html:
package cn.zgjkw.hm.util;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import cn.zgjkw.hm.model.Pecsection;
import cn.zgjkw.hm.model.PscuWithBLOBs;
import cn.zgjkw.hm.model.Pscuitem;
public class ExportHtml {
private static String getDate() {
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
Date date=new Date();
return sdf.format(date);
}
private static String getDate(Date date) {
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
return sdf.format(date);
}
public static String exportHtml(String path,PscuWithBLOBs pscu,List<Pecsection> sections,List<Pscuitem> psitems) throws UnsupportedEncodingException, IOException {
String date=getDate(pscu.getCudate());
String fidate="-";
if(pscu.getFidate()==null){
}else{
fidate=getDate(pscu.getFidate());
}
File dir=new File(path+"\\"+pscu.getPsid());
File file=new File(path+"\\"+pscu.getPsid()+"\\"+pscu.getId()+date+".html");
if(!dir.exists()){
dir.mkdir();
System.out.println(dir.exists());
}
if(!file.exists()){
file.createNewFile();
}else{
}
PrintStream printStream = new PrintStream(new FileOutputStream(file));
StringBuffer sb=new StringBuffer();
sb.append("<html>");
sb.append("<head>");
sb.append("<title>个人健康档案</title>");
sb.append("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />");
sb.append("<style type=\"text/css\">");
sb.append("body { font-family: SimSun; font-size:10px;font-style:italic;font-weight:bold;color:#00F;}");
sb.append(".titleBar {width:99%; align:center; border-collapse: collapse; }");
sb.append(".titleBar td { color:#026aa2;font-size:14px; font-weight:bold; text-align:center; height:35px; line-height:35px; vertical-align:middle;}");
sb.append(".tbl_detail {width:99%; align:center; border-collapse: collapse; border: 1px solid #68c8ed}");
sb.append(".tbl_detail tr {height:30px; line-height:30px; vertical-align:middle; color:#0876b2; padding:0;}");
sb.append(".tbl_detail td {color:#303030; line-height:28px;}");
sb.append(".tbl_detail input { width:150px; height:20px; line-height:20px; vertical-align:middle; text-align:left; text-indent:3px; border:1px solid #a2c8ed; margin-left:3px; color:#9A9A9A;}");
sb.append(".tbl_detail textarea { width:500px; height:100px; text-align:left; text-indent:3px; margin-left:3px;border:1px solid #68c8ed; margin:5px 0px 5px 3px;}");
sb.append(".tbl_detail .trodd { background:#eaf3f7; }");
sb.append(".tbl_detail .trodd td { background:#ffffff;}");
sb.append(".tbl_detail .treven { background:#e4f2f8; }");
sb.append(".tbl_detail .treven td { background:#eaf3f7;}");
sb.append(".tbl_detail .tdodd {text-align: left;}");
sb.append(".tbl_detail .tdeven {text-align: right;}");
sb.append(".tbl_detail .select{width: 150px;}");
sb.append(".tbl_detail .radio{width: 15px;border: none;}");
sb.append(".tbl_list {width:99%; border-collapse: collapse; }");//align:center;
sb.append(".tbl_list tr { line-height:30px; color:#0876b2; background-image: url(/hm/static/images/main3_tab.jpg); background-repeat: repeat-x; padding:0;}");//height:30px;vertical-align:middle;
sb.append(".tbl_list td {border: 1px solid #9bdbf3; border-spacing: 1px; text-align:center; color:#303030; line-height:28px;}");
sb.append(".tbl_list th {color:#0776b2; border: 1px solid #9bdbf3; border-spacing: 1px;}");
sb.append(".tbl_list tr td a, a:hover { text-decoration:none;}");
sb.append(".tbl_list .trodd { background:#eaf3f7; }");
sb.append(".tbl_list .trodd td { background:#ffffff;}");
sb.append(".tbl_list .treven { background:#e4f2f8;}");
sb.append(".tbl_list .treven td { background:#eaf3f7;}");
sb.append(".opBar {width:99%; align:center; border-collapse: collapse; }");
sb.append(".opBar td {align:center; height:45;}");
sb.append(".opBar input, .opInput {width:68px; height:25px; line-height:25px;vertical-align:middle; _padding-top:10px; text-align:center; background-repeat: no-repeat; color:#fff; cursor:pointer; border:0;background-image:url(/hm/static/images/menu3_button1.png);}");
sb.append("</style>");
sb.append("</head>");
sb.append("<body>");
sb.append("<div id=\"editDIV\">");
sb.append("<table class=\"titleBar\">");
sb.append("<tr><td>体检报告</td></tr></table>");
sb.append("<table class=\"tbl_detail\"><tr>");
sb.append("<th>项目</th><th>数值</th><th>项目</th><th>数值</th></tr>");
sb.append("<tr><td>体检记录ID:</td><td>"+pscu.getId()+"</td><td>记录ID:</td><td>"+NullUtil.getValue(pscu.getRid())+"</td></tr>");
sb.append("<tr><td>个人ID:</td><td>"+NullUtil.getValue(pscu.getPsid())+"</td><td>体检中心:</td><td></td></tr>");
sb.append("<tr><td>体检编号:</td><td>"+NullUtil.getValue(pscu.getSn())+"</td><td>体检卡号:</td><td>"+NullUtil.getValue(pscu.getCn())+"</td></tr>");
sb.append("<tr><td>年龄:</td><td>"+NullUtil.getValue(pscu.getAge())+"</td><td>附加年龄:</td><td>"+NullUtil.getValue(pscu.getAge2())+"</td></tr>");
sb.append("<tr><td>体检日期:</td><td>"+date+"</td><td>医院编号:</td><td>"+NullUtil.getValue(pscu.getHid())+"</td></tr>");
sb.append("<tr><td>单位编号:</td><td>"+NullUtil.getValue(pscu.getCid())+"</td><td>群体编号:</td><td>"+NullUtil.getValue(pscu.getGid())+"</td></tr>");
sb.append("<tr><td>总检标志:</td><td>"+NullUtil.getValue(pscu.getFiflag())+"</td><td></td><td></td></tr>");
sb.append("<tr><td>总检日期:</td><td>"+fidate+"</td><td>总检医生:</td><td>"+NullUtil.getValue(pscu.getFidoctor())+"</td></tr>");//pscu.getFidate()==null?"-":
String summary=NullUtil.getValue(pscu.getSummary());
summary=summary.replace("<", "<");
sb.append("<tr><td>综述:</td><td colspan=\"3\">"+summary+"</td></tr>");
sb.append("<tr><td>诊断:</td><td colspan=\"3\">"+NullUtil.getValue(pscu.getDiagnosis())+"</td></tr>");
sb.append("<tr><td>建议:</td><td colspan=\"3\">"+NullUtil.getValue(pscu.getSuggestion())+"</td></tr>");
sb.append("</table>");
sb.append("<table class=\"tbl_section\">");
for(Pecsection pc:sections){
sb.append("<tr><td>"+NullUtil.getValue(pc.getTitle())+"</td><td></td></tr>");
}
sb.append("</table>");
sb.append("<table class=\"tbl_list\">");
sb.append("<tr><th width=\"8%\">项目ID</th><th width=\"18%\">项目名称</th><th width=\"18%\">项目结果</th><th width=\"8%\">项目单位</th><th width=\"8%\">参考范围</th><th width=\"9%\">是否异常</th><th width=\"6%\">科室ID</th></tr>");
int x=1;
for(Pscuitem pscuitem:psitems){
String result2="";
String result="";
if(pscuitem.getResult()!=null){
result=pscuitem.getResult();
result=result.replace("<", "<");
result=result.trim();
System.out.println(result);
String result0=result;
int length=result.length();
int brCount= (int) Math.ceil((double)length/(double)10);
System.out.println("brCount"+brCount+"length"+length);
if(length>10){
int y=0;
for(int i=1;i<brCount;i++){
result2=result2+result0.substring((i-1)*10, i*10)+"<br/>";
y=i*10;
}
result2=result2+result0.substring(y, length);
System.out.println("result"+result2);
}else{
result2=result;
}
}
sb.append("<tr><td>"+NullUtil.getIID(pscuitem.getIid(),x)+"</td><td>"+NullUtil.getValue(pscuitem.getTitle())+"</td><td>"+result2+"</td><td>"+NullUtil.getValue(pscuitem.getUnit())+"</td><td>"+NullUtil.getValue(pscuitem.getLowvalue())+" - "+NullUtil.getValue(pscuitem.getHighvalue())+"</td><td>"+NullUtil.getValue(pscuitem.getIsabnormity())+"</td><td>"+Const.allSection.get(pscuitem.getSid())+"</td></tr>");
x=x+1;
}
sb.append("</table>");
sb.append("</div>");
// sb.append("</form>");
sb.append("</body>");
sb.append("</html>");
printStream.write(sb.toString().getBytes("utf-8"));
printStream.close();
return date;
}
}
生成pdf并压缩
package cn.zgjkw.hm.util;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;
import cn.zgjkw.hm.model.Pecsection;
import cn.zgjkw.hm.model.PscuWithBLOBs;
import cn.zgjkw.hm.model.Pscuitem;
import cn.zgjkw.hm.service.pscu.PSCUItemService;
import com.lowagie.text.pdf.BaseFont;
public class ExportUtil {
public static void report(String path,List<PscuWithBLOBs> pscus,Long psid,PSCUItemService itemService) throws Exception {
if(!pscus.isEmpty()){
for(PscuWithBLOBs pscu:pscus){
HashMap skey = new HashMap();
skey.put("pscuid", pscu.getId());
List<Pscuitem> psitems=itemService.search(skey);
List<Pecsection> sections=itemService.search(pscu.getId());
String html=ExportHtml.exportHtml(path,pscu,sections,psitems);//生成html文件
String fileHtml=path+"\\"+pscu.getPsid()+"\\"+pscu.getId()+html+".html";//html位置
File file=new File(path+"\\"+pscu.getPsid()+"\\"+pscu.getId()+html+".pdf");//pdf位置
OutputStream os = new FileOutputStream(file);
ITextRenderer renderer = new ITextRenderer();
String url = new File(fileHtml).toURI().toURL().toString();
renderer.setDocument(url);
// 解决中文支持问题
ITextFontResolver fontResolver = renderer.getFontResolver();
renderer.getFontResolver().addFont("C:/Windows/Fonts/simsun.ttc", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
renderer.layout();
renderer.createPDF(os);
os.flush();
os.close();
//FileUtil.remove(new File(fileHtml));
}
File fileZIP=new File(path+"\\"+psid+"report.zip");
if(fileZIP.exists()){
FileUtil.remove(fileZIP);
}
ZIPUtil.zipFile(path+"\\"+psid, path+"\\"+psid+"\\"+"report.zip");
}
}
}
action:
@RequestMapping(value="export/{id}",method=RequestMethod.GET)
public ModelAndView export(@PathVariable("id") Long id,HttpServletRequest request,HttpServletResponse response) throws Exception{
String path=request.getRealPath("/report");
List<PscuWithBLOBs> pscus = pscuService.getPSCUByPsid(id);
System.out.println(234);
ExportUtil.report(path, pscus,id,itemService);
response.setContentType("text/html;charset=utf-8");
request.setCharacterEncoding("UTF-8");
java.io.BufferedInputStream bis = null;
java.io.BufferedOutputStream bos = null;
String downLoadPath =path+"\\"+id+"\\"+"report.zip";
System.out.println(downLoadPath);
try {
long fileLength = new File(downLoadPath).length();
response.setContentType("application/x-msdownload;");
response.setHeader("Content-disposition", "attachment; filename="
+ new String("report.zip".getBytes("utf-8"), "ISO8859-1"));
response.setHeader("Content-Length", String.valueOf(fileLength));
bis = new BufferedInputStream(new FileInputStream(downLoadPath));
bos = new BufferedOutputStream(response.getOutputStream());
byte[] buff = new byte[2048];
int bytesRead;
while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
bos.write(buff, 0, bytesRead);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (bis != null)
bis.close();
if (bos != null)
bos.close();
}
FileUtil.remove(new File(path+"\\"+id));
return null;
}