PDFMaker.java 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387
  1. package kr.co.udapsoft.common.util;
  2. import java.awt.Dimension;
  3. import java.awt.Insets;
  4. import java.io.BufferedReader;
  5. import java.io.File;
  6. import java.io.FileInputStream;
  7. import java.io.FileNotFoundException;
  8. import java.io.FileOutputStream;
  9. import java.io.FileReader;
  10. import java.io.IOException;
  11. import java.io.StringReader;
  12. import java.net.MalformedURLException;
  13. import java.security.InvalidParameterException;
  14. import kr.co.hsnc.common.base.WAFLogger;
  15. import kr.co.hsnc.common.config.WAFConfig;
  16. import kr.co.hsnc.common.util.ValueObject;
  17. import org.zefer.pd4ml.PD4Constants;
  18. import org.zefer.pd4ml.PD4ML;
  19. import org.zefer.pd4ml.PD4PageMark;
  20. import crosscert.Hash;
  21. public class PDFMaker {
  22. private int htmlWidth = 750;
  23. private String header = null;
  24. private String footer = null;
  25. private String footerDefault = "*본 계약서는 상기업체 간에 전자서명법 등 관련법령에 근거하여 전자서명으로 체결한 전자계약서입니다.<br>&nbsp;&nbsp;전자계약 진위여부는 협력업체포털시스템(http://partner.sgcenc.co.kr)에서 확인하실 수 있습니다.";
  26. private String cont_no = "";
  27. private String cont_chasu = "";
  28. private String file_seq = "";
  29. private String random_no = "";
  30. private String cont_userno = ""; // 사용자 계약번호
  31. public static void main(String[] args) throws InvalidParameterException, MalformedURLException, IOException{
  32. PDFMaker ed = new PDFMaker();
  33. //ed.generatePDF("file:///d:/CJ-GLS 택배대리점 계약서.html", new File("d:/CJ-GLS 택배대리점 계약서.pdf"), PD4Constants.A4);
  34. try {
  35. File f = new File("D:/Project4/pd4ml/html/", "엔지니어링 표준하도급계약서(전문).html");
  36. FileReader reader = new FileReader(f);
  37. BufferedReader buffer = new BufferedReader(reader);
  38. String html = "";
  39. String str = buffer.readLine();
  40. while(str!=null) {
  41. html += str;
  42. str = buffer.readLine();
  43. }
  44. buffer.close();
  45. StringBuffer documentContents = new StringBuffer();
  46. //documentContents.append("<html><body>");
  47. documentContents.append("<html><head><style type=\"text/css\">");
  48. documentContents.append("<!--");
  49. documentContents.append(" td { font-family: \"나눔고딕\",\"Arial\"; font-size: 12px; font-style: normal; letter-spacing:0; color: black;line-height:150%}");
  50. documentContents.append(" .lineTable { border-collapse:collapse; border:1 solid black }");
  51. documentContents.append(" .lineTable td { border:1 solid black }");
  52. documentContents.append(" .lineTable .noborder { border:0 }");
  53. documentContents.append("-->");
  54. documentContents.append("</style>");
  55. documentContents.append("</head><body>");
  56. documentContents.append(html);
  57. documentContents.append("</body></html>");
  58. ed.generatePDF(documentContents.toString(), "D:/Project4/pd4ml/html/", "엔지니어링 표준하도급계약서(전문).pdf");
  59. }
  60. catch(IOException e) {
  61. e.printStackTrace();
  62. }
  63. }
  64. public String getContNo() {
  65. return cont_no+"-"+cont_chasu+"-"+random_no;
  66. }
  67. public void setContNo(String cont_no, String cont_chasu, String random_no, String file_seq) {
  68. this.cont_no = cont_no;
  69. this.cont_chasu = cont_chasu;
  70. this.random_no = random_no;
  71. this.file_seq = file_seq;
  72. }
  73. private String getUserContNo() {
  74. return this.cont_userno;
  75. }
  76. public void setUserNo(String cont_userno) {
  77. this.cont_userno = cont_userno;
  78. }
  79. public String getHeader() {
  80. return header;
  81. }
  82. public void setHeader(String header) {
  83. this.header = header;
  84. }
  85. public String getFooter() {
  86. return footer;
  87. }
  88. public void setFooter(String footer) {
  89. this.footer = footer;
  90. }
  91. public int getHtmlWidth() {
  92. return htmlWidth;
  93. }
  94. public void setHtmlWidth(int htmlWidth) {
  95. this.htmlWidth = htmlWidth;
  96. }
  97. /**
  98. * PDF 문서 생성
  99. * @param url
  100. * @param outputPDFFile
  101. * @param format
  102. * @return
  103. */
  104. public boolean generatePDF(String url, File outputPDFFile, Dimension format) {
  105. FileOutputStream fos = null;
  106. try{
  107. fos = new FileOutputStream(outputPDFFile);
  108. PD4ML pd4ml = new PD4ML();
  109. PD4PageMark headerMark = new PD4PageMark();
  110. headerMark.setAreaHeight( 30 ); //header 영역 설정
  111. //header 데이터 셋팅
  112. if(header == null){
  113. if(!this.getUserContNo().equals(""))
  114. headerMark.setHtmlTemplate("<table border=0 width=100%><tr><td align=\"right\" valign=\"top\" ><font size=1 color=\"#5B5B5B\">* 계약번호: "+this.getUserContNo()+"</font></td></tr></table>");
  115. else
  116. headerMark.setHtmlTemplate("");
  117. }else{
  118. headerMark.setHtmlTemplate(header);
  119. }
  120. pd4ml.setPageHeader(headerMark);
  121. //footer 영역설정
  122. PD4PageMark footerMark = new PD4PageMark();
  123. footerMark.setAreaHeight( 40 );
  124. //footer 데이터 셋팅
  125. if(footer == null){
  126. footerMark.setHtmlTemplate("<table width='100%' height='35' border='0'><tr><td valign='bottom'><font size=1 color=\"#5B5B5B\">"+footerDefault+ " (관리번호:"+this.getContNo()+")</font></td></tr></table>");
  127. }else{
  128. footerMark.setHtmlTemplate("<span><font size=1 color=\"#5B5B5B\">"+ getFooter() +"</font></span>");
  129. }
  130. pd4ml.setPageFooter(footerMark);
  131. pd4ml.setPageInsets(new Insets(10,20,5,20)); //여백설정
  132. pd4ml.setHtmlWidth(getHtmlWidth()); //변환할 html의 width 정보
  133. pd4ml.setPageSize(PD4Constants.A4); //용지모양 A4설정
  134. //pd4ml.setPageSize(pd4ml.changePageOrientation(PD4Constants.A4)); //가로로 설정
  135. pd4ml.useTTF("java:fonts", true); //지정한 폰트 사용
  136. //pd4ml.setDefaultTTFs("Nanum Gothic", "Times New Roman", "Arial"); //default 폰트 설정
  137. pd4ml.setDefaultTTFs("Nanum Gothic", "Times New Roman", "Arial"); //default 폰트 설정
  138. pd4ml.enableDebugInfo();
  139. pd4ml.render(new java.net.URL(url), fos);
  140. return true;
  141. }catch(Exception e){
  142. e.printStackTrace();
  143. return false;
  144. }finally{
  145. if(fos != null)
  146. try {
  147. fos.close();
  148. } catch (IOException e) {
  149. e.printStackTrace();
  150. }
  151. }
  152. }
  153. public ValueObject makeContPdf(ValueObject vo){
  154. ValueObject pdf = null;
  155. try{
  156. String fontSize = "12px";
  157. if(!vo.get("font_size").equals("")){
  158. fontSize = vo.get("font_size");
  159. }
  160. String pdfDir = WAFConfig.get("waf.repository.path")+"/cont/";
  161. String fileDir = vo.get("folder") +"/"+ vo.get("cont_no")+"/";
  162. String fileName = vo.get("cont_no")+"_"+vo.get("cont_chasu")+"_"+vo.get("file_seq")+".pdf";
  163. String path = pdfDir + fileDir+fileName;
  164. StringBuffer documentContents = new StringBuffer();
  165. //documentContents.append("<html><body>");
  166. documentContents.append("<html><head><style type=\"text/css\">");
  167. documentContents.append("<!--");
  168. documentContents.append(" td { font-family: \"굴림체\",\"Arial\"; font-size: "+fontSize+"; font-style: normal; letter-spacing:0; color: black;line-height:150%}");
  169. documentContents.append(" .lineTable { border-collapse:collapse; border:1 solid black }");
  170. documentContents.append(" .lineTable td { border:1 solid black }");
  171. documentContents.append(" .lineTable .noborder { border:0 }");
  172. documentContents.append(" .nText td { text-align:justify; vertical-align:top;}");
  173. documentContents.append("-->");
  174. documentContents.append("</style>");
  175. documentContents.append(" <meta http-equiv='Content-Type' content='application/xhtml+xml; charset=utf-8' />");
  176. documentContents.append("</head><body>");
  177. documentContents.append(vo.get("html"));
  178. documentContents.append("</body></html>");
  179. WAFLogger.debug("시작~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
  180. WAFLogger.debug(documentContents.toString());
  181. WAFLogger.debug("끝~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~");
  182. //WAFLogger.debug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
  183. //WAFLogger.debug(documentContents);
  184. //WAFLogger.debug("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
  185. this.setContNo(vo.get("cont_no"), vo.get("cont_chasu"), vo.get("true_random"),vo.get("file_seq"));
  186. this.setUserNo(vo.get("cont_userno"));
  187. this.setHtmlWidth(750);
  188. //하도급 대금 지급 서식 작성은 footer와 header를 셋팅한다.
  189. if (vo.get("true_random").isEmpty()){
  190. this.setFooter("본 문서는 상기업체 간에 전자서명법등 관련법령에 근거하여 전자서명으로 체결한 전자문서입니다.");
  191. this.setHeader(" ");
  192. }
  193. boolean result = this.generatePDF(documentContents.toString(), pdfDir+fileDir, fileName);
  194. if(!result){
  195. return null;
  196. }
  197. WAFLogger.debug("Exception PDFMAKER : ");
  198. pdf = new ValueObject();
  199. pdf.set("file_path", fileDir);
  200. pdf.set("file_name", fileName);
  201. pdf.set("file_size", new File(path).length());
  202. pdf.set("file_ext", "pdf");
  203. pdf.set("file_hash", getHash(pdfDir+fileDir+fileName));
  204. return pdf;
  205. }catch(Exception e){
  206. WAFLogger.error("Exception PDFMAKER : " + e.getMessage());
  207. return null;
  208. }
  209. }
  210. /**
  211. * PDF 문서 생성
  212. * @param html
  213. * @param outputDir
  214. * @param outputFileName
  215. * @return
  216. */
  217. public boolean generatePDF(String html, String outputDir, String outputFileName) {
  218. FileOutputStream fos = null;
  219. try{
  220. WAFLogger.debug(outputDir+outputFileName);
  221. File outputDirFile = new File(outputDir);
  222. if(outputDirFile.exists() == false) outputDirFile.mkdirs();
  223. fos = new FileOutputStream(new File(outputDir+outputFileName));
  224. PD4ML pd4ml = new PD4ML();
  225. PD4PageMark headerMark = new PD4PageMark();
  226. headerMark.setAreaHeight( 30 ); //header 영역 설정
  227. //header 데이터 셋팅
  228. if(header == null){
  229. if(!this.getUserContNo().equals(""))
  230. headerMark.setHtmlTemplate("<table border=0 width=100%><tr><td align=\"right\" valign=\"top\" ><font size=1 color=\"#5B5B5B\">* 계약번호: "+this.getUserContNo()+"</font></td></tr></table>");
  231. else
  232. headerMark.setHtmlTemplate("");
  233. }else{
  234. headerMark.setHtmlTemplate(header);
  235. }
  236. pd4ml.setPageHeader(headerMark);
  237. //footer 영역설정
  238. PD4PageMark footerMark = new PD4PageMark();
  239. footerMark.setAreaHeight( 40 );
  240. //footer 데이터 셋팅
  241. if(footer == null){
  242. footerMark.setHtmlTemplate("<table width='100%' height='35' border='0'><tr><td valign='bottom'><font size=1 color=\"#5B5B5B\">"+footerDefault+ " (관리번호:"+this.getContNo()+")</font></td></tr></table>");
  243. }else{
  244. footerMark.setHtmlTemplate("<span><font size=1 color=\"#5B5B5B\">"+ getFooter() +"</font></span>");
  245. }
  246. pd4ml.setPageFooter(footerMark);
  247. pd4ml.setPageInsets(new Insets(10,20,5,20)); //여백설정
  248. pd4ml.setHtmlWidth(getHtmlWidth()); //변환할 html의 width 정보
  249. pd4ml.setPageSize(PD4Constants.A4); //용지모양 A4설정
  250. //pd4ml.setPageSize(pd4ml.changePageOrientation(PD4Constants.A4)); //가로로 설정
  251. pd4ml.useTTF("java:fonts", true); //지정한 폰트 사용
  252. pd4ml.setDefaultTTFs("Nanum Gothic", "Times New Roman", "Arial"); //default 폰트 설정
  253. pd4ml.enableDebugInfo();
  254. pd4ml.render(new StringReader(html), fos);
  255. return true;
  256. }catch(Exception e){
  257. e.printStackTrace();
  258. WAFLogger.error("Exception PDF : " + e.getMessage());
  259. return false;
  260. }finally{
  261. if(fos != null)
  262. try {
  263. fos.close();
  264. } catch (IOException e) {
  265. e.printStackTrace();
  266. }
  267. }
  268. }
  269. /**
  270. * Hash 정보 가져오기
  271. * @param sOtherFullDir
  272. * @return
  273. * @throws ConfigurationException
  274. * @throws ConfigurationException
  275. * @throws IOException
  276. */
  277. public String getHash(String sOtherFullDir)
  278. {
  279. FileInputStream fis = null;
  280. String sHash = "";
  281. try {
  282. /*
  283. String sBaseDir = WAFConfig.get("waf.repository.path")+"/cont";
  284. if(sBaseDir.lastIndexOf("/") == sBaseDir.length() - 1)
  285. {
  286. sBaseDir = sBaseDir.substring(0,sBaseDir.length()-1);
  287. }
  288. if(sOtherFullDir.indexOf("/") == 0)
  289. {
  290. sOtherFullDir = sOtherFullDir.substring(1);
  291. }
  292. String sFullFilePath = sBaseDir + "/" + sOtherFullDir;
  293. */
  294. String sFullFilePath = sOtherFullDir;
  295. //sFullFilePath = StrUtil.replace(sFullFilePath,"\\",File.separator);
  296. //sFullFilePath = StrUtil.replace(sFullFilePath,"/",File.separator);
  297. WAFLogger.debug("getHash : " + sFullFilePath);
  298. fis = new FileInputStream(new File(sFullFilePath));
  299. int iFileLen = fis.available();
  300. byte[] b = new byte[iFileLen];
  301. int iRet = fis.read(b);
  302. Hash hash = new Hash();
  303. iRet = hash.GetHash(b, b.length);
  304. if(iRet == 0)
  305. {
  306. sHash = new String(hash.contentbuf);
  307. }else
  308. {
  309. sHash = "";
  310. }
  311. } catch (FileNotFoundException e) {
  312. WAFLogger.error("[ERROR "+this.getClass().getName() + ".getHash()] :" + e.toString());
  313. //throw new FileNotFoundException("[ERROR "+this.getClass().getName()+".getHash()] " + e.toString());
  314. } catch (IOException e) {
  315. WAFLogger.error("[ERROR "+this.getClass().getName() + ".getHash()] :" + e.toString());
  316. //throw new IOException("[ERROR "+this.getClass().getName()+".getHash()] " + e.toString());
  317. } finally
  318. {
  319. try {
  320. if(fis != null) fis.close();
  321. } catch (IOException e) {
  322. WAFLogger.error("[ERROR "+this.getClass().getName() + ".getHash()] :" + e.toString());
  323. //throw new IOException("[ERROR "+this.getClass().getName()+".getHash()] " + e.toString());
  324. }
  325. }
  326. return sHash;
  327. }
  328. }