欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java實現(xiàn)word轉(zhuǎn)pdf并在關(guān)鍵字位置插入圖片

 更新時間:2024年11月03日 15:06:38   作者:小七蒙恩  
這篇文章主要為大家詳細(xì)介紹了如何利用Java實現(xiàn)word轉(zhuǎn)pdf,并在word中關(guān)鍵字位置插入圖片,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下

java word轉(zhuǎn)pdf、word中關(guān)鍵字位置插入圖片 工具類

1.pom依賴

		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi</artifactId>
			<version>3.15</version>
		</dependency>
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi-ooxml</artifactId>
			<version>3.15</version>
		</dependency>
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi-scratchpad</artifactId>
			<version>3.15</version>
		</dependency>
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>ooxml-schemas</artifactId>
			<version>1.4</version>
		</dependency>

		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi-ooxml-schemas</artifactId>
			<version>3.15</version>

2.依賴jar包

        <dependency>
            <groupId>com.aspose</groupId>
            <artifactId>aspose-words</artifactId>
            <version>15.8.0</version>
            <scope>system</scope>
            <systemPath>${pom.basedir}/src/main/webapp/WEB-INF/lib/aspose-words-15.8.0-jdk16.jar</systemPath>
        </dependency>

aspose-words是需要在我們項目中引入的,并且使用時要在resouces目錄下導(dǎo)入license.xml文件,否則生成的文件抬頭會有紅色的license信息。

3.工具類

import com.aspose.words.*;
import com.aspose.words.Document;

import org.apache.poi.xwpf.usermodel.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @author dume
 * @ClassName WordToPdf
 * @description: TODO
 * @date 2024年07月02日
 * @version: 1.0
 */

public class WordUtils {
    private static Logger logger = LoggerFactory.getLogger(WordUtils.class);
    private static final String BASE_PATH = WordUtils.class.getClassLoader().getResource("").getPath();

