最近项目有个需求要java实现office文档与pdf文档的在线预览功能,刚刚接到的时候就觉得有点难,以自己的水平难以在三四天做完。压力略大。后面查找百度资料、以及在同事与网友的帮助下,四天多把它做完。查找资料发现我们要实现的过程就是把office转换成pdf,当然pdf就不用转换了。然后在pdf转换为swf文件,在浏览器实现预览swf文件。整个过程就是这样,看起来很简单,实际操作起来会出现各种问题。下面我就把自己写的这一小功能记录下来。

1、首先我们需要找到可以把office转换成pdf的方法,查找资料发现有openoffice这一软件可以把office转换成pdf,这一软件先下载下来,然后记住自己安装的在那个位置。然后在cmd环境下进入安装目录的program目录,输入打开openoffice的命令:

soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard

输入完成之后在任务管理器可以看见soffice.bin的进程在任务管理器,这一服务就启动成功。当然在代码中转换office2pdf我们还需要一些架包。下载jodconverter-2.2.2架包,然后复制到lib目录下,引入架包就可以了。这个架包有如下包:

有一些项目重复的可以删除,根据实际情况自己处理。

2、我们需要找到转换pdf2swf的方法。查找资料发现swftools这个软件可以把pdf转换成swf文件。把它下下来安装好就可以了。

3、我们需要一个展示swf文件的容器,发现有flexpaper这个插件。而且展示效果还不错。所以我们需要下载这个插件。使用这个插件需要有三个js文件。分别是:jquery.js、flexpaper_flash.js、flexpaper_flash_debug.js。插件的名字是FlexPaperViewer.swf。

整个项目结如下:

准备工作完成下面开始编码.

转换类为DocConverter 的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
package com.cectsims.util;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
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;
/**
 * doc docx格式转换 
 */
