java openOffice實現區域網內線上預覽(docx轉pdf)

来源:https://www.cnblogs.com/jasmine-e/archive/2022/05/10/16254454.html
-Advertisement-
Play Games

前言 當前的主瀏覽器都支持直接打開pdf文件,從而實現文件預覽。如果是其他格式文件則得下載,因此用openOffice實現文件轉pdf格式。 一、 openOffice的安裝 下載地址:http://www.openoffice.org/ 安裝教程可參考:openOffice下載和安裝 進入安裝目錄 ...


前言

當前的主瀏覽器都支持直接打開pdf文件,從而實現文件預覽。如果是其他格式文件則得下載,因此用openOffice實現文件轉pdf格式。

一、 openOffice的安裝

  1. 下載地址:http://www.openoffice.org/
    安裝教程可參考:openOffice下載和安裝

  2. 進入安裝目錄,輸入cmd
    安裝路徑

  3. 命令視窗輸入以下命令啟動:
    soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" –nofirststartwizard

二、測試

  1. 導包
    <!--openoffice-->
        <dependency>
            <groupId>com.artofsolving</groupId>
            <artifactId>jodconverter</artifactId>
            <version>2.2.1</version>
        </dependency>
  1. 文件工具類
import com.artofsolving.jodconverter.DefaultDocumentFormatRegistry;
import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.DocumentFormat;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.StreamOpenOfficeDocumentConverter;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

/**
 * 文件格式轉換工具類
 *
 * @author Simon
 * @version 1.0
 * @since JDK1.8
 */
public class FileConvertUtil {
    /** 預設轉換後文件尾碼 */
    private static final String DEFAULT_SUFFIX = "pdf";
    /** openoffice_port */
    public static final String DEFAULT_HOST = "127.0.0.1";
    private static final Integer OPENOFFICE_PORT = 8100;
 
    /**
     * office文檔轉換為PDF(處理本地文件)
     */
    public static InputStream convertLocaleFile(String sourcePath, String suffix) throws Exception {
        File inputFile = new File(sourcePath);
        InputStream inputStream = new FileInputStream(inputFile);
        return covertCommonByStream(inputStream, suffix);
    }
 

    /**
     * office文檔轉換為PDF(處理網路文件)
     */
    public static InputStream convertNetFile(String netFileUrl, String suffix) 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);
        }
        return null;
    }
 
    /**
     *  將文件以流的形式轉換
     */
    public static InputStream covertCommonByStream(InputStream inputStream, String suffix) throws Exception {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        OpenOfficeConnection connection = new SocketOpenOfficeConnection(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());
    }
}
  1. controler層代碼
 @PostMapping("/onlinePreview")
    public void onlinePreview(@RequestParam("url") String url, HttpServletResponse response) throws Exception {
        //獲取文件類型   根據實際的url截斷
        String suffix = url.substring(url.lastIndexOf('.') + 1);
        if (!suffix.equals("txt") && !suffix.equals("doc") && !suffix.equals("docx") && !suffix.equals("xls")
                && !suffix.equals("xlsx") && !suffix.equals("ppt") && !suffix.equals("pptx") && !suffix.equals("sheet") && !suffix.equals("pdf")) {
            throw new Exception("文件格式不支持預覽");
        }
        //我的文件是存在本地上的,該url是為了別的電腦能訪問到,再傳到這的時候就是解析本地文件了,所以找到我的本地文件路徑
        //根據具體情況來,否則會報錯
        url=url.replace("192.168.1.125:8765/knowledge/","G:/creo/knowledge/");
       //處理本地文件
        InputStream in = FileConvertUtil.convertLocaleFile(url, suffix);
        OutputStream 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();
    }
  1. 常見異常

java.lang.IllegalArgumentException: inputFormat is null at com.artofsolving.jodconverter.openoffice.converter.AbstractOpenOfficeDocumentConverter.ensureNotNull(AbstractOpenOfficeDocumentConverter.java:113)
這是因為轉換07版本及高版本(.docx/.xlsx/.pptx)時,這三種格式不在所支持的文件格式中。