    /**
     *  Word轉(zhuǎn)Pdf
     * @param sourcePath 原路徑
     * @param targetPath 轉(zhuǎn)出路徑
     * @return
     */
    public static boolean  WordToPdf(String sourcePath,String targetPath){
        FileOutputStream os = null;
        try{
            // 驗證License 若不驗證則轉(zhuǎn)化出的pdf文檔會有水印產(chǎn)生
        if (!getLicense()) {
            logger.info("license驗證失敗");
            return false;
        }

        File file = new File(targetPath);
         os = new FileOutputStream(file);
        FontSettings.setFontsFolder(BASE_PATH, true);
        FontSettings.setDefaultFontName("STFANGSO");
        Document doc = new Document(sourcePath);
        doc.save(os, SaveFormat.PDF);
        os.flush();
        os.close();
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage());
            return false;
        }finally {
            if(os!=null){
               try{
                   os.close();
               }catch (Exception e){

               }
            }
        }
       return true;
    }

    /**
     *  word中插入圖片方法
     * @param sourcePath  word路徑
     * @param imgPath     圖片路徑
     * @param keyWords    關(guān)鍵字
     * @return   插入是否成功
     */
    public static boolean InsertImg(String sourcePath,String imgPath,String keyWords){
        try{
            // 驗證License 若不驗證則轉(zhuǎn)化出的pdf文檔會有水印產(chǎn)生
            if (!getLicense()) {
                logger.info("license驗證失敗");
                return false;
            }
            Document doc = new Document(sourcePath);
            DocumentBuilder builder = new DocumentBuilder(doc);

            //插入圖片的方法
            NodeCollection runs = doc.getChildNodes(NodeType.PARAGRAPH, true);
            for (int i = 0; i < runs.getCount(); i++) {
                Node r = runs.get(i);
                String text = r.getText();
                //獲取鍵
                if(text.contains(keyWords)){
                    //鎖定到當(dāng)前段落即實現(xiàn)頁面變換
                    builder.moveTo(r);
                    builder.insertImage(imgPath, RelativeHorizontalPosition.PAGE, 205, RelativeVerticalPosition.PAGE, 0, 20, 7, WrapType.INLINE);
                    break;
                }
            }
            doc.save(sourcePath);
        }catch (Exception e){
            e.printStackTrace();
            logger.error(e.getMessage());
            return false;
        }
        return true;
    }

   
    public static boolean getLicense() {
        boolean result = false;
        try {
            FileInputStream is = new FileInputStream (BASE_PATH+"license.xml");
            License asposeLicense = new License();
            asposeLicense.setLicense(is);
            result = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }


    /***
     * @Description :替換段落文本
     * @param document docx解析對象
     * @param textMap  需要替換的信息集合
     * @return void
     */
    public static void changeText(XWPFDocument document, Map<String, Object> textMap) {
        // 獲取段落集合
        Iterator<XWPFParagraph> iterator = document.getParagraphsIterator();
        XWPFParagraph paragraph = null;
        while (iterator.hasNext()) {
            paragraph = iterator.next();
            // 判斷此段落是否需要替換
            if (checkText(paragraph.getText())) {
                replaceValue(paragraph, textMap);
            }
        }
    }

    /***
     * @Description :替換表格內(nèi)的文字
     * @param document
     * @param data
     * @return void
     */
    public static void changeTableText(XWPFDocument document, Map<String, Object> data) {
        // 獲取文件的表格
        Iterator<XWPFTable> tableList = document.getTablesIterator();
        XWPFTable table;
        List<XWPFTableRow> rows;
        List<XWPFTableCell> cells;
        // 循環(huán)所有需要進(jìn)行替換的文本,進(jìn)行替換
        while (tableList.hasNext()) {
            table = tableList.next();
            if (checkText(table.getText())) {
                rows = table.getRows();
                // 遍歷表格,并替換模板
                for (XWPFTableRow row : rows) {
                    cells = row.getTableCells();
                    for (XWPFTableCell cell : cells) {
                        // 判斷單元格是否需要替換
                        if (checkText(cell.getText())) {
                            List<XWPFParagraph> paragraphs = cell.getParagraphs();
                            for (XWPFParagraph paragraph : paragraphs) {
                                replaceValue(paragraph, data);
                            }
                        }
                    }
                }
            }
        }
    }

    /***
     * @Description :檢查文本中是否包含指定的字符(此處為“$”)
     * @param text
     * @return boolean
     */
    public static boolean checkText(String text) {
        boolean check = false;
        if (text.contains("$")) {
            check = true;
        }
        return check;
    }

    /***
     * @Description :替換內(nèi)容
     * @param paragraph
     * @param textMap
     * @return void
     */
    public static void replaceValue(XWPFParagraph paragraph, Map<String, Object> textMap) {
        XWPFRun run, nextRun;
        String runsText;
        List<XWPFRun> runs = paragraph.getRuns();
        for (int i = 0; i < runs.size(); i++) {
            run = runs.get(i);
            runsText = run.getText(0);
            if (runsText.contains("${") || (runsText.contains("$") && runs.get(i + 1).getText(0).substring(0, 1).equals("{"))) {
                while (!runsText.contains("}")) {
                    nextRun = runs.get(i + 1);
                    runsText = runsText + nextRun.getText(0);
                    //刪除該節(jié)點下的數(shù)據(jù)
                    paragraph.removeRun(i + 1);
                }
                Object value = changeValue(runsText, textMap);
                //判斷key在Map中是否存在
                String replaceText = runsText.replace("${", "").replace("}", "");
                if (textMap.containsKey(replaceText)) {
                    run.setText(value.toString(), 0);
                } else {
                    //如果匹配不到,則不修改
                    run.setText(runsText, 0);
                }
            }
        }
    }

    /***
     * @Description :匹配參數(shù)
     * @param value
     * @param textMap
     * @return java.lang.Object
     */
    public static Object changeValue(String value, Map<String, Object> textMap) {
        Object valu = "";
        for (Map.Entry<String, Object> textSet : textMap.entrySet()) {
            // 匹配模板與替換值 格式${key}
            String key = textSet.getKey();
            if (value.contains(key)) {
                valu = textSet.getValue();
            }
        }
        return valu;
    }

}

