Java实现在线预览功能
java实现在线预览功能,需要用到 jacob.dll jacob.jar 预览pdf所需js pdfobject.min.js
将上传文件转为pdf保存。
<div class="control-group">
<label class="control-label">文件:</label>
<div class="controls">
<input type="file" name="file" id="ck_attach_path" style="width:98%;"/>
</div>
</div>
后台保存文件并将文件转换为pdf
@RequiresPermissions("ha01:haHyjhb:edit")
@RequestMapping(value = "save")
public String save(HaHyjhb haHyjhb, @RequestParam MultipartFile file,Model model, RedirectAttributes redirectAttributes,HttpServletRequest request, HttpServletResponse response) throws IOException, ParseException { haHyjhb.setBh(hybh); String xdlj = request.getSession().getServletContext().getRealPath("userfiles")+"\\hy"+haHyjhb.getLx()+"\\"+dateStr+"\\"+hybh+"\\"; String path = "";
if(!file.isEmpty()){ HaHyzlb haHyzlb = new HaHyzlb();
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");//设置日期格式
String filename= df.format(new Date()); // 保存在服务器的随机文件名 //材料编号
haHyzlb.setClhb(filename);
haHyzlb.setHybh(hybh); xdlj=xdlj.replaceAll("\\\\", "/");
haHyzlb.setLj(xdlj);
haHyzlb.setCllx("0"); String aa[]=file.getOriginalFilename().split("[.]");
String fileName =filename+"."+aa[aa.length-1]; haHyzlb.setClywjm(file.getOriginalFilename());
haHyzlb.setClmc(fileName);
//保存文件
publicUtils.saveFile(file, xdlj,filename, request, response);
haHyzlbService.save(haHyzlb); }else{
request.setAttribute("msg", "未选择需上传的文件");
} haHyjhbService.save(haHyjhb);
addMessage(redirectAttributes, "保存会议计划成功");
} return "redirect:"+Global.getAdminPath()+"/ha01/haHyjhb/?repage";
}
public static void saveFile(@RequestParam MultipartFile file,String xdlj,String filename, HttpServletRequest request, HttpServletResponse response) { String path = ""; String pdfname= filename + ".pdf"; // 装换成pdf文件的名称
String refilename= ""; // 上传文件的名称 if(!file.isEmpty()){
//获取上传文件的原名称
refilename=file.getOriginalFilename();
String aa[]=refilename.split("[.]");
filename=filename+"."+aa[aa.length-1];
xdlj=xdlj.replaceAll("\\\\", "/");
File fpath = new File(xdlj); if(!fpath.exists()){
fpath.mkdirs();
}
try {
MultipartFile mfile = file; if(mfile!=null){
File localFile = new File(xdlj+filename); path = localFile.getPath();
try {
mfile.transferTo(localFile);//将上传文件写到服务器上指定的文件
ToPDF top=new ToPDF();
top.convert2PDF(xdlj+filename, xdlj+pdfname); } catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
} catch (Exception e) {
e.printStackTrace();
request.setAttribute("msg", refilename+"上传失败");
}
} else{
request.setAttribute("msg", "未选择需上传的文件");
}
}
转换pdf工具类
package com.thinkgem.jeesite.modules.bc.bc01.web; import java.io.File; import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComFailException;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch; public class ToPDF {
private static final int wdFormatPDF = 17;
private static final int xlTypePDF = 0;
private static final int ppSaveAsPDF = 32;
private static final int msoTrue = -1;
private static final int msofalse = 0; /*jacob配置
* 把jacob.dll放入 Java\jdk1.5.0_06\jre\bin目录下.
把jacob.jar放入 Java\jdk1.5.0_0\jre\lib\ext*/
//直接调用这个方法即可
public boolean convert2PDF(String inputFile, String pdfFile) {
String suffix = getFileSufix(inputFile);
File file = new File(inputFile);
if(!file.exists()){
System.out.println("文件不存在!");
return false;
}
if(suffix.equals("pdf")){
System.out.println("PDF not need to convert!");
return false;
}
if(suffix.equals("doc")||suffix.equals("docx")||suffix.equals("txt")){
return word2PDF(inputFile,pdfFile);
}else if(suffix.equals("ppt")||suffix.equals("pptx")){
return ppt2PDF(inputFile,pdfFile);
}else if(suffix.equals("xls")||suffix.equals("xlsx")){
return excel2PDF(inputFile,pdfFile);
}else{
System.out.println("文件格式不支持转换!");
return false;
}
}
public static String getFileSufix(String fileName){
int splitIndex = fileName.lastIndexOf(".");
return fileName.substring(splitIndex + 1);
}
public boolean word2PDF(String inputFile,String pdfFile){
ActiveXComponent app = null;
Dispatch doc = null;
boolean result=true;
try{
//打开word应用程序
app = new ActiveXComponent("Word.Application");
//设置word不可见
app.setProperty("Visible", false);
//获得word中所有打开的文档,返回Documents对象
Dispatch docs = app.getProperty("Documents").toDispatch();
//调用Documents对象中Open方法打开文档,并返回打开的文档对象Document
doc = Dispatch.call(docs,
"Open",
inputFile,
false,
true
).toDispatch(); Dispatch.call(doc,
"ExportAsFixedFormat",
pdfFile,
wdFormatPDF //word保存为pdf格式宏,值为17
); result= true;
}catch(Exception e){
result= false;
}finally {
if (doc != null) {
Dispatch.call(doc, "Close");
}
if (app != null) {
app.invoke("Quit");
}
}
return result;
} public boolean excel2PDF(String inputFile,String pdfFile){
ActiveXComponent app = null;
Dispatch excel = null;
boolean result=true;
try{
app = new ActiveXComponent("Excel.Application");
app.setProperty("Visible", false);
Dispatch excels = app.getProperty("Workbooks").toDispatch();
excel = Dispatch.call(excels,
"Open",
inputFile,
false,
true
).toDispatch();
Dispatch.call(excel,
"ExportAsFixedFormat",
xlTypePDF,
pdfFile
);
result= true;
}catch(Exception e){
result= false;
}finally {
if (excel != null) {
Dispatch.call(excel, "Close");
}
if (app != null) {
app.invoke("Quit");
}
}
return result;
} public boolean ppt2PDF(String srcFilePath, String pdfFilePath){
ActiveXComponent app = null;
Dispatch ppt = null;
boolean result=true;
try {
ComThread.InitSTA();
app = new ActiveXComponent("PowerPoint.Application");
Dispatch ppts = app.getProperty("Presentations").toDispatch(); // 因POWER.EXE的发布规则为同步,所以设置为同步发布
ppt = Dispatch.call(ppts, "Open", srcFilePath, true,// ReadOnly
true,// Untitled指定文件是否有标题
false// WithWindow指定文件是否可见
).toDispatch(); Dispatch.call(ppt, "SaveAs", pdfFilePath, 32); //ppSaveAsPDF为特定值32 result=true; // set flag true;
} catch (ComFailException e) {
result=false;
} catch (Exception e) {
result=false;
} finally {
if (ppt != null) {
Dispatch.call(ppt, "Close");
}
if (app != null) {
app.invoke("Quit");
}
ComThread.Release();
}
return result;
}
}
预览文件
<c:if test="${haHyjhb.cllist ne null and haHyjhb.cllist.size() ne 0}">
</br ><h4>会议文件列表</h4></br >
<table id="contentTable" class="table table-striped table-bordered table-condensed">
<thead>
<tr>
<th>文件名</th>
<th>预览</th>
</tr>
</thead>
<tbody>
<c:forEach items="${haHyjhb.cllist}" var="haHyjhb">
<tr>
<td>${haHyjhb.clywjm }</td>
<td><a href="javascript:void(0);" onclick="filescan('${haHyjhb.id}')">预览</a></td>
</tr>
</c:forEach>
</tbody>
</table>
</c:if>
function filescan(fileid){
top.$.jBox.open("iframe:${ctx}/ha01/haHyjhb/scan?id="+fileid, "文件预览",800,$(top.document).height()-100,{
buttons:{"确定":"ok", "关闭":true}, submit:function(v, h, f){ }, loaded:function(h){
$(".jbox-content", top.document).css("overflow-y","hidden");
}, closed:function (){
}
});
}
<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="/WEB-INF/views/include/taglib.jsp"%>
<html>
<head>
<title>资料信息管理</title> <style type="text/css">
html,body,#content{
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
</style>
<script type="text/javascript">
window.onload = function (){ //项目名称
var filepath="${pageContext.request.contextPath}/"+"${saMyclbClxx.lj}".split("/dxzjzx_wz/")[1];
var name="${saMyclbClxx.clmc}"; var a=name.split(".");
var hzm=a[a.length-1];//后缀名
var wjm=name.split("."+hzm)[0];//文件名 if(hzm=="txt"||hzm=="doc"||hzm=="docx"||hzm=="xls"||hzm=="xlsx"||hzm=="ppt"||hzm=="pptx"||hzm=="pdf"){
filepath = filepath+wjm+".pdf"; PDFObject.embed(filepath, "#content" );
//var success = new PDFObject({ url:filepath ,pdfOpenParams: { scrollbars: '0', toolbar: '0', statusbar: '0'}}).embed("content1");
}else if(hzm=="png"||hzm=="jpeg"||hzm=="gif"||hzm=="jpg"){
$("#content").html("<img style='background-size:contain|cover;width:100%;height: auto;' src='"+filepath+name+"' id='ylimg'/>");
}else if(hzm=="wav"||hzm=="mp3"||hzm=="midi"||hzm=="wma"||hzm=="swf"||hzm=="flv"||hzm=="wmv"||hzm=="asf"||hzm=="asx"||hzm=="mid"||hzm=="rm"||hzm=="rmvb"||hzm=="mp4"||hzm=="mov"||hzm=="avi"||hzm=="ram"){
$("#content").html("<video src='"+filepath+name+"' controls='controls'></video>");
}else{
alert("该文件格式不支持预览");
}
}
</script>
</head>
<body>
<ul class="nav nav-tabs">
</ul><br/>
<form:form id="inputForm" modelAttribute="saSqmyxxb" action="${ctx}/sa01/saSqmyxxb/save" method="post" class="form-horizontal">
<sys:message content="${message}"/>
<div id="content"></div>
</form:form> <script type="text/javascript" src='${ctxStatic}/js/pdfobject.min.js'></script> </body>
</html>
Java实现在线预览功能的更多相关文章
- java实现在线预览--poi实现word、excel、ppt转html
java实现在线预览 - -之poi实现word.excel.ppt转html 简介 java实现在线预览功能是一个大家在工作中也许会遇到的需求,如果公司有钱,直接使用付费的第三方软件或者云在线预览服 ...
- java实现在线预览 - -之poi实现word、excel、ppt转html
简介 java实现在线预览功能是一个大家在工作中也许会遇到的需求,如果公司有钱,直接使用付费的第三方软件或者云在线预览服务就可以了,例如永中office.office web 365(http://w ...
- Java实现office文档与pdf文档的在线预览功能
最近项目有个需求要java实现office文档与pdf文档的在线预览功能,刚刚接到的时候就觉得有点难,以自己的水平难以在三四天做完.压力略大.后面查找百度资料.以及在同事与网友的帮助下,四天多把它做完 ...
- svn服务支持网页显示并增加在线预览功能,支持视频在线播放
1.svn服务器支持网页显示 VisualSVN Server是一个非常不错的SVN Server程序,方便,直观,用户管理也异常方便.不过,它本身并没有提供在线修改密码的功能.由于在实际使用过程中, ...
- Java实现在线预览–openOffice实现
实现逻辑有两种: 一.利用jodconverter(基于OpenOffice服务)将文件(.doc..docx..xls..ppt)转化为html格式. 二.利用jodconverter(基于Open ...
- Java实现在线预览--openOffice实现
简介 之前有写了poi实现在线预览的文章,里面也说到了使用openOffice也可以做到,这里就详细介绍一下. 我的实现逻辑有两种: 一.利用jodconverter(基于OpenOffice服务)将 ...
- word,excel,ppt在线预览功能
我们在开发web项目时,尤其类似oa功能时总会遇到上传附件并在线预览的功能,发现一款api比较好使,下面简单介绍一下. 微软官网本身提供了在线预览的API 首先将要预览的文档转成.docx,.xlsx ...
- kkFileView对接svn服务完成文件在线预览功能
1.需求: 之前在公司内部搭建了svn服务器,给部门存放文档.视频,做成了一个文档服务器来用,随着视频文件太大,每次下载太慢 需要把文件在线打开查看 2.解决: kkFileView https:// ...
- 如何实现QQ附件在线预览功能
方法一:使用 openoffice 的接口把文档转换成html (linux主机或者windows主机): 方法二:使用 一个叫 jacob.jar 的工具,在安装了 office 的windows主 ...
随机推荐
- 1004. Counting Leaves(30)—PAT 甲级
A family hierarchy is usually presented by a pedigree tree. Your job is to count those family member ...
- 各种快速幂(qaq)
今天分享下各种快速幂(有点坑),首先说一下快速幂的原理, 以下以求a的b次方来介绍 [1] 把b转换成二进制数. 该二进制数第i位的权为 例如 11的二进制是1011 11 = 2³×1 + 2 ...
- JavaScript入门学习(2)--进度条
<html> <style type="text/css"> #bar{width:0px; height:20px; background:#ee00ff ...
- ElasticSearch 安装root用户启动失败问题解决
1. 下载ElasticSearch 2.3.3 2. 安装JDK 1.8.0以上版本 3. ElasticSearch 安装时会出现 Exception in thread "main ...
- Centos7.5搭建Hadoop2.8.5完全分布式集群部署
一.基础环境设置 1. 准备4台客户机(VMware虚拟机) 系统版本:Centos7.5 节点配置: 192.168.208.128 --Master 192.168.208.129 --Slave ...
- Microbit蓝芽配对
Microbit蓝芽配对 (Bluetooth Pairing) Microbit 可以像手机或平板与其他蓝芽装置一样,一旦做完第一次配对完就可以使用”蓝芽服务” paired with the mi ...
- 格式化输出%02hhx
每次看到人家的十六进制输出,对齐的很好,ff就显示了,而我的总是0xffffffff.如果是"%02x",是以0补齐2位数,如果超过2位就显示实际的数:"%hhx&quo ...
- Golang Gin 项目包依赖管理 godep 使用
Golang Gin 项目包依赖管理 godep 使用 标签(空格分隔): Go 在按照github.com/tools/godep文档go get完包以后,调整项目结构为$GOPATH/src/$P ...
- j使用数组实现约瑟夫环 java
我们首先来看一下约瑟夫环问题: 给定m个人,m个人围成一圈,在给定一个数n,从m个人中的第一个人每第n个人便将其除去,求被最后一个出去的人的编号. 思路: 建立一个长度为m+1的数组,将其的内容初始化 ...
- 【EXCEL】簡単に重複探し
下記のような表があって.重複があるかどうか探すのが大変と思いますが. 簡単に重複探す方法を紹介します. Step1.重複を探す(例えこちらでは項目)を選択します. Step2.メニューで 条件付き書式 ...