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实现在线预览功能的更多相关文章

  1. java实现在线预览--poi实现word、excel、ppt转html

    java实现在线预览 - -之poi实现word.excel.ppt转html 简介 java实现在线预览功能是一个大家在工作中也许会遇到的需求,如果公司有钱,直接使用付费的第三方软件或者云在线预览服 ...

  2. java实现在线预览 - -之poi实现word、excel、ppt转html

    简介 java实现在线预览功能是一个大家在工作中也许会遇到的需求,如果公司有钱,直接使用付费的第三方软件或者云在线预览服务就可以了,例如永中office.office web 365(http://w ...

  3. Java实现office文档与pdf文档的在线预览功能

    最近项目有个需求要java实现office文档与pdf文档的在线预览功能,刚刚接到的时候就觉得有点难,以自己的水平难以在三四天做完.压力略大.后面查找百度资料.以及在同事与网友的帮助下,四天多把它做完 ...

  4. svn服务支持网页显示并增加在线预览功能,支持视频在线播放

    1.svn服务器支持网页显示 VisualSVN Server是一个非常不错的SVN Server程序,方便,直观,用户管理也异常方便.不过,它本身并没有提供在线修改密码的功能.由于在实际使用过程中, ...

  5. Java实现在线预览–openOffice实现

    实现逻辑有两种: 一.利用jodconverter(基于OpenOffice服务)将文件(.doc..docx..xls..ppt)转化为html格式. 二.利用jodconverter(基于Open ...

  6. Java实现在线预览--openOffice实现

    简介 之前有写了poi实现在线预览的文章,里面也说到了使用openOffice也可以做到,这里就详细介绍一下. 我的实现逻辑有两种: 一.利用jodconverter(基于OpenOffice服务)将 ...

  7. word,excel,ppt在线预览功能

    我们在开发web项目时,尤其类似oa功能时总会遇到上传附件并在线预览的功能,发现一款api比较好使,下面简单介绍一下. 微软官网本身提供了在线预览的API 首先将要预览的文档转成.docx,.xlsx ...

  8. kkFileView对接svn服务完成文件在线预览功能

    1.需求: 之前在公司内部搭建了svn服务器,给部门存放文档.视频,做成了一个文档服务器来用,随着视频文件太大,每次下载太慢 需要把文件在线打开查看 2.解决: kkFileView https:// ...

  9. 如何实现QQ附件在线预览功能

    方法一:使用 openoffice 的接口把文档转换成html (linux主机或者windows主机): 方法二:使用 一个叫 jacob.jar 的工具,在安装了 office 的windows主 ...

随机推荐

  1. nRF5 SDK for Mesh(八) Exploring Mesh APIs using light switch example,使用 灯开关 案例探索BLE mesh 的APIS

    Exploring Mesh APIs using light switch example The light switch example is meant to showcase the API ...

  2. ubuntu 14.04 将窗体button移到右边

    刚刚安装了Ubuntu 14.04,想改动窗体button的位置.但依照曾经的办法发现不行了,在gconftool-->apps中找不到metacity. 多方查找后找到解决方式,例如以下 Ub ...

  3. mysql修改数据表自增步长

    可以修改系统变量 auto_increment_increment mysql> SHOW VARIABLES LIKE 'auto_inc%'; +---------------------- ...

  4. css让不同大小的图片适应div的大小,且不变形。

    做成背景图片 单个 .imgdiv { width: 100px; // 你要的正方形 height: 100px; // 你要的正方形 background-image: url(/your/ima ...

  5. iOS:位置相关(18-03-09更)

    1.定位设置 2.定位页面逻辑 1.定位设置 2.定位页面逻辑 1).第一次进入该VC,在 viewDidLoad 调用刷新页面 refreshLocationView .这时用户还没决定,会刷出“正 ...

  6. nodejs的事件轮询机制

    1.timers定时器阶段 执行定时器到点的回调函数(所有定时器setTimeout / setInterval的回调函数都在这个阶段执行) 2.idle prepare 准备阶段 TCP错误回调 3 ...

  7. jQuery.validate.js表单验证插件

    jQuery.validate.js表单验证插件的使用 效果: 代码: <!DOCTYPE html> <html lang="en"> <head& ...

  8. Linux --- Ubuntu16.04.5 LTS 虚拟机安装后的软件安装基础操作总结

    1. 配置安装源 因为默认是使用Ubuntu官方服务器,国内电脑使用外国服务器较慢,所以需使用国内的服务器(以下清华大学服务器为例). 方法一: (此过程很慢,实在不动就取消吧,加载一部分也够用,以后 ...

  9. js如何获取键盘高度

    在移动端或混合app开发中,js如何获取键盘高度,直接贴上代码吧 input是一个html input 标签 var timer = { id:null, run:function (callback ...

  10. 数据采集与分析的那些事——从数据埋点到AB测试

    作者:网易有数郑栋. 一.为什么企业需要一套完善的用户行为埋点和分析平台 产品初创期间,需要分析天使用户的行为来改进产品,甚至从用户行为中得到新的思路或发现来调整产品方向:产品成长过程,通过对用户行为 ...