SoFunction
Updated on 2025-04-14

Java implements word to pdf and inserts pictures in keyword position

Java Word to PDF, insert pictures in keyword positions in Word Tools

rely

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

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

2. Depend on jar package

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

Aspose-words needs to be introduced in our project, and when using it, you must import the file in the resouces directory, otherwise the generated file header will have red license information.

3. Tools

import .*;
import ;

import .*;
import org.;
import org.;
import ;
import ;
import ;
import ;
import ;
import ;

/**
  * @author dume
  * @ClassName WordToPdf
  * @description: TODO
  * @date July 2, 2024
  * @version: 1.0
  */

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

    /**
      * Word to Pdf
      * @param sourcePath Original path
      * @param targetPath Out path
      * @return
      */
    public static boolean  WordToPdf(String sourcePath,String targetPath){
        FileOutputStream os = null;
        try{
            // Verify License If you do not verify, the converted PDF document will have a watermark        if (!getLicense()) {
            ("license verification failed");
            return false;
        }

        File file = new File(targetPath);
         os = new FileOutputStream(file);
        (BASE_PATH, true);
        ("STFANGSO");
        Document doc = new Document(sourcePath);
        (os, );
        ();
        ();
        }catch (Exception e){
            ();
            (());
            return false;
        }finally {
            if(os!=null){
               try{
                   ();
               }catch (Exception e){

               }
            }
        }
       return true;
    }

    /**
      * Method of inserting pictures in word
      * @param sourcePath word path
      * @param imgPath picture path
      * @param keyWords keywords
      * @return Is the insert successful?
      */
    public static boolean InsertImg(String sourcePath,String imgPath,String keyWords){
        try{
            // Verify License If you do not verify, the converted PDF document will have a watermark            if (!getLicense()) {
                ("license verification failed");
                return false;
            }
            Document doc = new Document(sourcePath);
            DocumentBuilder builder = new DocumentBuilder(doc);

            //How to insert pictures            NodeCollection runs = (, true);
            for (int i = 0; i &lt; (); i++) {
                Node r = (i);
                String text = ();
                //Get key                if((keyWords)){
                    //Locking to the current paragraph will realize page transformation                    (r);
                    (imgPath, , 205, , 0, 20, 7, );
                    break;
                }
            }
            (sourcePath);
        }catch (Exception e){
            ();
            (());
            return false;
        }
        return true;
    }

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


    /***
      * @Description : Replace paragraph text
      * @param document docx parsing object
      * @param textMap The information collection that needs to be replaced
      * @return void
      */
    public static void changeText(XWPFDocument document, Map&lt;String, Object&gt; textMap) {
        // Get the paragraph collection        Iterator&lt;XWPFParagraph&gt; iterator = ();
        XWPFParagraph paragraph = null;
        while (()) {
            paragraph = ();
            // Determine whether this paragraph needs to be replaced            if (checkText(())) {
                replaceValue(paragraph, textMap);
            }
        }
    }

    /***
      * @Description : Replace text in the table
      * @param document
      * @param data
      * @return void
      */
    public static void changeTableText(XWPFDocument document, Map&lt;String, Object&gt; data) {
        // Get the file form        Iterator&lt;XWPFTable&gt; tableList = ();
        XWPFTable table;
        List&lt;XWPFTableRow&gt; rows;
        List&lt;XWPFTableCell&gt; cells;
        // Loop all text that needs to be replaced and replace        while (()) {
            table = ();
            if (checkText(())) {
                rows = ();
                // Iterate over the table and replace the template                for (XWPFTableRow row : rows) {
                    cells = ();
                    for (XWPFTableCell cell : cells) {
                        // Determine whether the cell needs to be replaced                        if (checkText(())) {
                            List&lt;XWPFParagraph&gt; paragraphs = ();
                            for (XWPFParagraph paragraph : paragraphs) {
                                replaceValue(paragraph, data);
                            }
                        }
                    }
                }
            }
        }
    }

    /***
      * @Description : Check whether the text contains the specified character (here is "$")
      * @param text
      * @return boolean
      */
    public static boolean checkText(String text) {
        boolean check = false;
        if (("$")) {
            check = true;
        }
        return check;
    }

    /***
      * @Description : Replace content
      * @param paragraph
      * @param textMap
      * @return void
      */
    public static void replaceValue(XWPFParagraph paragraph, Map&lt;String, Object&gt; textMap) {
        XWPFRun run, nextRun;
        String runsText;
        List&lt;XWPFRun&gt; runs = ();
        for (int i = 0; i &lt; (); i++) {
            run = (i);
            runsText = (0);
            if (("${") || (("$") &amp;&amp; (i + 1).getText(0).substring(0, 1).equals("{"))) {
                while (!("}")) {
                    nextRun = (i + 1);
                    runsText = runsText + (0);
                    //Delete the data under this node                    (i + 1);
                }
                Object value = changeValue(runsText, textMap);
                //Judge whether the key exists in the map                String replaceText = ("${", "").replace("}", "");
                if ((replaceText)) {
                    ((), 0);
                } else {
                    //If the match does not match, it will not be modified                    (runsText, 0);
                }
            }
        }
    }

    /***
      * @Description : Match parameters
      * @param value
      * @param textMap
      * @return
      */
    public static Object changeValue(String value, Map&lt;String, Object&gt; textMap) {
        Object valu = "";
        for (&lt;String, Object&gt; textSet : ()) {
            // Match template and replace value Format ${key}            String key = ();
            if ((key)) {
                valu = ();
            }
        }
        return valu;
    }

}

The above is the detailed content of Java implementing word to pdf and inserting pictures in keyword positions. For more information about Java word to pdf, please follow my other related articles!