word轉PDF,PDF轉Image,使用oppenOffice註意事項等

来源:https://www.cnblogs.com/liran123/archive/2018/10/01/9733833.html
-Advertisement-
Play Games

word轉PDF,PDF轉Image,使用oppenOffice註意事項等 ...


最近在電子合同等項目中需要把word或者pdf轉換成image,用到了openOffice把word轉換pdf,以及把pdf轉換成圖片

感謝小伙伴張國清花費了三天時間來實現了此功能。下麵我將把具體的步驟和註意事項說明。防止重覆造輪子,最後我會把我的demo工程,以及對應的jar等發送到百度雲。提供各位下載

一、首先,列出maven依賴以及jar包

  <!--PDF轉圖片-->
        <dependency>
            <groupId>org.icepdf.os</groupId>
            <artifactId>icepdf-core</artifactId>
            <version>6.2.2</version>
            <exclusions>
                <exclusion>
                    <groupId>javax.media</groupId>
                    <artifactId>jai_core</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.icepdf.os</groupId>
            <artifactId>icepdf-viewer</artifactId>
            <version>6.2.2</version>
        </dependency>
        <!--word轉pdf-->
        <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>
        <!--需要手動添加到本地倉庫 word 轉 pdf-->
        <dependency>
            <groupId>org.artofsolving.jodconverter</groupId>
            <artifactId>jodconverter-core</artifactId>
            <version>3.0-beta-4</version>
        </dependency>

  這裡註意:你還一個需要把一個jar的文件夾(文章最下邊有相應的百度雲下載地址)你找到自己的maven倉庫把對應的jar手動放入到 【repository/org/】目錄下,在idea右邊導入後會有有紅色波浪線警告。整個可忽略,不影響使用

  下圖是對應怎麼找到自己的maven repository路徑

  

 二、這裡貼出詳細的代碼和配置,註意如果有的地方不正確或者不理解,歡迎評論或者在文章末尾下載我的demo工程來實際運行。以進一步詳細熟悉

   word轉換pdf工具類

import org.apache.commons.lang3.StringUtils;
import org.artofsolving.jodconverter.OfficeDocumentConverter;
import org.artofsolving.jodconverter.office.DefaultOfficeManagerConfiguration;
import org.artofsolving.jodconverter.office.OfficeManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.io.File;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.regex.Pattern;

/**
 * FileName: OfficeToPdfUtil
 * author:   zhangguoqing
 * Date:     2018/9/19 9:18
 * 說明:  word文件轉換成pdf文件(必須安裝Openoffice)
 */
@Component
public class OfficeToPdfUtil {
    
    static OfficeManager officeManager;

    private static ReentrantLock OfficeLock = new ReentrantLock();

    @PostConstruct
    public void init() {
        DefaultOfficeManagerConfiguration config = new DefaultOfficeManagerConfiguration();
        // 設置OpenOffice.org 3的安裝目錄
        config.setOfficeHome(getOfficeHome());
        // 啟動OpenOffice的服務
        OfficeManager getOfficeManager = config.buildOfficeManager();
        if (getOfficeManager == null) {
            getOfficeManager.start();
        }
        officeManager = getOfficeManager;
    }

    private static Logger logger = LoggerFactory.getLogger(OfficeToPdfUtil.class);

    /**
     * 鎖
     */
    private static Lock lock = new ReentrantLock();

    /**
     * windows下openoffice安裝地址
     */
    private static String windowsOpenOfficeUrl;
    /**
     * linux下openoffice安裝地址
     */
    private static String linuxOpenOfficeUrl;
    /**
     * mac下opneoffice安裝地址
     */
    private static String macOpenofficeUrl = "/Applications/OpenOffice.org.app/Contents/";

