添加maven依赖
<dependency>
<groupId>com.documents4j</groupId>
<artifactId>documents4j-api</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>com.documents4j</groupId>
<artifactId>documents4j-local</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>com.documents4j</groupId>
<artifactId>documents4j-transformer-msoffice-word</artifactId>
<version>1.0.0</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>18.0</version>
</dependency>
前端点击事件
因为我存的filepath是带文件类型,文件类型并没有单独存,所以我是把id和文件路径写在一起了,因为是在js里面拼接的html代码,所以暂时不知道怎么可以传两个参数,就拼接在一起了
function showAllByPage(pageNo) {
var fileName=$('#search_filename').val();
var wordtype=2;//2:月报
$.ajax({
type: "post",
url: contentp_path+"/reportRecord/data.do",
data: {pageNo:pageNo,fileName:fileName,fileType:wordtype},
dataType: "json",
success: function (result) {
var pages = result.pages;
var pageNo = result.pageNo;
page_curr = pageNo;
var tbody = "";
for (i = 0; i < result.datas.length; i++) {
var date_curr = new Date();
date_curr.setTime(result.datas[i].uploadtime);
var uptimes = date_curr.format('yyyy-MM-dd HH:mm:ss');
var auth_script_curr=
"<a type='submit' class=\"btn btn-info\" οnclick=\"onlineBrowse('"+result.datas[i].id+","+result.datas[i].filepath+"')\" href=\"javascript:;\">在线浏览</a> "+
"<a type='submit' class=\"btn btn-info\" οnclick=\"downloadFile('"+result.datas[i].filepath+"')\" href=\"javascript:;\">下载</a> "+
"<a type='submit' class=\"btn btn-info\" οnclick=\"deleteReport('"+result.datas[i].id+"')\" href=\"javascript:;\">删除</a>";
var tr= "<tr>"+
"<td><label class=\"i-checks m-b-none\">"+
"<input type=\"checkbox\" name=\"post[]\" value='"+result.datas[i].id+"' οnclick='check_ids(this);'/>"+
"<i></i></label></td>" +
"<td>"+result.datas[i].filename+"</td>" +
"<td><span class=\"text-ellipsis\">"+uptimes+"</span></td>"+
"<td>"+auth_script_curr+"</td>"+
"</tr>";
tbody += tr;
}
if(tbody==''){
tbody='<tr><td colspan="8" style="text-align:center;">暂无数据</td></tr>';
$("#datasbody").html(tbody);
$("#pages").html('');
}else{
$("#datasbody").html(tbody);
generatorPage(pageNo,pages,'pages');
}
}
});
}
//在线预览
function onlineBrowse(idAndfilename) {
var wordtype=2;//2:月报
var id=idAndfilename.substring(0,idAndfilename.indexOf(","));
var suffix=idAndfilename.substring(idAndfilename.lastIndexOf(".")+1);
//如果对应的是文档
if(suffix == 'doc' || suffix == 'docx' || suffix == 'txt'|| suffix == 'pdf'){
//打开跳转页面
window.open( contentp_path+'/onlineBrowse/index.do?id='+id,"_blank");
//location.href=contentp_path+"/onlineBrowse/obfile.do?params="+params+"&fname="+filename+"&wordtype="+wordtype;
} else{
layer.msg('当前文件类型暂不支持预览!', {icon: 2,time:1000});
}
}
页面跳转中间Action以及最终的预览处理接口
package com.wms;
import com.wms.reportrecord.entity.reportrecord;
import com.wms.reportrecord.service.reportrecordMapper;
import com.wms.util.ToPDFUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
/***
* 下载控制
*/
@Controller
@RequestMapping(value = "onlineBrowse")
@PropertySource({ "classpath:appconfig.properties" })
public class onlineBrowse {
@Autowired
private reportrecordMapper reportMapper;
@Value(value = "${downloadpath}")
private String onlineBrowsepath;
@RequestMapping(value = "/index", method = RequestMethod.GET)
public ModelAndView collectionSiteFrontIndex(Integer id) {
ModelAndView view = new ModelAndView();
view.addObject("id",id);
view.setViewName("/front/common/onlinePreview");
return view;
}
/**
* 在线浏览
*/
@RequestMapping(value = "obfile")
public void onlineBrowse(HttpServletResponse response, HttpServletRequest request, HttpSession session,
@RequestParam(value = "id")Integer id) throws IOException {
reportrecord report=reportMapper.selectByPrimaryKey(id);
String folder = "monthReport";//月报
if (report.getFiletype() == 1)//周报
folder = "weekReport";
String filePath = onlineBrowsepath + "/" + folder + "/" ;
String fname=report.getFilepath();
// 读取pdf文件的路径
String pdfPath="";
// 将对应的后缀转换成小写
String lastSuffix=fname.substring(fname.lastIndexOf(".")+1,fname.length()).toLowerCase();
String fileName=fname;
//读取文件内容,获取文件存储的路径
String orgPath = filePath + fname;//文件存放路径
// 生成pdf文件的路径
String toPath = filePath + "pdf/";
// 判断对应的pdf是否存在,不存在则创建
File file = new File(toPath);
if (!file.exists()) {
file.mkdirs();
}
// doc类型
if (lastSuffix.equals("pdf")) {
// pdf 文件不需要转换,直接从上传文件路径读取即可
pdfPath=orgPath;
} else {
// 转换之后的pdf文件
String newName=fileName.replace(lastSuffix,"pdf");;
File newFile = new File( toPath+"/"+newName);
// 如果转换之后的文件夹中有转换后的pdf文件,则直接从里面读取即可
if (newFile.exists()) {
pdfPath =toPath+"/"+newName;
}else {
pdfPath = new ToPDFUtil().wordToPdf(fileName,orgPath, toPath,lastSuffix);
}
}
// 读取文件流上
FileInputStream fis = new FileInputStream(pdfPath);
//设置返回的类型
response.setContentType("application/pdf");
FileInputStream in = new FileInputStream(pdfPath);
OutputStream out = response.getOutputStream();
byte[] b = new byte[512];
while ((in.read(b))!=-1) {
out.write(b);
}
out.flush();
in.close();
out.close();
}
}
word转pdf的处理代码
package com.wms.util;
import com.documents4j.api.DocumentType;
import com.documents4j.api.IConverter;
import com.documents4j.job.LocalConverter;
import java.io.*;
public class ToPDFUtil {
/**
* 将之前对应的word文件转换成pdf,然后预览pdf文件
*/
public String wordToPdf(String orgFile,String orgPath, String toPath, String suffix ){
// 转换之后的pdf文件
String targetFile=orgFile.replace(suffix,"pdf");
File inputWord = new File(orgPath);
File outputFile = new File(toPath+targetFile);
try {
InputStream docxInputStream = new FileInputStream(inputWord);
OutputStream outputStream = new FileOutputStream(outputFile);
IConverter converter = LocalConverter.builder().build();
if(suffix.equals("doc")){
converter.convert(docxInputStream).as(DocumentType.DOC).to(outputStream).as(DocumentType.PDF).execute();
} else if(suffix.equals("docx")){
converter.convert(docxInputStream).as(DocumentType.DOCX).to(outputStream).as(DocumentType.PDF).execute();
} else if(suffix.equals("txt")){
converter.convert(docxInputStream).as(DocumentType.TEXT).to(outputStream).as(DocumentType.PDF).execute();
}
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
return toPath+targetFile;
}
}
预览页面jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html lang="en">
<head>
<base href="<%=basePath%>">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>科技社团发展跟踪系统</title>
<!--引入pdfobject.js-->
<script src="<%=basePath %>pages/front/images/js/pdfobject.js"></script>
<script src="<%=basePath %>pages/console/js/common/rootPath.js"></script>
<script src="<%=basePath %>pages/console/images/js/jquery-2.1.1.min.js"></script>
<script src="/coalminehwaui/static/js/jquery-3.1.1.min.js"></script>
<script src="/coalminehwaui/static/js/project/common.js"></script>
<script src="<%=basePath %>pages/front/images/js/toastr.min.js"></script>
<!-- slimscroll把任何div元素包裹的内容区加上具有好的滚动条-->
<script src="<%=basePath %>pages/front/images/js/jquery.slimscroll.min.js"></script>
<script>
'use strict';
$(function () {
LookPlan.getUrlString();
LookPlan.init();
});
var LookPlan = new Object({
getUrlString:function(name){
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
var r = window.location.search.substr(1).match(reg);
if (r != null) return unescape(r[2]);
return '';
},
init:function() {
var id =LookPlan.getUrlString('id');
var src='/dshow/onlineBrowse/obfile.do?id='+id;
setTimeout(function () {
document.getElementById("pdf").src=src;
}, 500);
}
});
</script>
</head>
<body>
<div class="container">
<div>
<div >
<iframe style="width: 100%;height: 1000px;" src="" id="pdf"></iframe>
</div>
</div>
</div>
</body>
</html>