** 解決辦法: **
重寫BasicDocumentFormatRegistry (一定得在com.artofsolving.jodconverter包下)

package com.artofsolving.jodconverter;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class BasicDocumentFormatRegistry implements DocumentFormatRegistry {
    private List documentFormats = new ArrayList();
    public BasicDocumentFormatRegistry() {
    }
    public void addDocumentFormat(DocumentFormat documentFormat) {
        this.documentFormats.add(documentFormat);
    }
    protected List getDocumentFormats() {
        return this.documentFormats;
    }
    public DocumentFormat getFormatByFileExtension(String extension) {
        if (extension == null) {
            return null;
        } else {
            if (extension.indexOf("doc") >= 0) {
                extension = "doc";
            }
            if (extension.indexOf("ppt") >= 0) {
                extension = "ppt";
            }
            if (extension.indexOf("xls") >= 0) {
                extension = "xls";
            }
            String lowerExtension = extension.toLowerCase();
            Iterator it = this.documentFormats.iterator();
            DocumentFormat format;
            do {
                if (!it.hasNext()) {
                    return null;
                }
                format = (DocumentFormat)it.next();
            } while(!format.getFileExtension().equals(lowerExtension));
            return format;
        }
    }
    public DocumentFormat getFormatByMimeType(String mimeType) {
        Iterator it = this.documentFormats.iterator();
        DocumentFormat format;
        do {
            if (!it.hasNext()) {
                return null;
            }
            format = (DocumentFormat)it.next();
        } while(!format.getMimeType().equals(mimeType));
        return format;
    }
}

參考:解決jodconverter 2.2.1 版本不支持docx、xlsx、pptx 轉換成PDF格式異常


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 背景: 當我們使用微服務時,若想在本地聯調就需要啟動多個服務,為了避免本地啟動過多服務,現將註冊中心等基礎服務共用。當我們在服務A開發時,都是註冊到同一個nacos,這樣本地和開發環境的服務A就會同時存在,當調用服務時就會使用負載均衡選擇服務,導致我們無法正常調試介面。這時我們可以選擇使用灰度版本來 ...
  • MyBatis框架提供兩級緩存,一級緩存和二級緩存,預設開啟一級緩存。緩存就是為了提交查詢效率 ...
  • 1.salesforce是什麼? salesforce致力於在銷售,服務,營銷,分析和 客戶聯繫方面為用戶提供幫助。 通過使用標準產品和功能(standard products and features),可以管理潛在客戶(prospects )和客戶(customers)的關係,與員工和合作伙伴協 ...
  • 算數運算符 <?php $x=10; $y=6; echo ($x + $y); // 加 echo '<br>'; // 換行 echo ($x - $y); // 減 echo '<br>'; // 換行 echo ($x * $y); // 乘 echo '<br>'; // 換行 echo ...
  • Spring Bean 的創建過程介紹了FactoryBean 的創建方式,那麼接下來介紹不是FactoryBean的創建方式,在創建過程中,又會分為單例的Bean的創建,原型類型的Bean的創建等。一般來說在Spring中幾乎所有對象都是單例創建的,除非有其他業務需要設置為其他作用域的Bean,所 ...
  • 動態規劃 [P1216 USACO1.5][IOI1994]數字三角形 Number Triangles - 洛谷 | 電腦科學教育新生態 (luogu.com.cn) 題目描述 觀察下麵的數字金字塔。 寫一個程式來查找從最高點到底部任意處結束的路徑,使路徑經過數字的和最大。每一步可以走到左下方的 ...
  • 前言 作為目前全世界最大的視頻網站,它幾乎全是用Python來寫的 該網站當前行業內線上視頻服務提供商,該網站的系統每天要處理上千萬個視頻片段,為全球成千上萬的用戶提供高水平的視頻上傳、分發、展示、瀏覽服務。 2015年2月,央視首次把春晚推送到該網站。 今天,我們就要用Python來快速批量下載該 ...
  • 在開發中,遇到這樣一個需求,在介質資料新增時,需要生成一個介質編號,格式為"JZ+yyyyMMDD+4位遞增數字" 先是使用百度找尋解決方法。解決方法 裡面的查詢緩存的方法在我這項目里沒有,我也不會寫。就自己想了個折中的方法,再請求這個介面的時候,先去資料庫查詢MAX(id),如果有,就在此基礎上+ ...