    /**
     * 使Office2003-2007全部格式的文檔(.doc|.docx|.xls|.xlsx|.ppt|.pptx) 轉化為pdf文件<br>
     *
     * @param inputFilePath 源文件路徑,如:"e:/test.docx"
     * @return 轉換後的圖片地址
     */
    public static String officeToPdf(String inputFilePath) throws Exception {
        try {
            if (officeManager == null) {
                //如果openOffice中途關閉了 再次啟動 防止報錯
                officeManager = getOfficeManager();
            }
            if (StringUtils.isEmpty(inputFilePath)) {
                logger.info("輸入文件地址為空,轉換終止!");
                return null;
            }
            File inputFile = new File(inputFilePath);
            // 轉換後的pdf文件路徑
            String outputFilePath_end = getOutputFilePath(inputFilePath);
            if (!inputFile.exists()) {
                logger.info("輸入文件不存在,轉換終止!");
                return null;
            }
            // 連接OpenOffice
            OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager);
            return converterFile(inputFile, outputFilePath_end, inputFilePath, converter);
        } catch (Exception e) {
            logger.error("word轉化pdf出錯!", e);
            throw e;
        }
    }

    /**
     * @author: zhangguoqing
     * @date: 2018/9/19 14:03
     * @param: [inputFilePath] word源文件路徑 如:"e:/test.docx"
     * @return: java.util.List<java.lang.String> 轉換後圖片地址列表
     * @Description: word轉成圖片
     */
    public static List<String> officeToImg(String inputFilePath) {
        try {
            //word轉成pdf
            String pdfFilePath = officeToPdf(inputFilePath);
            //pdf轉圖片
            List<String> iamgeFilePath = PdfToImageUtil.pdfToIamge(pdfFilePath);
            for (String string : iamgeFilePath) {
                logger.info("圖片地址:" + string);
            }
            //刪除pdf文件
            new File(pdfFilePath).delete();
            return iamgeFilePath;
        } catch (Exception e) {
            logger.error("word轉化圖片出錯!", e);
            return null;
        }
    }

    /**
     * 獲取輸出文件
     *
     * @param inputFilePath
     * @return
     */
    public static String getOutputFilePath(String inputFilePath) {
        String outputFilePath = inputFilePath.replaceAll("." + getPostfix(inputFilePath), ".pdf");
        return outputFilePath;
    }

    /**
     * 獲取inputFilePath的尾碼名,如:"e:/test.pptx"的尾碼名為:"pptx"<br>
     *
     * @param inputFilePath
     * @return
     */
    public static String getPostfix(String inputFilePath) {
        return inputFilePath.substring(inputFilePath.lastIndexOf(".") + 1);
    }

    /**
     * 連接OpenOffice.org 並且啟動OpenOffice.org
     *
     * @return
     */
    public static OfficeManager getOfficeManager() {
        DefaultOfficeManagerConfiguration config = new DefaultOfficeManagerConfiguration();
        // 設置OpenOffice.org 3的安裝目錄
        config.setOfficeHome(getOfficeHome());
        // 啟動OpenOffice的服務
        OfficeManager getOfficeManager = config.buildOfficeManager();
        getOfficeManager.start();
        return getOfficeManager;
    }

    /**
     * 根據操作系統的名稱,獲取OpenOffice.org 3的安裝目錄<br>
     * 如我的OpenOffice.org 3安裝在:C:/Program Files (x86)/OpenOffice.org 3<br>
     *
     * @return OpenOffice.org 3的安裝目錄
     */
    public static String getOfficeHome() {
        String osName = System.getProperty("os.name");
        logger.info("操作系統名稱:" + osName);
        if (Pattern.matches("Linux.*", osName)) {
            return linuxOpenOfficeUrl;
        } else if (Pattern.matches("Windows.*", osName)) {
            return windowsOpenOfficeUrl;
        } else if (Pattern.matches("Mac.*", osName)) {
            return macOpenofficeUrl;
        }
        return null;
    }

    /**
     * @author: zhangguoqing
     * @date: 2018/9/19 11:35
     * @param: [inputFile, outputFilePath_end, inputFilePath, converter]
     * @return: java.util.List<java.lang.String> 轉換後的圖片地址列表
     * @Description: 文件轉換
     */
    public static String converterFile(File inputFile, String outputFilePath_end, String inputFilePath,
                                       OfficeDocumentConverter converter) throws Exception {
        File outputFile = new File(outputFilePath_end);
        // 假如目標路徑不存在,則新建該路徑
        if (!outputFile.getParentFile().exists()) {
            outputFile.getParentFile().mkdirs();
        }
        //判斷轉換文件的編碼方式,如果不是UTF-8,則改為UTF-8編碼
        converter.convert(inputFile, outputFile);
        logger.info("文件:" + inputFilePath + "\n轉換為\n目標文件:" + outputFile + "\n成功!");
        if (outputFile.isFile() && outputFile.exists()) {
            return outputFilePath_end;
        } else {
            throw new Exception("轉換的目標文件不存在 路徑" + outputFilePath_end);
        }
    }

    @Value("${officeToPdf.linuxOpenOfficeUrl}")
    public void setLinuxOpenOfficeUrl(String linuxOpenOfficeUrl) {
        OfficeToPdfUtil.linuxOpenOfficeUrl = linuxOpenOfficeUrl;
    }

    @Value("${officeToPdf.windowsOpenOfficeUrl}")
    public void setWindowsOpenOfficeUrl(String windowsOpenOfficeUrl) {
        OfficeToPdfUtil.windowsOpenOfficeUrl = windowsOpenOfficeUrl;
    }

}

  pdf轉換image工具類

