Java realizes the online preview function of office files such as excel, word, txt, ppt, etc.

I believe that everyone will encounter the online preview function during the development process. Have you ever thought about how to realize the online preview function of excel, word, txt, ppt and other office files through java? Today we will solve this problem!

In fact, there are still some companies on the Internet that provide fee-based services for this function. So, how to achieve free features? Next, let's implement a version for free.

We want to achieve free, use is openoffice.

The principle of openoffice is: first convert word, ppt, excel, txt files into pdf file streams through openoffice;

In addition, if the browser supports pdf file preview, and Adobe Reader XI is installed, you can directly browse by dragging the pdf into the browser.

The download address of Apache OpenOffice: Apache OpenOffice - Official Download

After the installation package is downloaded, it can be installed and run in a fool-proof way. For Linux, just click Baidu.

Introduce dependencies in the pom file

<dependency>

   <groupId>com.artofsolving</groupId>
   <artifactId>jodconverter</artifactId>
   <version>2.2.1</version>
</dependency>



<dependency>
   <groupId>org.jodconverter</groupId>
   <artifactId>jodconverter-core</artifactId>
   <version>4.4.2</version>
</dependency>
<dependency>
   <groupId>org.openoffice</groupId>
   <artifactId>jurt</artifactId>
   <version>3.0.1</version>
</dependency>
<dependency>
   <groupId>org.openoffice</groupId>
   <artifactId>ridl</artifactId>
   <version>3.0.1</version>
</dependency>
<dependency>
   <groupId>org.openoffice</groupId>
   <artifactId>juh</artifactId>
   <version>3.0.1</version>
</dependency>
<dependency>
   <groupId>org.openoffice</groupId>
   <artifactId>unoil</artifactId>
   <version>3.0.1</version>
</dependency>

Code

Tools:

/**
 * 文件格式转换工具类
 */
public class FileConvertUtil {
    /**
     * 默认转换后文件后缀
     **/
    private static final String DEFAULT_SUFFIX = "pdf";
    /**
     * openoffice_port
     */
    private static final Integer OPENOFFICE_PORT = 8100;


   /**
    * 方法描述 office文档转换为PDF(处理本地文件)
    * @param sourcePath 源文件路径
    * @param suffix     源文件后缀
    * @param ip          链接ip地址
    * @return InputStream 转换后文件输入流
    */
   public static InputStream convertLocaleFile(String sourcePath, String suffix,String ip) throws Exception {
       File inputFile = new File(sourcePath);
       InputStream inputStream = new FileInputStream(inputFile);
       return covertCommonByStream(inputStream, suffix,ip);
   }

   /**
    * 方法描述  office文档转换为PDF(处理网络文件)
    * @param netFileUrl 网络文件路径
    * @param suffix     文件后缀
    * @param ip          链接ip地址
    * @return InputStream 转换后文件输入流
    **/
   public static InputStream convertNetFile(String netFileUrl, String suffix,String ip) throws Exception {
       // 创建URL
       URL url = new URL(netFileUrl);
       // 试图连接并取得返回状态码
       URLConnection urlconn = url.openConnection();
       urlconn.connect();
       HttpURLConnection httpconn = (HttpURLConnection) urlconn;
       int httpResult = httpconn.getResponseCode();
       if (httpResult == HttpURLConnection.HTTP_OK) {
           InputStream inputStream = urlconn.getInputStream();
           return covertCommonByStream(inputStream, suffix,ip);
       }
       return null;
   }

   /**
    * 方法描述  将文件以流的形式转换
    * @param inputStream 源文件输入流
    * @param suffix      源文件后缀
    * @param ip          链接ip地址
    * @return InputStream 转换后文件输入流
    */
   public static InputStream covertCommonByStream(InputStream inputStream, String suffix,String ip) throws Exception {
       ByteArrayOutputStream out = new ByteArrayOutputStream();
       OpenOfficeConnection connection = new SocketOpenOfficeConnection(ip,OPENOFFICE_PORT);
       connection.connect();
       DocumentConverter converter = new StreamOpenOfficeDocumentConverter(connection);
       DefaultDocumentFormatRegistry formatReg = new DefaultDocumentFormatRegistry();
       DocumentFormat targetFormat = formatReg.getFormatByFileExtension(DEFAULT_SUFFIX);
       DocumentFormat sourceFormat = formatReg.getFormatByFileExtension(suffix);
       converter.convert(inputStream, sourceFormat, out, targetFormat);
       connection.disconnect();
       return outputStreamConvertInputStream(out);
   }

   /**
    * 方法描述 outputStream转inputStream
    */
   public static ByteArrayInputStream outputStreamConvertInputStream(final OutputStream out) throws Exception {
       ByteArrayOutputStream baos=(ByteArrayOutputStream) out;
       return new ByteArrayInputStream(baos.toByteArray());

   }

/**
 * @Description:系统文件在线预览接口
 */
public void onlinePreview(String url,String ip, HttpServletResponse response) throws BaseException {
    if(StringUtils.isEmpty(url)){
        throw new ParamException("文件路径不能为空");
    }
    //获取文件类型
    String[] str = url.split("\\.");


   if(str.length==0){
throw new ParamException("文件格式不正确");
   }
String suffix = str[str.length-1];
   if(!suffix.equals("txt") && !suffix.equals("doc") && !suffix.equals("docx") && !suffix.equals("xls")
&& !suffix.equals("xlsx") && !suffix.equals("ppt") && !suffix.equals("pptx")){
throw new ParamException("文件格式不支持预览");
   }
InputStream in= null;
   OutputStream outputStream = null;
   try {
in = convertNetFile(url,suffix,ip);
       outputStream = response.getOutputStream();
       //创建存放文件内容的数组
       byte[] buff =new byte[1024];
       //所读取的内容使用n来接收
       int n;
       //当没有读取完时,继续读取,循环
       while((n=in.read(buff))!=-1){
//将字节数组的数据全部写入到输出流中
           outputStream.write(buff,0,n);
       }
//强制将缓存区的数据进行输出
       outputStream.flush();
       //关流
       outputStream.close();
       in.close();
   } catch (Exception e) {
e.printStackTrace();
       if (outputStream != null) {
//关流
           try {
outputStream.close();
           } catch (IOException e1) {
e1.printStackTrace();
           }
}
if(in != null){
try {
in.close();
           } catch (IOException e1) {
e1.printStackTrace();
           }
}
}

}

The online preview function can be completed by calling onlinePreview in the interface of the Controller class, without any return parameters, and the online preview is realized through the input and output streams.

Renderings:

Note: If the file is docx, xlsx, pptx will not support!

A follow-up article will be updated to tell you how to support the preview of the above three files

Welcome to click on the card below to pay attention to "coder trainees"

Guess you like

Origin blog.csdn.net/ybb_ymm/article/details/130016140