以上就是Java實現(xiàn)word轉(zhuǎn)pdf并在關(guān)鍵字位置插入圖片的詳細(xì)內(nèi)容,更多關(guān)于Java word轉(zhuǎn)pdf的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

  • Maven之遠(yuǎn)程倉庫的配置詳解

    Maven之遠(yuǎn)程倉庫的配置詳解

    這篇文章主要介紹了Maven之遠(yuǎn)程倉庫的配置詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-09-09
  • spring自定義一個簡單的Starter啟動器

    spring自定義一個簡單的Starter啟動器

    這篇文章主要介紹了spring自定義一個簡單的Starter啟動器,一個 starter其實就是對一個功能的集成封裝,然后對外提供一個依賴,讓業(yè)務(wù)去使用,像我們熟悉的 Redis,mongo,mybatis 等均屬于,需要的朋友可以參考下
    2023-07-07
  • Springboot項目基于Devtools實現(xiàn)熱部署步驟詳解

    Springboot項目基于Devtools實現(xiàn)熱部署步驟詳解

    這篇文章主要介紹了Springboot項目基于Devtools實現(xiàn)熱部署,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友可以參考下
    2020-06-06
  • maven?傳遞依賴的實現(xiàn)

    maven?傳遞依賴的實現(xiàn)

    本文主要介紹了Maven中傳遞依賴的處理方式,如scope=compile影響依賴傳遞,使用排除不需要的依賴,以及如何通過查看依賴樹解決運行時錯誤,特別是在依賴排除后可能導(dǎo)致的運行時缺少必需包的問題,感興趣的可以了解一下
    2024-10-10
  • JavaSE遞歸求解漢諾塔問題的思路與方法

    JavaSE遞歸求解漢諾塔問題的思路與方法

    遞歸是一種非常重要的算法思想,無論你是前端開發(fā),還是后端開發(fā),都需要掌握它,下面這篇文章主要給給大家介紹了關(guān)于JavaSE遞歸求解漢諾塔問題的思路與方法,文中通過實例代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2022-08-08
  • jdbc實現(xiàn)圖書館借閱系統(tǒng)

    jdbc實現(xiàn)圖書館借閱系統(tǒng)

    這篇文章主要為大家詳細(xì)介紹了jdbc實現(xiàn)圖書館借閱系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2019-02-02
  • 基于java中泛型的總結(jié)分析

    基于java中泛型的總結(jié)分析

    本篇文章介紹了,在java中泛型的總結(jié)分析。需要的朋友參考下
    2013-05-05
  • JAVA使用hutool工具實現(xiàn)查詢樹結(jié)構(gòu)數(shù)據(jù)(省市區(qū))

    JAVA使用hutool工具實現(xiàn)查詢樹結(jié)構(gòu)數(shù)據(jù)(省市區(qū))

    今天通過本文給大家分享JAVA使用hutool工具實現(xiàn)查詢樹結(jié)構(gòu)數(shù)據(jù)(省市區(qū)),代碼分為表結(jié)構(gòu)和數(shù)據(jù)結(jié)構(gòu),代碼簡單易懂,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友參考下吧
    2021-08-08
  • mybatis plus怎么忽略映射字段

    mybatis plus怎么忽略映射字段

    這篇文章主要介紹了mybatis plus怎么忽略映射字段,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-10-10
  • Springboot整合mybatis開啟二級緩存的實現(xiàn)示例

    Springboot整合mybatis開啟二級緩存的實現(xiàn)示例

    在一級緩存中,是查詢兩次數(shù)據(jù)庫的,顯然這是一種浪費,既然SQL查詢相同,就沒有必要再次查庫了,直接利用緩存數(shù)據(jù)即可,這種思想就是MyBatis二級緩存的初衷,本文就詳細(xì)的介紹了Springboot整合mybatis開啟二級緩存,感興趣的可以了解一下
    2022-05-05

最新評論