不知觉就过了这个久了,继上篇java实现文件上传下载后,今天给大家分享一篇java实现的对office文件预览功能。

相信大家在平常的项目中会遇到需要对文件实现预览功能,这里不用下载节省很多事。大家请擦亮眼睛下面直接上代码了。

步骤:

    1.需要下载openoffice插件,这是一款免费的工具,所以我们选择他。

2.需要pdf.js文件

这两个工具文件我下面会给地址需要的可以去下载

 https://download.csdn.net/download/dsn727455218/10474679 这是下载地址

不多说废话了,直接上代码了。

java预览工具类:

 

package com.file.utils;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties; import org.apache.log4j.Logger; import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;
import com.lowagie.text.Document;
import com.lowagie.text.Image;
import com.lowagie.text.PageSize;
import com.lowagie.text.pdf.PdfWriter; /**
* doc docx格式转换
*/
public class DocConverter {
private static final Logger logger = Logger.getLogger(DocConverter.class);
private static final int environment = 1;// 环境 1:windows 2:linux
private String fileString;// (只涉及pdf2swf路径问题)
private String outputPath = "";// 输入路径 ,如果不设置就输出在默认的位置
private String fileName;
private static String[] docFileLayouts = { ".txt", ".doc", ".docx", ".wps", ".xls", ".xlsx", ".et", ".ppt", ".pptx",
".dps" };//office办公软件格式
private static String[] imgFileLayouts = { ".jpg", ".gif", ".jpeg", ".png", ".bmp" };//图片格式
private static String[] pdfFileLayouts = { ".pdf" };//pdf格式
private File imgFile;
private File oldFile;//原文件
private File pdfFile;
private File swfFile;
private File docFile; private String pdf2swfPath; /**
* 可预览的文件格式
*
* @param baseAddition
*/
public static String getPreviewFileExt() {
List list = new ArrayList(Arrays.asList(docFileLayouts));
list.addAll(Arrays.asList(imgFileLayouts));
list.addAll(Arrays.asList(pdfFileLayouts));
Object[] c = list.toArray();
//System.out.println(Arrays.toString(c));
return Arrays.toString(c);
} public DocConverter(String fileurl) {
ini(fileurl);
} /**
* 重新设置file
*
* @param fileString
*/
public void setFile(String fileurl) {
ini(fileurl);
} /**
* 初始化
*
* @param fileString
*/
private void ini(String fileurl) {
this.fileString = fileurl;
fileName = fileString.substring(0, fileString.lastIndexOf("."));
int type = fileString.lastIndexOf(".");
String typeStr = fileString.substring(type);
if (Arrays.toString(docFileLayouts).contains(typeStr)) {
docFile = new File(fileString);
} else if (Arrays.toString(imgFileLayouts).contains(typeStr)) {
imgFile = new File(fileString);
} else if (Arrays.toString(pdfFileLayouts).contains(typeStr)) {
oldFile = new File(fileString);
}
pdfFile = new File(fileName + ".pdf");
} /**
* 转为PDF
*
* @param file
*/
private void doc2pdf() throws Exception {
if (docFile != null && docFile.exists()) {
if (!pdfFile.exists()) {
OpenOfficeConnection connection = new SocketOpenOfficeConnection("localhost", 8100);
try {
connection.connect();
DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
converter.convert(docFile, pdfFile);
// close the connection
connection.disconnect();
logger.info("****pdf转换成功,PDF输出:" + pdfFile.getPath() + "****");
} catch (java.net.ConnectException e) {
e.printStackTrace();
logger.info("****swf转换器异常,openoffice服务未启动!****");
throw e;
} catch (com.artofsolving.jodconverter.openoffice.connection.OpenOfficeException e) {
e.printStackTrace();
logger.info("****swf转换器异常,读取转换文件失败****");
throw e;
} catch (Exception e) {
e.printStackTrace();
throw e;
}
} else {
logger.info("****已经转换为pdf,不需要再进行转化****");
}
} else {
logger.info("****swf转换器异常,需要转换的文档不存在,无法转换****");
}
} /**
* 将图片转换成pdf文件 imgFilePath 需要被转换的img所存放的位置。
* 例如imgFilePath="D:\\projectPath\\55555.jpg"; pdfFilePath 转换后的pdf所存放的位置
* 例如pdfFilePath="D:\\projectPath\\test.pdf";
*
* @param image
* @return
* @throws IOException
* @throws Exception
*/ private void imgToPdf() throws Exception {
if (imgFile != null && imgFile.exists()) {
if (!pdfFile.exists()) {
Document document = new Document();
FileOutputStream fos = null;
try {
fos = new FileOutputStream(pdfFile.getPath());
PdfWriter.getInstance(document, fos); // 添加PDF文档的某些信息,比如作者,主题等等
//document.addAuthor("arui");
//document.addSubject("test pdf.");
// 设置文档的大小
document.setPageSize(PageSize.A4);
// 打开文档
document.open();
// 写入一段文字
// document.add(new Paragraph("JUST TEST ..."));
// 读取一个图片
Image image = Image.getInstance(imgFile.getPath());
float imageHeight = image.getScaledHeight();
float imageWidth = image.getScaledWidth();
int i = 0;
while (imageHeight > 500 || imageWidth > 500) {
image.scalePercent(100 - i);
i++;
imageHeight = image.getScaledHeight();
imageWidth = image.getScaledWidth();
System.out.println("imageHeight->" + imageHeight);
System.out.println("imageWidth->" + imageWidth);
} image.setAlignment(Image.ALIGN_CENTER);
// //设置图片的绝对位置
// image.setAbsolutePosition(0, 0);
// image.scaleAbsolute(500, 400);
// 插入一个图片
document.add(image);
} catch (Exception de) {
System.out.println(de.getMessage());
}
document.close();
fos.flush();
fos.close();
}
}
} /**
* 转换成 pdf
*/
@SuppressWarnings("unused")
private void pdfTopdf() throws Exception {
Runtime r = Runtime.getRuntime();
if (!pdfFile.exists() && oldFile.exists()) {
if (environment == 1) {// windows环境处理
try {
int bytesum = 0;
int byteread = 0;
File oldfile = new File(oldFile.getPath());
if (oldfile.exists()) { // 文件存在时
InputStream inStream = new FileInputStream(oldFile.getPath()); // 读入原文件
FileOutputStream fs = new FileOutputStream(pdfFile.getPath());
byte[] buffer = new byte[1444];
int length;
while ((byteread = inStream.read(buffer)) != -1) {
bytesum += byteread; // 字节数 文件大小
System.out.println(bytesum);
fs.write(buffer, 0, byteread);
}
inStream.close();
}
} catch (Exception e) {
logger.info("复制单个文件操作出错");
e.printStackTrace(); }
} else if (environment == 2) {// linux环境处理 }
} else {
logger.info("****pdf不存在,无法转换****");
}
} /**
* 转换成 swf
*/
@SuppressWarnings("unused")
private void pdf2swf() throws Exception {
Runtime r = Runtime.getRuntime();
if (!swfFile.exists()) {
if (pdfFile.exists()) {
if (environment == 1) {// windows环境处理
try {
// 从配置文件获取swfFile.exe 安装路径
InputStream in = DocConverter.class.getClassLoader()
.getResourceAsStream("parameters/flow/pdf2swfPath.properties");
Properties config = new Properties();
try {
config.load(in);
in.close();
} catch (IOException e) {
System.err.println("No AreaPhone.properties defined error");
} if (config != null && config.getProperty("pdf2swfPath") != null) {
pdf2swfPath = config.getProperty("pdf2swfPath").toString();
} Process p = r
.exec(pdf2swfPath + " " + pdfFile.getPath() + " -o " + swfFile.getPath() + " -T 9");
swfFile = new File(swfFile.getPath());
//System.out.print(loadStream(p.getInputStream()));
//System.err.print(loadStream(p.getErrorStream()));
//System.out.print(loadStream(p.getInputStream()));
System.err.println("****swf转换成功,文件输出:" + swfFile.getPath() + "****");
/*
* if (pdfFile.exists()) { pdfFile.delete(); }
*/ } catch (IOException e) {
e.printStackTrace();
throw e;
}
} else if (environment == 2) {// linux环境处理
try {
Process p = r.exec("pdf2swf " + pdfFile.getPath() + " -o " + swfFile.getPath() + " -T 9");
//System.out.print(loadStream(p.getInputStream()));
//System.err.print(loadStream(p.getErrorStream()));
System.err.println("****swf转换成功,文件输出:" + swfFile.getPath() + "****");
/*
* if (pdfFile.exists()) { pdfFile.delete(); }
*/
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
} else {
System.out.println("****pdf不存在,无法转换****");
}
} else {
System.out.println("****swf已经存在不需要转换****");
}
} static String loadStream(InputStream in) throws IOException { int ptr = 0;
in = new BufferedInputStream(in);
StringBuffer buffer = new StringBuffer(); while ((ptr = in.read()) != -1) {
buffer.append((char) ptr);
} return buffer.toString();
} /**
* 转换主方法
*/
@SuppressWarnings("unused")
public boolean conver() { if (pdfFile.exists()) {
logger.info("****swf转换器开始工作,该文件已经转换为swf****");
return true;
} if (environment == 1) {
logger.info("****swf转换器开始工作,当前设置运行环境windows****");
} else {
logger.info("****swf转换器开始工作,当前设置运行环境linux****");
}
try {
doc2pdf();
imgToPdf();
pdfTopdf();
//pdf2swf();
} catch (Exception e) {
e.printStackTrace();
return false;
} if (pdfFile.exists()) {
return true;
} else {
return false;
}
} public static void main(String[] args) {
// 调用转换类DocConverter,并将需要转换的文件传递给该类的构造方法
/*
* DocConverter d = new
* DocConverter("C:/Users/Administrator/Desktop/工作动态第19期.pdf"); //
* 调用conver方法开始转换,先执行doc2pdf()将office文件转换为pdf;再执行pdf2swf()将pdf转换为swf;
* d.conver(); // 调用getswfPath()方法,打印转换后的swf文件路径
* System.out.println(d.getswfPath());
*/
} /**
* 返回文件路径
*
* @param s
*/
public String getPdfName() {
//if (swfFile.exists()) {
String tempString = pdfFile.getName();
//tempString = tempString.replaceAll("\\\\", "/");
return tempString;
/*
* } else { return ""; }
*/ } /**
* 设置输出路径
*/
public void setOutputPath(String outputPath) {
this.outputPath = outputPath;
if (!outputPath.equals("")) {
String realName = fileName.substring(fileName.lastIndexOf("/"), fileName.lastIndexOf("."));
if (outputPath.charAt(outputPath.length()) == '/') {
swfFile = new File(outputPath + realName + ".swf");
} else {
swfFile = new File(outputPath + realName + ".swf");
}
}
} }

是不是觉得很简单,这里需要说明的一个问题是,连接openoffice服务如果用:

OpenOfficeConnection connection = new SocketOpenOfficeConnection(8100);
OpenOfficeConnection connection = new SocketOpenOfficeConnection("localhost", 8100);

第一种会报错,连接失败,具体错误代码我就不贴,不信可以试试看,所以我们选择第二种连接方式。

aciton中调用:

@ResponseBody
@RequestMapping(value = "/onlinefile")
public void onlinefile(Logonlog logonlog, FileList user, HttpServletRequest request, HttpServletResponse response,
HttpSession session, String msg) throws Exception {
response.setHeader("Access-Control-Allow-Origin", "*");
String fileurl = request.getParameter("fileurl");
if ("".equals(Tools.RmNull(fileurl))) {
msg = StatusCode.PARAMETER_NULL;
} else {
String filePath = request.getSession().getServletContext().getRealPath("/") + "\\upload\\";
DocConverter d = new DocConverter(filePath + fileurl);//调用的方法同样需要传文件的绝对路径
d.conver();//d.getPdfName()是返回的文件名 需要加上项目绝对路径 不然会以相对路径访问资源
session.setAttribute("fileurl", "/filemanagement/upload/" + d.getPdfName());//设置文件路径
response.sendRedirect("/filemanagement/file/showinfo.jsp");//跳转到展示页面
}
}

jsp页面:

<%@ page language="java" import="java.util.*" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ page language="java" import="javax.servlet.http.HttpSession"%>
<%
String fileurl=session.getAttribute("fileurl").toString();
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>预览</title>
</head>
<body>
<!--内容-->
<div class="mim_content">
<iframe width="100%"height="700px" src="/filemanagement/online/viewer.html?file=${fileurl}"></iframe>
</div>
</body>
</html>

这里我们是需要的文件传到pdf.js文件里面才能展示的:

viewer.html 是一个官方文件 下载来用就可以

我就不贴代码,需要文件的可以去我的下载地址下载文件以及工具包

https://download.csdn.net/download/dsn727455218/10474679 这是下载地址

实现文件的预览其实就是这么的简单,这里需要给大家说明一点,需要先启动openoffice服务,不然会报错的。

当然还有一些其他的方式 比如 poi,以及使用office web 365第三方服务 但是这是收费的有钱任性的可以试试。;

到这里已经完成了对文件的预览功能,如有需要可以加我Q群【308742428】大家一起讨论技术。

后面会不定时为大家更新文章,敬请期待。

如果对你有帮助,请打赏一下!!!

  

  

  

java实现office文件预览的更多相关文章

  1. .net 实现Office文件预览 Word PPT Excel 2015-01-23 08:47 63人阅读 评论(0) 收藏

    先打个广告: .Net交流群:252713569 本人QQ :524808775 欢迎技术探讨, 近期公司要求上传的PPT和Word都需要可以在线预览.. 小弟我是从来没有接触过这一块的东西 感觉很棘 ...

  2. .net 实现Office文件预览,word文件在线预览、excel文件在线预览、ppt文件在线预览

    转自源地址:http://www.cnblogs.com/GodIsBoy/p/4009252.html,有部分改动 使用Microsoft的Office组件将文件转换为PDF格式文件,然后再使用pd ...

  3. js调用本地office打开服务器的office文件预览

    本来是想做成直接在网页上在线预览office文件的,但是找了好多,要不是收费,要不就是要调用别人的API不安全,所以纠结了好久还是用调用本地的office预览office文件. 废话不多说,那么怎么调 ...

  4. 手把手教你用 Spring Boot搭建一个在线文件预览系统!支持ppt、doc等多种类型文件预览

    昨晚搭建环境都花了好一会时间,主要在浪费在了安装 openoffice 这个依赖环境上(Mac 需要手动安装). 然后,又一步一步功能演示,记录,调试项目,并且简单研究了一下核心代码之后才把这篇文章写 ...

  5. Java实现web在线预览office文档与pdf文档实例

    https://yq.aliyun.com/ziliao/1768?spm=5176.8246799.blogcont.24.1PxYoX 摘要: 本文讲的是Java实现web在线预览office文档 ...

  6. java 文件转成pdf文件 预览

    一.前端代码 //预览功能 preview: function () { //判断选中状态 var ids =""; var num = 0; $(".checkbox& ...

  7. Office在线预览及PDF在线预览的实现方式史上最全大集合

    Office在线预览及PDF在线预览的实现方式大集合 一.服务器先转换为PDF,再转换为SWF,最后通过网页加载Flash预览 微软方:利用Office2007以上版本的一个PDF插件SaveAsPD ...

  8. 关于pc端 app端pdf,word xls等文件预览的功能

    第一种用H5标签<iframe>标签实现 返回的文件类型,文件流,文件流返回必须在设置 contentType对应的Mime Type, 返回文件的物理位置. 已经实测可以支持的文件类型 ...

  9. 如何利用Python实现Office在线预览

    目前,市场对于Office在线预览功能的需求是很大的.对于我们用户本身来说,下载Office文件后再实现预览是极其不方便的,何况还有一些不能打开的专业文档.压缩文件等.此时,能提供在线预览服务的软件就 ...

随机推荐

  1. 2018.12.30 bzoj3028: 食物(生成函数)

    传送门 生成函数模板题. 我们直接把每种食物的生成函数列出来: 承德汉堡:1+x2+x4+...=11−x21+x^2+x^4+...=\frac 1{1-x^2}1+x2+x4+...=1−x21​ ...

  2. linux 修改yum 为阿里云源

    为了加快yum的下载速度,我们可以讲yum源指向阿里云的资源. 操作方法: 1.备份系统的yum源 mv /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repo ...

  3. MFC连接MySQL数据库方法

    MFC连接数据库的三种方法: 1.ODBC(开放式数据互联) 2.OLEDB与ADO 3.用mysql为C语言提供的接口

  4. Oracle中根据当前时间和活动类型去数据库查询活动id

    活动类型默认是1,代表邀请好友 select * from t_invite_activityinfo twhere sysdate >= t.begintime and sysdate< ...

  5. 时间控件My97简单用法

    my97的用法很是简单,项目中用到,查了资料才找到的,简单使用,记一下,方便查阅. 1.添加依赖. <script language="javascript" type=&q ...

  6. IP之ALTIOBUF仿真

    这里实现了差分转单端的功能. 问题:差分信号的电平是怎样的?如果像平常一样不设置Pin Planner中的电平的话,编译会报错. 在Pin Planner中做了如下设置: `timescale 1 n ...

  7. 1101 Quick Sort

    There is a classical process named partition in the famous quick sort algorithm. In this process we ...

  8. Ng第十五课:异常检测(Anomaly Detection)

    15.1  问题的动机 15.2  高斯分布 15.3  算法 15.4  开发和评价一个异常检测系统 15.5  异常检测与监督学习对比 15.6  选择特征 15.7  多元高斯分布(可选) 15 ...

  9. Northwind测试学习用数据库

    下载地址: https://northwinddatabase.codeplex.com/

  10. SurfaceView+MediaPlayer播放视频

    SurfaceView拥有独立的绘图表面,因此SurfaceView的UI就可以在一个独立的线程中进行行绘制.又由于不占用主线程资源,SurfaceView一方面可以实现复杂而高效的UI,另一方面又不 ...