springboot整合Jobconverter + openOffice + pdf.js 在页面实现预览效果

实现效果:

点击页面的预览按钮,将我们指定的一个office文件(word、excel、txt或者ppt都行)在页面展示出来

实现思路:

我们想要将pdf文件在页面上展示很简单,有很多插件可以给我们使用,例如pdf.js,并且界面提供很多功能。但是想要将word等office文件在页面展示就有点困难。如何解决?将word等office文件后台转换成pdf,再将pdf展示即可。

准备工作

1.下载安装openOffice,我这里使用win版(openOffice是实际用来提供将office转换成pdf功能的,它是运行在客户端的,需要开启它的服务;而Jobconverter是java里面调用的工具,用来连接openOffice操作的)。安装openOffice的教程这里就不放了,网上搜,如果官网的下载速度太慢了,可以试下这个下载地址
2.下载pdf.js文件,解压 下载连接

整合开始

1.引入maven ,这里包含了整合openOffice和Jobconverter的所有jar包

        <!-- openOffice 和 jobconverter-->
        <dependency>
            <groupId>org.jodconverter</groupId>
            <artifactId>jodconverter-core</artifactId>
            <version>4.2.2</version>
        </dependency>
        <dependency>
            <groupId>org.jodconverter</groupId>
            <artifactId>jodconverter-spring-boot-starter</artifactId>
            <version>4.2.2</version>
        </dependency>
        <dependency>
            <groupId>org.jodconverter</groupId>
            <artifactId>jodconverter-local</artifactId>
            <version>4.2.2</version>
        </dependency>

下面用到 thymeleaf和 fastjson

        <!--thymeleaf-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <!--fastjson-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.47</version>
        </dependency>

2.application.properties 配置文件 

这里注意:你本地的openOffice的安装路径,必须要跟这里对应上,我这个是openOffice默认的安装路径,还有端口号,跟你启动openOffice服务所指定的端口也要对应!

#jodconverter的基础配置,指定安装路径和端口
jodconverter.local.enabled=true
jodconverter.local.office-home: C:\\Program Files (x86)\\OpenOffice 4
jodconverter.local.max-tasks-per-process: 10
jodconverter.local.port-numbers: 8100

因为我用到 thymeleaf模板,这里顺便贴上配置

#thymeleaf 模板解析器属性
spring.thymeleaf.mode=HTML5
spring.thymeleaf.encoding=UTF-8
spring.thymeleaf.servlet.content-type=text/html
# 默认的前后缀,不写默认就是这个
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
#开发时关闭缓存,不然没法看到实时页面
spring.thymeleaf.cache=false

到这里其实整合好了,下面就是使用过程。

3.使用过程

1)准备
在resources目录下的static下,新建pdf.js目录,将下载好的pdf.js压缩包解压后,所有东西放在刚新建的文件夹pdf.js里面
在resources目录下的static下,新建file目录(用来保存临时生成的pdf文件),还有新建template目录(用来存放你要生成pdf的office文件,我这里就放一个txt文件)

2)先指定一个页面,该页面有一个点击预览的按钮,和发起的连接

    @RequestMapping("/index")
    public ModelAndView hello(){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("index");
        return modelAndView;
    }

index.html页面

<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/html">
<html  xmlns:th="http://www.thymeleaf.org" >
<head>
    <meta charset="UTF-8">
    <title>hello</title>

    <script src="http://code.jquery.com/jquery-latest.js"></script>
    <script>
        function method(){
            $.ajax({
                type:"GET",
                url:"generatePDF",
                cache:false,  // 表示浏览器是否缓存被请求页面,默认是 true
                dataType:"json",
                success:function(data){
                    if(data.flag == 'success'){
                        window.open (getRootPath()+'/pdf.js/web/viewer.html?file='+getRootPath()+'/file/文件.pdf', '预览图', 'height=700px, width=900px, ' +
                            'top=100, left=400, toolbar=yes, menubar=no, scrollbars=no, resizable=no,location=no, status=no')
                    }else{
                        alert('预览失败');
                    }
                },
                error:function(){
                    alert("发生错误");
                }
            })
        }
        // 该方法获取项目根路径
        function getRootPath(){
            var strFullPath=window.document.location.href;
            var strPath=window.document.location.pathname;
            var pos=strFullPath.indexOf(strPath);
            var prePath=strFullPath.substring(0,pos);
            var postPath=strPath.substring(0,strPath.substr(1).indexOf('/')+1);
            return(prePath+postPath);
        }
    </script>
</head>
<body>
<button onclick="method()">预览</button>
</body>
</html>

页面发起一个ajax请求,去后端将我们指定的txt文件(当然其他的office文件也可以,直接替换名字即可)转换成pdf,返回来后,在前端打开一个小窗口,连接指向我们刚生成的pdf

这里页面展示一个pdf用到插件pdf.js,用起来十分简单,直接在href指向我们导入的包的viewer.html页面,后面再跟上参数  ?file=你生成的pdf的实际路径 即可,详细的pdf.js教程可以自行百度

3)这个是上面ajax请求的后端代码,主要就是注入Jobconverter的工具类,然后调用,将我们指定的txt文件转成pdf,保存在我们新建的 /static/file 目录

    @Autowired
    private DocumentConverter converter;
    
    @RequestMapping("/generatePDF")
    @ResponseBody
    public String generatePDF() throws IOException {
        // 获取项目根路径
        Resource resource = new ClassPathResource("");
        String absolutePath = resource.getFile().getAbsolutePath();
        File inputFile = new File(absolutePath+"/static/template/文件.txt");
        File outputFile = new File(absolutePath+"/static/file/文件.pdf");
        HashMap<String, String> map = new HashMap<>();
        try {
            converter.convert(inputFile).to(outputFile).execute();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("转换出错!");
            map.put("flag","false");
            String s = JSON.toJSONString(map);
            return s;
        }finally {
            if(!outputFile.exists()){
                outputFile.createNewFile();
            }
        }
        System.out.println("转换成功!");
        map.put("flag","success");
        String s = JSON.toJSONString(map);
        return s;
    }

测试

输入 http://localhost:8080/index 进入页面,点击预览按钮
弹出小窗口:

这个是我放的txt文件,你可以放入你自己的word文档、execl等等

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值