Word轉換Html後分頁展示--第二部分
阿新 • • 發佈:2018-11-30
這篇文章繼續上一篇”Word轉換Html後分頁展示--第一部分“
實現
2. 當瀏覽器開啟Html頁面後需要執行一段計算分頁的js,這段js是在生成Html後通過改寫加入的。下面是上傳Servlet
注意48—52行就是加入js,js內容如下package com.word.servlet; import java.io.File; import java.io.IOException; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.io.FileUtils; import com.word.jacob.JacobUtil; import com.word.websocket.WebSocketMessageInboundPool; public class UpLoadServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); String path = request.getRealPath("/upload")+"\\"; DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try { List<FileItem> list = (List<FileItem>)upload.parseRequest(request); for(FileItem item : list) { String name = item.getFieldName(); if(item.isFormField()) { request.setAttribute(name, item.getString()); } else { //獲取路徑名 String value = item.getName(); int start = value.lastIndexOf("\\"); String filename = value.substring(start+1); Long time = System.currentTimeMillis(); String htmlName = time+".html"; item.write(new File(path,filename)); //轉換word JacobUtil.wordConvertSingleton(path + filename, path + htmlName); //改寫html,加入js File file = new File(path + htmlName); String content = FileUtils.readFileToString(file,"GBK"); content = content.replaceAll("<head>", "<head><script src=\"jquery-1.9.0.min.js\"></script>"); content = content.replaceAll("</body>", "</body><script src=\"record.js\"></script>"); FileUtils.writeStringToFile(file , content); WebSocketMessageInboundPool.sendMessage("upload\\"+htmlName); //寫空html String htmlName2 = time+"_1.html"; File file2 = new File(path + htmlName2); int div_start = content.indexOf("<div"); int div_end = content.substring(div_start).indexOf(">"); content = content.substring(0,div_start+div_end+1)+"</div></body><script src='read.js'></script></html>"; FileUtils.writeStringToFile(file2 , content); response.sendRedirect("upload/"+htmlName2+"?id="+htmlName); } } }catch (Exception e) { e.printStackTrace(); } } }
3.儲存很簡單,我使用的Dbutils工具包,具體是servlet如下$(document).ready(function(){ setTimeout('calc()',1000); }) //計算分頁長度,提交分頁資訊和段落內容 function calc(){ var page = 0; var height = 0; var html = ""; var pathname = window.location.pathname var id = pathname.substr(pathname.lastIndexOf("/")+1); //獲取div下的子元素,即<p> $("div").children().each(function(i){ height += $(this).height(); //將<p>累加,當高度大於等於600畫素時,向後臺記錄一次 html += $("<p1>").append($(this).clone()).html(); if(height >= 600){ page++; height = 0; $.post("../record", {id: id, pages: page, content: html}); html = ""; } }); page++; //記錄最後一頁內容,並關閉 $.post("../record", {id: id, pages: page, content: html},function(){ window.close(); }); }
插入和讀取程式碼如下package com.word.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.word.jdbc.DbUtil; public class RecordServlet extends HttpServlet { private static final long serialVersionUID = 1L; @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); try { DbUtil.insert("insert into pagecontent (id, pages, content) values (?, ?, ?)", new Object[]{request.getParameter("id"), request.getParameter("pages"), request.getParameter("content")}); } catch (Exception e) { e.printStackTrace(); } } }
package com.word.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.dbutils.DbUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.ResultSetHandler;
import org.apache.commons.dbutils.handlers.MapHandler;
public class DbUtil {
public static void insert(String sql,Object[] objects) throws Exception{
QueryRunner run = new QueryRunner(true);
Connection connection = getConn();
try {
run.update(connection, sql, objects);
} catch (Exception e) {
DbUtils.close(connection);
}
}
/**
* 查詢並返回Map
* @param sql
* @return
* @throws Exception
*/
public static Map<String, Object> queryForMap(String sql,Object[] objects) throws Exception{
Map<String, Object> map = new HashMap<String, Object>();
QueryRunner run = new QueryRunner(true);
Connection connection = getConn();
try {
map = (Map<String, Object>)run.query(connection, sql, getMapHandler(), objects);
} catch (Exception e) {
DbUtils.close(connection);
}
return map;
}
/**
* 獲取MapHandler封裝
* @return
*/
private static ResultSetHandler getMapHandler() {
ResultSetHandler handler = new MapHandler() {
public Map<String, Object> handle(ResultSet rs) throws SQLException {
if (!rs.next()) {
return null;
}
ResultSetMetaData meta = rs.getMetaData();
int cols = meta.getColumnCount();
Map<String, Object> result = new HashMap<String, Object>();
String data = "";
for (int i = 0; i < cols; i++) {
if (rs.getObject(i + 1)==null) {
data= "";
}else {
data = rs.getObject(i + 1).toString();
}
result.put(meta.getColumnName(i + 1).toLowerCase(), data);
}
return result;
}
};
return handler;
}
/**
* 獲取連線
* @return
* @throws Exception
*/
public static Connection getConn() throws Exception{
Class.forName("com.mysql.jdbc.Driver");
Connection connection =
DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
return connection;
}
}
資料庫表結構
DROP TABLE IF EXISTS `pagecontent`;
CREATE TABLE `pagecontent` (
`id` varchar(255) DEFAULT NULL,
`pages` int(11) DEFAULT NULL,
`content` text
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
4.生成檢視介面其實在第2步時就完成了,見UpLoadServlet第57—63行。為什麼這裡要生成一個新的檢視介面呢,因為要分頁載入,所以需要一個空的介面。但這個介面不能通用,必須每次生成對應的。這個介面的內容是將Word轉換生成的Html檔案中Body清空,並加入分頁讀取的js方法,js如下
var pages = 1;
var fdiv;
var id;
$(document).ready(function(){
var href = window.location.href;
id = href.substr(href.indexOf("id=")+3);
//獲取第一個div,並修改樣式,加上有背景色和邊框線
//修改寬度讓其看上去是Word編輯介面大小
fdiv = $("div:first");
fdiv.attr("style",fdiv.attr("style")+";width:600;height: auto;margin: 0 auto;border: 1px solid #e3e3e3;background-color: white;margin-top:30px");
$.get("../view", {id: id, pages: pages},function(data){
fdiv.html(data);
});
var allpages = 17;
//滾動條載入
$(window).scroll(function(){
var scrollHeight = Math.max(document.body.scrollHeight, document.documentElement.scrollHeight);
if ($(document).scrollTop() + document.body.clientHeight == scrollHeight) {
nextPage();
}
});
$("#index").html(pages);
})
function nextPage(){
pages++;
$.get("../view", {id: id, pages: pages},function(data){
fdiv.append(data);
$("#index").html(pages);
});
}