一周排行
    -Advertisement-
    Play Games
  • Dapr Outbox 是1.12中的功能。 本文只介紹Dapr Outbox 執行流程,Dapr Outbox基本用法請閱讀官方文檔 。本文中appID=order-processor,topic=orders 本文前提知識:熟悉Dapr狀態管理、Dapr發佈訂閱和Outbox 模式。 Outbo ...
  • 引言 在前幾章我們深度講解了單元測試和集成測試的基礎知識,這一章我們來講解一下代碼覆蓋率,代碼覆蓋率是單元測試運行的度量值,覆蓋率通常以百分比表示,用於衡量代碼被測試覆蓋的程度,幫助開發人員評估測試用例的質量和代碼的健壯性。常見的覆蓋率包括語句覆蓋率(Line Coverage)、分支覆蓋率(Bra ...
  • 前言 本文介紹瞭如何使用S7.NET庫實現對西門子PLC DB塊數據的讀寫,記錄了使用電腦模擬,模擬PLC,自至完成測試的詳細流程,並重點介紹了在這個過程中的易錯點,供參考。 用到的軟體: 1.Windows環境下鏈路層網路訪問的行業標準工具(WinPcap_4_1_3.exe)下載鏈接:http ...
  • 從依賴倒置原則(Dependency Inversion Principle, DIP)到控制反轉(Inversion of Control, IoC)再到依賴註入(Dependency Injection, DI)的演進過程,我們可以理解為一種逐步抽象和解耦的設計思想。這種思想在C#等面向對象的編 ...
  • 關於Python中的私有屬性和私有方法 Python對於類的成員沒有嚴格的訪問控制限制,這與其他面相對對象語言有區別。關於私有屬性和私有方法,有如下要點: 1、通常我們約定,兩個下劃線開頭的屬性是私有的(private)。其他為公共的(public); 2、類內部可以訪問私有屬性(方法); 3、類外 ...
  • C++ 訪問說明符 訪問說明符是 C++ 中控制類成員(屬性和方法)可訪問性的關鍵字。它們用於封裝類數據並保護其免受意外修改或濫用。 三種訪問說明符: public:允許從類外部的任何地方訪問成員。 private:僅允許在類內部訪問成員。 protected:允許在類內部及其派生類中訪問成員。 示 ...
  • 寫這個隨筆說一下C++的static_cast和dynamic_cast用在子類與父類的指針轉換時的一些事宜。首先,【static_cast,dynamic_cast】【父類指針,子類指針】,兩兩一組,共有4種組合:用 static_cast 父類轉子類、用 static_cast 子類轉父類、使用 ...
  • /******************************************************************************************************** * * * 設計雙向鏈表的介面 * * * * Copyright (c) 2023-2 ...
  • 相信接觸過spring做開發的小伙伴們一定使用過@ComponentScan註解 @ComponentScan("com.wangm.lifecycle") public class AppConfig { } @ComponentScan指定basePackage,將包下的類按照一定規則註冊成Be ...
  • 操作系統 :CentOS 7.6_x64 opensips版本: 2.4.9 python版本:2.7.5 python作為腳本語言,使用起來很方便,查了下opensips的文檔,支持使用python腳本寫邏輯代碼。今天整理下CentOS7環境下opensips2.4.9的python模塊筆記及使用 ...