Office转换成pdf

Office转换成pdf

​ 帮助别人写的一个需求,Linux好像兼容性比较差。支持Office的全部格式转换成pdf,自行生成Office各种格式的文档做过测试,都能转换成功。如果,有出入自行留言讨论,我会第一时间回复!谢谢。

1、依赖

  • guava
<dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>19.0</version>
</dependency>
  • jodconverter
<dependency>
            <groupId>com.github.livesense</groupId>
            <artifactId>jodconverter-core</artifactId>
            <version>1.0.5</version>
</dependency>

2、客户端

  • OpenOffice

下载地址:http://www.openoffice.org/

安装:安装根据操作系统自行下载安装(我的是Linux-Ubuntu系统)如果有出入自行解决,百度很多教程。

3、中文乱码

  • Linux参考

https://blog.csdn.net/fanjin287659245/article/details/80360767

  • Windows

目前没有发现哪里不兼容。

4、代码

  • DemoController.java
package com.fude.demo.controller

import com.fude.demo.util.OpenOfficeUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;

@Controller
public class DemoController {

    @ResponseBody
    @RequestMapping(value = "/getPDF", method = RequestMethod.POST)
    public File getPDF(MultipartFile inputFile) throws Exception {
        OpenOfficePdfUtils openOfficeUtils = new OpenOfficeUtils();
        return openOfficeUtils.pdfConverter(inputFile);
    }
}
  • OpenOfficeUtils.java
package com.fude.demo.util;

import org.apache.commons.io.IOUtils;
import org.artofsolving.jodconverter.OfficeDocumentConverter;
import org.artofsolving.jodconverter.office.DefaultOfficeManagerConfiguration;
import org.artofsolving.jodconverter.office.OfficeManager;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.util.Random;

/**
 * office文件转换pdf
 */
public class OpenOfficeUtils {
    /**
     * @param args
     */
    private static OfficeManager officeManager;
    private static String SERVER_PATH = "/opt/openoffice4/";
    private static int port[] = {8100};
    File toFile;

    /**
     * pdf 转换器
     *
     * @param inputFile office文件
     * @throws Exception
     */
    public File pdfConverter(MultipartFile inputFile) throws Exception {

        try {
            // 开启服务器
            startService();
            // 获取Excel文件
            final File officeFile = getFile(inputFile);
            final File pdfFile = File.createTempFile(getRandByNum(6), ".pdf");
            // Office文档转换器
            OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager);
            converter.convert(officeFile, pdfFile);
            // 返回
            toFile = pdfFile;
            // 删除
            deleteFile(officeFile);
//            deleteFile(pdfFile);
            return toFile;
        } finally {
            // 关闭服务器
            stopService();
        }

    }

    /**
     * 删除
     *
     * @param files
     */
    private void deleteFile(File... files) {
        for (File file : files) {
            if (file.exists()) {
                file.delete();
            }
        }
    }
    
    /**
     * 产生num位的随机数
     *
     * @return
     */
    private static synchronized String getRandByNum(int num) {
        // 定制长度
        String length = "1";
        for (int i = 0; i < num; i++) {
            length += "0";
        }
        // 获取随机数
        Random rad = new Random();
        String result = rad.nextInt(Integer.parseInt(length)) + "";

        if (result.length() != num) {
            return getRandByNum(num);
        }
        return result;
    }
    
     /**
     * 获取File文件流对象
     *
     * @param inputFile
     * @return
     * @throws IOException
     */
    private File getFile(MultipartFile inputFile) throws IOException {
        File toFile = null;
        if (inputFile.equals("") || inputFile.getSize() <= 0) {
            inputFile = null;
        } else {
            InputStream ins = null;
            ins = inputFile.getInputStream();
            toFile = new File(inputFile.getOriginalFilename());
            inputStreamToFile(ins, toFile);
            ins.close();
        }
        return toFile;
    }
    
     /**
     * 转换器
     *
     * @param ins
     * @param file
     */
    private static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 打开服务器
     */
    private static void startService() {
        DefaultOfficeManagerConfiguration configuration = new DefaultOfficeManagerConfiguration();
        try {
            System.out.println("准备启动服务....");
            // 设置OpenOffice.org安装目录
            configuration.setOfficeHome(SERVER_PATH);
            // 设置转换端口,默认为8100
            configuration.setPortNumbers(port);
            // 设置任务执行超时为5分钟
            configuration.setTaskExecutionTimeout(1000 * 60 * 5L);
            // 设置任务队列超时为24小时
            configuration.setTaskQueueTimeout(1000 * 60 * 60 * 24L);

            officeManager = configuration.buildOfficeManager();
            // 启动服务
            officeManager.start();
            System.out.println("office转换服务启动成功!");
        } catch (Exception e) {
            System.out.println("office转换服务启动失败!详细信息:" + e);
        }
    }

    /**
     * 关闭服务器
     */
    private static void stopService() {
        System.out.println("关闭office转换服务....");
        if (officeManager != null) {
            officeManager.stop();
        }
        System.out.println("关闭office转换成功!");
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值