java原裝代碼完成pdf在線預覽和pdf打印及下載。本站提示廣大學習愛好者:(java原裝代碼完成pdf在線預覽和pdf打印及下載)文章只能為提供參考,不一定能成為您想要的結果。以下是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" />打印效果:
以上就是本文的全部內容,希望本文的內容對大家的學習或許任務能帶來一定的協助,同時也希望多多支持!