java使用在線編輯器生成PDF

    最近要作經過在線編輯器生成PDF文件的功能。在參考了網上的資料後,結合項目的實際須要作了些修改,現把作完的功能記錄下來。須要的jar包: core-renderer.jar 和 iText-2.0.8.jar

java代碼以下:css

/**
	 * 使用在線編輯器生成PDF
	 * @param htmlCode  編輯器內容
	 * @param pdfPath	PDF文件保存路徑
	 */

	public static void html2Pdf(String htmlCode, String pdfPath) {
		 try {
			 
			 String realPath = ServletActionContext.getRequest().getSession().
				getServletContext().getRealPath("");
			 String fontPath = realPath + "\\resource\\font\\simsun.ttc";
			 String projectName = realPath.substring(realPath.lastIndexOf("\\") + 1);
			 
			 /**
			  * 替換編輯器中上傳圖片的路徑, 用於解決用戶上傳圖片的相對路徑問題     
			  * 替換前:src="/xxx/resource/manual/
			  * 替換後:src="xxx/resource/manual/
			  */
			 String oldChar = "/" + projectName + "/resource/manual/";
			 String newChar = projectName + "/resource/manual/";
			 htmlCode = htmlCode.replace(oldChar, newChar);
				
			 OutputStream os = new FileOutputStream(pdfPath);     
			 ITextRenderer renderer = new ITextRenderer();     
			 StringBuffer html = new StringBuffer();
			 // DOCTYPE 必需寫不然相似於這樣的字符( )解析會出現錯誤
			 html.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">");
			 html.append("<html xmlns=\"http://www.w3.org/1999/xhtml\">")
				 .append("<head>")
				 .append("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\" />")
				 .append("<style type=\"text/css\" >body {font-family: SimSun;}</style>")
				 .append("</head>").append("<body>");
			 html.append(htmlCode);
			 html.append("</body></html>");  
			 renderer.setDocumentFromString(html.toString());
			 // 解決中文支持問題     
			 ITextFontResolver fontResolver = renderer.getFontResolver();     
			 fontResolver.addFont(fontPath, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);     
			 realPath = realPath.replace(projectName, ""); // 去掉項目名
			 realPath = realPath.replace("\\", "/");
			 // 解決圖片的相對路徑問題  ,圖片路徑必須以file開頭
			 renderer.getSharedContext().setBaseURL("file:/" + realPath); 
			 renderer.layout();     
			 renderer.createPDF(os);     
			 os.close();
		} catch (Exception e) {
			e.printStackTrace();
		} 
	}
相關文章
相關標籤/搜索