java原装代码完成pdf在线预览和pdf打印及下载
前提准备:
1. 项目中至少需要引入的jar包,注意版本:
a) core-renderer.jar
b) freemarker-2.3.16.jar
c) itext-2.0.8.jar
d) itextasian.jar
上代码:
注释: 此类为自定义的tag类的基类,在action中怎么放的数据,在ftl中就怎么取数据,简洁明了。
1. 自定义tag类的基类
/** * 通用的生成pdf预览和生成打印的html文件 * * @author xg君 * */ public abstract class pdftag extends bodytagsupport { private static final long serialversionuid = 1l; // 标签属性变量 private string json = ""; private string tempdir = ""; // 非标签属性变量 private map<string, object> rootmap = new hashmap<string, object>(); private string templatestr = null; private string freemarkereconfigurationbeanname = null; private string filename = null; private string basepath = null; private string fileencoding = "utf-8"; @override public int dostarttag() throws jspexception { setconfigparams(); webapplicationcontext application = webapplicationcontextutils.getwebapplicationcontext(pagecontext .getservletcontext()); doservicestart(); string ctx = (string) pagecontext.getattribute("ctx"); rootmap.put("ctx", ctx); map<string, object> map = parsejson2map(json); rootmap.putall(map); if (freemarkereconfigurationbeanname == null) { try { throw new cstuexception("freemarkereconfigurationbeanname不能为空!"); } catch (cstuexception e) { e.printstacktrace(); } } configuration cptfreemarkereconfiguration = (configuration) application .getbean(freemarkereconfigurationbeanname); try { if (templatestr == null) { throw new cstuexception("模板文件不能为空!"); } template template = cptfreemarkereconfiguration.gettemplate(templatestr); if (basepath == null) { throw new cstuexception("文件的基本路径(父路径)不能为空!"); } file htmlpath = new file(tempdir + file.separator + basepath); if (!htmlpath.exists()) { htmlpath.mkdirs(); } if (filename == null) { throw new cstuexception("生成的html文件名不能为空!"); } file htmlfile = new file(htmlpath, file.separator + filename); if (!htmlfile.exists()) { htmlfile.createnewfile(); } bufferedwriter out = new bufferedwriter( new outputstreamwriter(new fileoutputstream(htmlfile), fileencoding)); template.process(rootmap, out); out.flush(); doservicedoing(); // 显示在页面 template.process(rootmap, pagecontext.getresponse().getwriter()); } catch (exception e) { e.printstacktrace(); } doserviceend(); return skip_body; } /** * 配置基础参数,如 */ public abstract void setconfigparams(); /** * 业务处理方法-开始 填充数据 * * @return */ public abstract void doservicestart(); /** * 业务处理方法-执行中 备用,可空实现,若rootmap中存在双份数据则可在此处填充判断条件 * * @return */ public abstract void doservicedoing(); /** * 业务处理方法-结束 清空rootmap并调用垃圾回收,也可空实现 * * @return */ public abstract void doserviceend(); /** * 将元素放入rootmap中 */ public void putkv(string key, object value) { rootmap.put(key, value); } /** * 将map放入rootmap中 * * @param m */ public void putmap(map m) { rootmap.putall(m); } public void clear() { rootmap.clear(); rootmap = null; } /** * 移除元素 * * @param key * @return */ public object remove(string key) { return rootmap.remove(key); } public static map<string, object> parsejson2map(string jsonstr) { map<string, object> map = new hashmap<string, object>(); jsonobject json = jsonobject.fromobject(jsonstr); for (object k : json.keyset()) { object v = json.get(k); if (v instanceof jsonarray) { list<map<string, object>> list = new arraylist<map<string, object>>(); iterator<jsonobject> it = ((jsonarray) v).iterator(); while (it.hasnext()) { jsonobject json2 = it.next(); list.add(parsejson2map(json2.tostring())); } map.put(k.tostring(), list); } else { map.put(k.tostring(), v); } } return map; } public string getjson() { return json; } public void setjson(string json) { this.json = json; } public string gettempdir() { return tempdir; } public void settempdir(string tempdir) { this.tempdir = tempdir; } public string gettemplatestr() { return templatestr; } public void settemplatestr(string templatestr) { this.templatestr = templatestr; } public string getfreemarkereconfigurationbeanname() { return freemarkereconfigurationbeanname; } public void setfreemarkereconfigurationbeanname(string freemarkereconfigurationbeanname) { this.freemarkereconfigurationbeanname = freemarkereconfigurationbeanname; } public string getfilename() { return filename; } public void setfilename(string filename) { this.filename = filename; } public string getbasepath() { return basepath; } public void setbasepath(string basepath) { this.basepath = basepath; } public string getfileencoding() { return fileencoding; } public void setfileencoding(string fileencoding) { this.fileencoding = fileencoding; } }
注释: setconfigparams方法是用于调用接口定义的配置参数的方法,如:templatestr,basepath等,doservicestart,doservicedoing和doserviceend等方法用于处理业务逻辑,比如我的需求是做出合同在一个页面显示,要分页,要加水印,但生成的pdf样式与预览的是不同的,所以我加了一个doservicedoing中给rootmap添加判断条件,这样就能一个flt文件作出两种效果(预览和打印),当然如果预览和打印要一样的效果,doservicedoing方法可以空实现。这四个方法总结一下就是:
1. setconfigparams : 配置参数
2. doservicestart : 填充数据/条件
3. doservicedoing : 填充数据/条件,到这里是个分界线,此方法之前,rootmap数据先进入html再进入浏览器(预览),此方法之后,rootmap数据会再次进入html文件,结束,所以此处可写判断
4. doserviceend : 可有可无,我还是写上了,万一哪天的数据集太大,此处便可以在数据填充完后,清理掉,节省内存空间
2. pdftag的子类
/** * 用户自定义pdftag类 * * @author xg君 * */ public class viewpdftag extends pdftag { private static final long serialversionuid = 4528567203497016087l; private string prjnature = ""; private string bookname = ""; private string prjcode = ""; /** * 用户自定义的配置参数 */ public pdfconfigurationinterface pdfconfigurationinterface = new pdfconfigurationinterface() { @override public void configtemplatestr() { // 横,纵向 if (prjnature.equalsignorecase("2") || prjnature.equalsignorecase("1")) { settemplatestr("wj-project-print.ftl"); } } @override public void configfreemarkereconfigurationbeanname() { setfreemarkereconfigurationbeanname("cptfreemarkereconfiguration"); } @override public void configfilename() { // 填入html文件 setfilename(prjcode + ".html"); } @override public void configfileencoding() { // 默认utf-8 } @override public void configbasepath() { setbasepath("html_pdf"); } }; @override public void doservicestart() { putkv("prjnature", prjnature); putkv("bookname", bookname); putkv("flag", "0"); } @override public void doservicedoing() { putkv("flag", "1"); } @override public void doserviceend() { clear(); system.gc(); } public string getprjnature() { return prjnature; } public void setprjnature(string prjnature) { this.prjnature = prjnature; } public string getbookname() { return bookname; } public void setbookname(string bookname) { this.bookname = bookname; } public string getprjcode() { return prjcode; } public void setprjcode(string prjcode) { this.prjcode = prjcode; } @override public void setconfigparams() { pdfconfigurationinterface.configtemplatestr(); pdfconfigurationinterface.configfreemarkereconfigurationbeanname(); pdfconfigurationinterface.configfilename(); pdfconfigurationinterface.configbasepath(); pdfconfigurationinterface.configfileencoding(); } }
注释: pdfconfigurationinterface 是自定义的标签参数配置接口,子类必须定义一个该接口的实现类的成员变量或定义一个成员变量内部类,并在setconfigparams方法中调用使其生效。
子类的成员变量接收在tld文件中配置的属性。
3. 自定义的标签参数配置接口
/** * pdftag类的配置 * * @author xg君 * */ public interface pdfconfigurationinterface { /** * 设置模板名称 */ void configtemplatestr(); /** * 设置配置的freemarkereconfigurationbean的名称 */ void configfreemarkereconfigurationbeanname(); /** * 设置生成的html文件名称 */ void configfilename(); /** * 设置生成的html文件的基本路径(父目录) */ void configbasepath(); /** * 设置文件编码,默认utf-8 */ void configfileencoding(); }
4. 自定义异常类
/** * 自定义异常类 * * @author administrator * */ public class cstuexception extends exception { private static final long serialversionuid = 4266461814747405870l; public cstuexception(string msg) { super(msg); } }
5. tld文件配置
<tag> <name>print</name> <tagclass>com.iris.taglib.web.previewpdftag</tagclass> <bodycontent>jsp</bodycontent> <attribute> <name>json</name> <required>true</required> <rtexprvalue>true</rtexprvalue> </attribute> <attribute> <name>prjnature</name> <required>true</required> <rtexprvalue>true</rtexprvalue> </attribute> <attribute> <name>bookname</name> <required>true</required> <rtexprvalue>true</rtexprvalue> </attribute> <attribute> <name>tempdir</name> <required>true</required> <rtexprvalue>true</rtexprvalue> </attribute> <attribute> <name>prjcode</name> <required>true</required> <rtexprvalue>true</rtexprvalue> </attribute> </tag>
6. action
/** * 处理pdf导出 * */ @namespace("/export") @results({ @result(name = "exceltemplate", location = "/web-inf/content/pdf/export-pdf.jsp"), @result(name = "exprotpdf2", location = "/web-inf/content/project/project/export/export-pdf2.jsp") }) public class exportpdfaction extends actionsupport { private static final long serialversionuid = -5454188364706173477l; @value("${tempdir}") private string tempdir; @value("${pdffont}") private string pdffont; @value("${staticresrootdir}") private string staticresrootdir; @value("${staticresrootdir2}") private string staticresrootdir2; @value("${watermarkimgdir}") private string watermarkimgdir; @autowired private projectservice projectservice; @autowired private personservice personservice; @autowired private constdictionaryservice constdictionaryservice; @autowired private fdplandetailservice fdplandetailservice; @autowired private servicefactory servicefactory; @action("exprotpdf2") public string exprotpdf2() { string prjcode = struts2utils.getparameter("prjcode"); prjcode = struts2utils.decodedesstring(prjcode); project project = projectservice.getprojectbyid(long.parselong(prjcode)); map<string, string> baseinfo = new hashmap<string, string>(); baseinfo.put("tempdir", tempdir); // 项目编号 baseinfo.put("prjcode", prjcode); // 项目类型 string prjnature = project.getprjnature(); baseinfo.put("prjnature", prjnature); // 水印名称格式:watermark+"-"+prjnature baseinfo.put("watermarkimg", watermarkimgdir + file.separator + "watermark-" + prjnature + ".png"); // 负责人 person person = personservice.getperson(project.getpsncode()); string zhname = person.getzhname(); baseinfo.put("zhname", addstr(9, "<br/>", zhname)); // 项目编号 string prjno = project.getprjno(); baseinfo.put("prjno", prjno); // 项目来源 constdictionary cd = constdictionaryservice.findcdbycategorycode("project_from", project.getgrantno()); string project_from = cd.getzh_cn_caption(); baseinfo.put("project_from", addstr(9, "<br/>", project_from)); simpledateformat sdf = new simpledateformat("yyyy-mm-dd"); // 起止年限 string startdate = sdf.format(project.getstartdate()); string enddate = sdf.format(project.getenddate()); string startenddate = startdate + "~" + enddate; baseinfo.put("startenddate", startenddate); // 项目类别--资助类别 string grantname = project.getgrantname(); baseinfo.put("grantname", addstr(9, "<br/>", grantname)); // 合同金额 string totalamt = project.gettotalamt().tostring(); bigdecimal totalamt_ = checknumber(totalamt); baseinfo.put("totalamt", totalamt_.tostring()); // 项目名称 string zhtitle = project.getzhtitle(); baseinfo.put("zhtitle", addstr(38, "<br/>", zhtitle)); list<map<string, string>> ps = null; try { ps = getmembers(project.getprjxml()); } catch (exception e) { e.printstacktrace(); } string bookname = ""; // 判断项目类型 map<string, object> itemmap = new hashmap<string, object>(); if (prjnature.equalsignorecase("1")) { bookname = "第一份合同"; // 获取fdplandetail list<map<string, object>> list = fdplandetailservice.getfdplandetailsbyprjcode(long.parselong(prjcode)); // test /* * map<string, object> test = new hashmap<string, object>(); test.put("itemvalue", "6"); * test.put("itemname", "差旅费"); test.put("remark", "xxxxx"); list.add(test); */ for (map<string, object> m : list) { string key = (string) m.get("itemname"); bigdecimal itemvalue = (bigdecimal) m.get("itemvalue"); bigdecimal proportion = new bigdecimal(0.00); if (itemvalue != null && totalamt_.compareto(new bigdecimal("0.00")) != 0) { proportion = itemvalue.divide(totalamt_, 6, bigdecimal.round_half_even); } if (itemvalue == null) { itemvalue = new bigdecimal("0.00"); } proportion = checknumber(proportion.tostring()); map<string, object> data = new hashmap<string, object>(); // 添加比例 data.put("proportion", proportion.tostring()); // 检测金额规范 bigdecimal amt = checknumber(itemvalue.tostring()); data.put("itemvalue", amt.tostring()); // remark string remark = (string) m.get("reamrk"); data.put("remark", remark == null ? "" : remark); itemmap.put(key, data); } } else if (prjnature.equalsignorecase("2")) { bookname = "第二份合同"; } map<string, object> map = new hashmap<string, object>(); map.put("baseinfo", baseinfo); map.put("projectmember", ps); map.put("itemmap", itemmap); map.put("pscount", ps.size()); map.put("pssum", 25 - ps.size()); string json = jsonobject.fromobject(map).tostring(); struts2utils.getrequest().setattribute("jsondata", json); struts2utils.getrequest().setattribute("prjnature", prjnature); struts2utils.getrequest().setattribute("bookname", bookname); struts2utils.getrequest().setattribute("tempdir", tempdir); struts2utils.getrequest().setattribute("prjcode", prjcode); return "exprotpdf2"; } public list<map<string, string>> getmembers(string xmldata) throws exception { list<map<string, string>> list = new arraylist<map<string, string>>(); document doc = documenthelper.parsetext(xmldata); node ps = doc.selectsinglenode("/data/project/persons"); list<node> pslist = ps.selectnodes("person"); string totalamt = doc.selectsinglenode("/data/project/basic_info/total_amt").gettext(); for (node person : pslist) { map<string, string> map = new hashmap<string, string>(); node fund_proportion = person.selectsinglenode("fund_proportion"); string fund_proportion_text = ""; if (fund_proportion == null) { map.put("proportion", "0.00"); map.put("fpamt", "0.00"); } else { fund_proportion_text = fund_proportion.gettext(); bigdecimal fp = new bigdecimal(fund_proportion_text); fp = fp.multiply(new bigdecimal("0.01")); fp = checknumber(fp.tostring()); map.put("proportion", fp.tostring()); bigdecimal fdamt_ = fp.multiply(new bigdecimal(totalamt)); fdamt_ = checknumber(fdamt_.tostring()); map.put("fpamt", fdamt_.tostring()); } node psn_name = person.selectsinglenode("psn_name"); string psn_name_text = psn_name.gettext(); map.put("zhname_p", addstr(9, "<br/>", psn_name_text)); node psn_work = person.selectsinglenode("psn_work"); string psn_work_text = ""; if (psn_work != null) { psn_work_text = psn_work.gettext(); } map.put("work", addstr(9, "<br/>", psn_work_text)); node dept_code_name = person.selectsinglenode("dept_code_name"); string dept_code_name_text = ""; if (dept_code_name != null) { dept_code_name_text = dept_code_name.gettext(); } map.put("deptname", addstr(9, "<br/>", dept_code_name_text)); node psn_type_name = person.selectsinglenode("psn_type_name"); string psn_type_name_text = ""; if (psn_type_name != null) { psn_type_name_text = psn_type_name.gettext(); } map.put("psntypename", psn_type_name_text); list.add(map); } return list; } /** * 为字符串添加指定字符 * * @param num * @param splitstr * @param str * @return */ public string addstr(int num, string splitstr, string str) { stringbuffer sb = new stringbuffer(); string temp = str; int len = str.length(); while (len > 0) { if (len < num) { num = len; } sb.append(temp.substring(0, num)).append(splitstr); temp = temp.substring(num); len = temp.length(); } return sb.tostring(); } /** * 两个数字/英文 * * @param str * @param num * @return 最终索引 */ public static int getendindex(string str, double num) { int idx = 0; int count = 0; double val = 0.00; // 判断是否是英文/数字 for (int i = 0; i < str.length(); i++) { if ((str.charat(i) >= 'a' && str.charat(i) <= 'z') || (str.charat(i) >= 'a' && str.charat(i) <= 'z') || character.isdigit(str.charat(i))) { val += 0.50; } else { val += 1.00; } count = i + 1; if (val >= num) { idx = i; break; } } if (idx == 0) { idx = count; } return idx; } /** * 下载pdf文件 * * @return */ @action("download") public string download() { string prjcode = struts2utils.getparameter("prjcode"); string basepath = "html_pdf"; project project = projectservice.getprojectbyid(long.parselong(prjcode)); string zhtitle = project.getzhtitle(); fileoutputstream fos = null; // html file htmlfile = new file(tempdir + file.separator + basepath + file.separator + prjcode + ".html"); string pdfpath = tempdir + file.separator + basepath + file.separator + zhtitle + ".pdf"; try { fos = new fileoutputstream(pdfpath); string url = htmlfile.touri().tourl().tostring(); itextrenderer renderer = new itextrenderer(); renderer.setdocument(url); itextfontresolver fontresolver = renderer.getfontresolver(); fontresolver.addfont(pdffont + file.separator + "simsun.ttc", basefont.identity_h, basefont.not_embedded); renderer.layout(); renderer.createpdf(fos); } catch (exception e) { e.printstacktrace(); } finally { try { if (fos != null) { fos.close(); } } catch (ioexception e) { e.printstacktrace(); } } // 添加水印 string wartermark = ""; if (project.getprjnature().equalsignorecase("1")) { // 横向 wartermark = "ctgu横向科研项目立项通知书"; } else if (project.getprjnature().equalsignorecase("2")) { // 纵向 wartermark = "ctgu纵向科研项目立项通知书"; } string wm_pdf = tempdir + file.separator + "wm_" + project.getzhtitle() + ".pdf"; try { bufferedoutputstream bos = new bufferedoutputstream(new fileoutputstream(wm_pdf)); watermark(bos, pdfpath, wartermark, staticresrootdir2 + file.separator + watermarkimgdir + file.separator + "watermark-" + project.getprjnature() + ".png"); } catch (exception e2) { e2.printstacktrace(); } // 拿到pdf file pdffile = new file(wm_pdf); bufferedoutputstream out = null; fileinputstream in = null; try { in = new fileinputstream(pdffile); httpservletresponse response = struts2utils.getresponse(); response.reset(); string filename = zhtitle + ".pdf"; string filename2 = urlencoder.encode(filename, "utf-8"); string agent = struts2utils.getrequest().getheader("user-agent"); // ie if (null != agent && -1 != agent.indexof("msie")) { filename2 = new string(filename.getbytes("gbk"), "iso8859-1"); } else if (null != agent && -1 != agent.indexof("mozilla")) { filename2 = new string(filename.getbytes("utf-8"), "iso8859-1"); } response.setcharacterencoding("utf-8"); response.setheader("content-disposition", "attachment;filename=\"" + filename2 + "\""); response.setcontenttype(filecontenttypes.getcontenttype(zhtitle + ".pdf")); out = new bufferedoutputstream(response.getoutputstream()); byte[] buffer = new byte[16 * 1024]; int len = 0; while ((len = in.read(buffer)) > 0) { out.write(buffer, 0, len); } out.flush(); } catch (exception e) { e.printstacktrace(); } finally { if (out != null) { try { out.close(); } catch (ioexception e1) { e1.printstacktrace(); } try { in.close(); } catch (ioexception e) { e.printstacktrace(); } } } // 清理残留文件 // if (htmlfile.exists()) { // htmlfile.delete(); // } file temp_file = new file(pdfpath); if (temp_file.exists()) { temp_file.delete(); } if (pdffile.exists()) { pdffile.delete(); } return null; } public bigdecimal checknumber(string number) { // 初始化为6位小数 decimalformat df = new decimalformat("0.000000"); string num = df.format(double.parsedouble(number)); bigdecimal bd = new bigdecimal(num); string val = bd.tostring(); val = val.replaceall("^(0+)", ""); val = val.replaceall("(0+)$", ""); int idx = val.indexof("."); int len = val.substring(idx + 1).length(); if (len < 2) { if (len == 0 && idx == 0) { bd = new bigdecimal("0.00"); } else { bd = new bigdecimal(val).setscale(2); } } else { bd = new bigdecimal(val).setscale(len); } return bd; } private string replacestr(string str, string reval) { pattern pattern = pattern.compile("^" + reval + "+|" + reval + "+$"); matcher matcher = pattern.matcher(str); return matcher.replaceall(""); } /** * 添加水印 */ private void watermark(bufferedoutputstream bos, string input, string watermarkname, string imagepath) { try { pdfreader reader = new pdfreader(input); pdfstamper stamper = new pdfstamper(reader, bos); int total = reader.getnumberofpages() + 1; pdfcontentbyte content; basefont base = basefont.createfont("stsong-light", "unigb-ucs2-h", basefont.embedded); pdfgstate gs = new pdfgstate(); for (int i = 1; i < total; i++) { content = stamper.getovercontent(i);// 在内容上方加水印 content.setgstate(gs); content.begintext(); image image = image.getinstance(imagepath); image.setabsoluteposition(-30, 200); image.scalepercent(80); content.addimage(image); content.endtext(); } stamper.close(); } catch (exception e) { e.printstacktrace(); } } }
7. ftl文件(模板文件)
<?xml version="1.0" encoding="utf-8"?> <!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>打印预览</title> <meta http-equiv="content-type" content="text/html;charset=utf-8" /> ...... </head> <body> </body> </html>
预览效果:
打印效果:
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持!