import org.apache.commons.lang3.StringUtils;
import org.icepdf.core.pobjects.Document;
import org.icepdf.core.pobjects.Page;
import org.icepdf.core.util.GraphicsRenderingHints;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.awt.image.RenderedImage;
import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * FileName: PdfToImageUtil
 * Author:   zhangguoqing
 * Date:     2018/9/18 17:53
 * 說明:  PDF轉圖片
 */
@Component
public class PdfToImageUtil {
    static Logger logger = LoggerFactory.getLogger(PdfToImageUtil.class);

    // 水印透明度
    private static float alpha = 0.2f;
    // 水印橫向位置
    private static int positionWidth = 150;
    // 水印縱向位置
    private static int positionHeight = 300;
    // 水印文字字體
    private static Font font = new Font("仿宋", Font.BOLD, 26);
    // 水印文字顏色
    private static Color color = Color.GRAY;
    // 水印文字
    private static String watermark;

    //圖片寬度(做成可配置項)
    private static Integer width;
    //圖片高度(做成可配置項)
    private static Integer height;
    //圖片格式(做成可配置項)
    private static String imgType;


    public PdfToImageUtil() {
    }

    /**
     * 有參構造,傳參水印文字,生成圖片時根據是否傳參選擇是否生成水印
     *
     * @param watermark 水印內容
     */
    public PdfToImageUtil(String watermark) {
        this.watermark = watermark;
    }

    //設置水印
    public static BufferedImage setGraphics(BufferedImage bfimage) {
        Graphics2D g = bfimage.createGraphics();
        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        // 5、設置水印文字顏色
        g.setColor(color);
        // 6、設置水印文字Font
        g.setFont(font);
        // 7、設置水印文字透明度
        g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha));
        //設置旋轉
        g.rotate(-Math.PI / 6);
        g.drawString(watermark, 0, (bfimage.getHeight() / 2) * 1);
        // 9、釋放資源
        g.dispose();
        return bfimage;
    }

    /**
     * @author: zhangguoqing
     * @date: 2018/9/18 17:55
     * @param: [inputFile] pdf文件路徑
     * @return: java.util.List<java.lang.String> 圖片地址列表
     * @Description: pdf文件轉圖片
     */
    public static List<String> pdfToIamge(String inputFile) {
        //獲取inputFile的尾碼名前的內容,如:"e:/test.pptx"的尾碼名為:"e:/test"
        String imgPath_start = inputFile.substring(0, inputFile.lastIndexOf("."));

        List<String> list=null;
        Document document = null;
        try {

            document = new Document();
            document.setFile(inputFile);
            float rotation = 0; //旋轉角度
            int maxPages = document.getPageTree().getNumberOfPages();

            new ArrayList(maxPages);
            for (int i = 0; i < maxPages; i++) {
                //zoom 縮放比例 ,記住這裡調清晰度,我用的是8.5超清晰,9以上就報錯了
                BufferedImage bfimage = (BufferedImage) document.getPageImage(i, GraphicsRenderingHints.SCREEN, Page.BOUNDARY_CROPBOX, rotation, 2.1f);
                //設置圖片的寬和高
                Image tempImage = bfimage.getScaledInstance(width, height, Image.SCALE_SMOOTH);
                BufferedImage biTemp = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
                Graphics gTemp = biTemp.getGraphics();
                gTemp.drawImage(tempImage, 0, 0, null);
                //加水印
                if (StringUtils.isNotBlank(watermark)) {
                    biTemp = setGraphics(biTemp);
                }
                RenderedImage rendImage = biTemp;
                //拼接圖片地址
                String imgPath = imgPath_start + "_" + i + "." + imgType;
                ImageIO.write(rendImage, imgType, new File(imgPath));
                bfimage.flush();
                list.add(imgPath);
            }
        } catch (Exception e) {
            logger.error("pdf轉化圖片出錯!", e);
        }

        if (document != null) {
            document.dispose();
        }
        return list;
    }

    @Value("${pdfToImg.imgWidth}")
    public void setWidth(Integer width) {
        PdfToImageUtil.width = width;
    }

    @Value("${pdfToImg.imgHeight}")
    public void setHeight(Integer height) {
        PdfToImageUtil.height = height;
    }

    @Value("${pdfToImg.imgType}")
    public void setImgType(String imgType) {
        PdfToImageUtil.imgType = imgType;
    }
}

  spring boot yml配置文件