public class DocConverter {
    private static final int environment = 1;// 环境 1:Windows 2:Linux
    private String fileString;// (只涉及PDF2swf路径问题)
    private String outputPath = "";// 输入路径 ,如果不设置就输出在默认 的位置
    private String fileName;
    private File pdfFile;
    private File swfFile;
    private File docFile;
    public DocConverter(String fileString) {
        ini(fileString);
        System.out.println("文件路径"+fileString);
    }
    /**
     * * 重新设置file
     *
     * @param fileString
     *            32.
     */
    public void setFile(String fileString) {
        ini(fileString);
    }
    /**
     *  * 初始化
     *
     * @param fileString
     *          
     */
    private void ini(String fileString) {
        this.fileString = fileString;
        fileName = fileString.substring(0, fileString.lastIndexOf("."));
        docFile = new File(fileString);
        pdfFile = new File(fileName+ ".pdf");
        swfFile = new File(fileName+ ".swf");
    }
    /**
     *  转为PDF
     *
     * @param file
     *      
     */
    private void doc2pdf() throws Exception {
        if (docFile.exists()) {
            if (!pdfFile.exists()) {
                OpenOfficeConnection connection = new SocketOpenOfficeConnection(8100);
                try {
                    connection.connect();
                    DocumentConverter converter = new OpenOfficeDocumentConverter(
                            connection);
                    converter.convert(docFile, pdfFile);
                    // close the connection
                    connection.disconnect();
                    System.out.println("****pdf转换成功,PDF输出: "+ pdfFile.getPath() + "****");
                catch (java.net.ConnectException e) {
                    e.printStackTrace();
                    System.out.println("****swf转换器异常,openoffice 服务未启动!****");
                    throw e;
                catch (com.artofsolving.jodconverter.openoffice.connection.OpenOfficeException e) {
                    e.printStackTrace();
                    System.out.println("****swf转换器异常,读取转换文件 失败****");
                    throw e;
                catch (Exception e) {
                    e.printStackTrace();
                    throw e;
                }
            else {
                System.out.println("****已经转换为pdf,不需要再进行转化 ****");
            }
        else {
            System.out.println("****swf转换器异常,需要转换的文档不存在, 无法转换****");
        }
    }
    /** * 转换成 swf */
    @SuppressWarnings("unused")
    private void pdf2swf() throws Exception {
        Runtime r = Runtime.getRuntime();
        if (!swfFile.exists()) {
            if (pdfFile.exists()) {
                if (environment == 1) {// windows环境处理
                    try {
                        Process p = r.exec("D:/Program/swfttools/pdf2swf.exe "+ pdfFile.getPath() + " -o "+ swfFile.getPath() + " -T 9");
                         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 (swfFile.exists()) {
            System.out.println("****swf转换器开始工作,该文件已经转换为 swf****");
            return true;
        }
        if (environment == 1) {
            System.out.println("****swf转换器开始工作,当前设置运行环境 windows****");
        else {
            System.out.println("****swf转换器开始工作,当前设置运行环境 linux****");
        }
        try {
            doc2pdf();
            pdf2swf();
        catch (Exception e) {
              e.printStackTrace();
              return false;
        }
        System.out.println("文件存在吗?"+swfFile);
        if (swfFile.exists()) {
            System.out.println("存在");
            return true;
        else {
            System.out.println("不存在");
            return false;
        }
    }
    /**
     *返回文件路径      
     * @param     
     */
    public String getswfPath(){
        if (this.swfFile.exists()){
            String tempString = swfFile.getPath();
            tempString = tempString.replaceAll("\\\\""/");
            System.out.println("最后文件路径为"+tempString);
            return tempString;
        else {
            return "文件不存在";
        }
    }
    /**
     * 设置输出路径
     *
     * @param outputPath
     */
    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");
            }
        }
    }
}

  

调用转换类只需要传word、ptt、excel、pdf文件所在的路径参数就可以了。

展示在线预览的jsp代码如下:

<%@page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%String swfFilePath=session.getAttribute("swfpath").toString();System.out.println("展示路径"+swfFilePath);%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta content="text/html;charset=UTF-8" http-equiv="Content-Type">
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/flexpaper_flash.js"></script>
<script type="text/javascript" src="js/flexpaper_flash_debug.js"></script>
<!--  <script type="text/javascript" src="js/jquery-1.6.2.min.js"></script>
<script type="text/javascript" src="js/flexpaper.js"></script>
<script type="text/javascript" src="js/flexpaper_handlers.js"></script>-->
<style type="text/css" media="screen">
html,body{height: 100%;
}
body{margin: 0;padding: 0;overflow: auto;
}
#flashContent{display: none;
}
</style>
<title>在线文档预览</title>
</head>
<body><div style="position: absolute; left:50px;top:10px;"><a id="viewerPlaceHolder" style="width: 820px;height: 650px;display: block;"></a><script type="text/javascript">var fp=new FlexPaperViewer('FlexPaperViewer','viewerPlaceHolder',{config:{SwfFile:escape('<%=swfFilePath%>'),Scale:1.2,ZoomTransition:'easeOut',ZoomTime:0.5,ZoomInterval:0.2,FitPageOnLoad:false,FitWidthOnload:false,FullScreenAsMaxWindow:false,ProgressiveLoading:false,MinZoomSize:0.2,MaxZoomSize:5,SearchMatchAll:false,InitViewMode:'SinglePage',RenderingOrder : 'flash',ViewModeToolsVisible:true,ZoomToolsVisible:true,NavToolsVisible:true,CursorToolsVisible:true,SearchToolsVisible:true,localeChain:'en_US'}});</script></div>
</body>
</html>

其中可能会出现在线预览只能实现10页的情况,需要把RenderingOrder : 'flash',设置为flash才可以实现超过10页的在线预览。swfFilePat为转换后的文件所在路径。

转换后面的效果如下:

注意问题:

1、发现错误一般是openoffice服务没有开启。

2、Linux环境下会存在中文乱码的问题,是linux下不像windows支持那么多字体,需要安装多的字体,并且把字体所在位置链接到flexpaper所在位置。在使用pdf2swf加上参数-s languagedir=/usr/local/xpdf-chinese-simplified/。具体的一些参数请百度。

源代码已经在我的github上了,可以访问https://github.com/liaowp/OnlinePreview,也可以点击我博客的github标签。

如果有问题可以QQ上问我。906522957

作者:鹏鹏

    

出处:http://www.cnblogs.com/liaoweipeng/

java零碎要点010---Java实现office文档与pdf文档的在线预览功能相关推荐

  1. java 预览word文档_Java实现office文档与pdf文档的在线预览功能

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

  2. 快速实现word、excel、ppt、txt等办公文件在线预览功能(Java版)

    点击关注公众号,实用技术文章及时了解 来源:blog.csdn.net/weixin_40986713/ article/details/109527294 java实现办公文件在线预览功能是一个大家 ...

  3. Java 实现word、excel、ppt、txt等办公文件在线预览功能!

    大家好,我是宝哥! 如何用 Java 实现word.excel.ppt.txt等办公文件在线预览功能?本文告诉你答案! java 实现办公文件在线预览功能是一个大家在工作中也许会遇到的需求,网上些公司 ...

  4. 手把手教你用 Java 实现word、excel、ppt、txt等办公文件在线预览功能!

    如何用 Java 实现word.excel.ppt.txt等办公文件在线预览功能?本文告诉你答案! java 实现办公文件在线预览功能是一个大家在工作中也许会遇到的需求,网上些公司专门提供这样的服务, ...

  5. 前端【vue】实现文档在线预览功能,在线预览pdf、word、xls、ppt等office文件

    前端江太公 前端实现文档在线预览功能 最直接的就是使用XDOC 文档云服务 XDOC可以实现预览以DataURI表示的DOC文档,此外XDOC还可以实现文本.带参数文本.html文本.json文本.公 ...

  6. word转图片 java_Java 利用LibreOffice将Office文档转换成 PDF,进而转图片,实现在线预览功能...

    项目中需要将 Office 文档上传并实现在线预览,用到了 LibreOffice 将 Office 文档转换为 PDF 文档,然后再用 pdfbox 将 PDF 转为图片. 本文介绍借助 Libre ...

  7. Java实现在线预览功能

    java实现在线预览功能,需要用到  jacob.dll jacob.jar   预览pdf所需js  pdfobject.min.js 将上传文件转为pdf保存. <divclass=&quo ...

  8. office 文档 在线预览功能实现(word,excel,pdf,ppt等多种格式)——使用https://view.xdocin.com/view 提示文档过期——基础积累

    web实现office文档在线预览功能--基础积累 最近遇到一个需求,就是要实现多种文档链接的在线预览,最简单的方式就是通过window.open(url地址)的方式来实现. 但是如果要求是在一个弹窗 ...

  9. SpringBoot+Vue+OpenOffice实现文档管理(文档上传、下载、在线预览)

    场景 SpringBoot集成OpenOffice实现doc文档转html: SpringBoot集成OpenOffice实现doc文档转html_BADAO_LIUMANG_QIZHI的博客-CSD ...

最新文章

  1. Quartz cron表达式
  2. SAP Spartacus pageSlot一览
  3. 基4fft算法的蝶形图_原地且自动整序的FFT算法
  4. 电子计算机的应用是第四次信息技术革命,造纸术和印刷术的发明和应用第四次电报.PPT...
  5. (12)FPGA时钟设计原则
  6. 一张图明白jenkins和docker作用
  7. ubuntu怎么安装python3操作系统32_ubuntu系统下安装python3
  8. 天津大学学硕和专硕的区别_21考研考生,学硕与专硕的区别你必须知道,选错或后悔读研...
  9. Java Web底层(1)
  10. iOS 评论中含有表情的处理方法
  11. 按键精灵定位坐标循环_关于按键精灵win10抓抓截图问题
  12. 动易html在线编辑器 漏洞,动易网站漏洞总结
  13. 硅谷外卖安装axios报错
  14. 二自由度云台扫描算法_基于二维压电透射式微扫描器的红外超分辨率成像|压电扫描台...
  15. spark标签计算及用户画像应用
  16. python编译成可执行文件 发布 win_[PYTHON]_ELVE_Python源代码文件编译成可执行文件(支持macOS High Sierra和window 10)...
  17. 计算机拓扑结构网状图,网络拓扑结构大全和图片(星型、总线型、环型、树型、分布式、网状拓扑结构)...
  18. 2007福布斯名人榜完全名单 巩俐收入盖过章子怡
  19. Kettle之数据同步
  20. 海德汉 LSV2 协议采集

热门文章

  1. NYOJ-超级台阶(dp)
  2. 浙江大学PTA 数据结构 习题2.2 数组循环左移 (20 分)
  3. Attension Mechanism模型的详细介绍,原理、分类及应用
  4. Service Mesh服务网格:8种方式简化微服务部署
  5. centos 6.5 x64 上安装mariadb10
  6. 让远程传输大文件变得更快
  7. swift(不同设备适配详解)
  8. Ubuntu9.04更新源
  9. Bootstrap-基于jquery的bootstrap在线文本编辑器插件Summernote
  10. 自定义jQuery 跨域请求 callback 函数名