#word轉pdf
officeToPdf:
  #linux下openoffice安裝地址
  linuxOpenofficeUrl: /opt/openoffice4
  #windows下openoffice安裝地址 預設 請不要改變 (安裝在哪個盤符都是這樣)
  windowsOpenofficeUrl: C:\Program Files (x86)\OpenOffice 4
#pdf轉圖片
pdfToImg:
  #圖片寬度
  imgWidth: 1080
  #圖片高度
  imgHeight: 1920
  #圖片格式
  imgType: png

三、最後說明一下oppenOffice安裝時候的註意事項

  windows下(我的是win10)oppenOffice在安裝時候一路確定就可以,

  在linux我在自己的阿裡雲Centos7.4上安裝linux遇到了一些問題。開始下載的【download language pack】但是在安裝過程中會缺少依賴出問題,後來選擇了 【download full installation】

  1、首先linux上安裝需要把下麵的安裝包下載

  2、然後解壓 運行命令解壓文件:tar -xzvf  Apache_OpenOffice_4.1.5_Linux_x86-64_install-rpm_zh-CN.tar.gz

  3、然後運行安裝命令:cd zh-CN/RPMS/   rpm -ivh *.rpm

  

 

 四、最後提供大家下載對應的工程demo和對應的jar包,以及oppenoffice下載的安裝包

  鏈接:https://pan.baidu.com/s/1RQQgmeSIpEiJVPkKVC2zuw 密碼:ttp4

  再次註意:maven jar 對應直接解壓放入到org目錄下,然後刷新maven依賴或者重啟ide

  

  最後請大家轉文章時不要複製粘貼一部分導致別人看不懂。如果我寫的哪裡有不懂了直接評論刷一下,看到我會及時回覆的。

 


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

-Advertisement-
Play Games
更多相關文章
  • 某些手機上 fixed 元素在頁面滾動時會消失,某些 IOS 設備上觸發不了點擊事件,IOS 設備上點擊事件有 300ms 延遲,IOS 設備上 fixed 元素在鍵盤彈起時位置會變幻不定,在彈窗上滑動時底部頁面也跟著動,兩年移動端前端開發,我TM都經歷了什麼 ...
  • N-blog 使用 Express + MongoDB 搭建多人博客 原文地址: https://github.com/nswbmw/N-blog 建議初學者,研究下整個項目。 這裡節選了一些內容為筆記 : nrm 是一個管理 npm 源的工具。用來切換官方 npm 源和國內的 npm 源(如: c ...
  • BFC 即為Block formatting context 的縮寫,BFC 主要用來將一個盒子設置為一個隔離的容器,不管盒子內部的元素具有什麼屬性,都不會影響到盒子的外面。 1、哪些元素能產生BFC 不是所有的元素都能產生BFC的,只有display 屬性為 block, list-item, t ...
  • 一、阻止刷新頁面 在表單中的提交按鈕<button></button>標簽改為<input type="button">或者在<button>中添加屬性 type="button" 二、阻止表單的預設提交 1、使用preventDefault() 2、使用return false; ...
  • 微服務是一種系統架構的設計風格,它主旨在於將一個原本獨立的系統,拆分成多個獨立運行的小型服務。不同服務之間通過Restful介面進行通訊協作。 ...
  • 1.下載 2.安裝 3.配置schema.xml mycat就是把跨庫的資料庫表,彙集到schema(新庫)中,然後就可以join查詢了 4.配置server.xml 5.啟動mycat 6.查看mycat狀態 7.使用mysql客戶端連接mycat 然後就可以使用mysql語法查詢了 8. 兩個表 ...
  • 使用ant可以輕鬆的將一個項目分離代碼,直接打包成不同需求的tar.gz包使用 1.build.properties (屬性) 2.build.xml (ant打包文件) <?xml version="1.0" encoding="UTF-8"?> <project basedir="." defa ...
  • 山師第二周 一.高數小結 •極限的唯一性 •收斂數列的有界性 •收斂數列的保號性 •收斂數列與其子數列 3.函數極限的證明 •自變數趨於有限值時 •自變數趨於無窮時 證明思路:類比數列極限的證明,利用∣f(x)-A∣將f(x)上的極限轉化到x上。 二.C語言小結(目前為止只上了一次機子…果然得靠自學 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...