如何使用docx4j替换带有格式化文本字符串的占位符

时间:2018-01-07 12:09:36

标签: java docx4j

我正在尝试使用简单格式化的字符串replace_text.2a替换docx文档中的占位符<body><div><font color='red'>RED COLOR</font></div></body>,但它始终会删除最终word文档中的格式。如何在word文件中保留格式

以下是代码

import java.io.File;
import java.util.List;

import javax.xml.bind.JAXBException;

import org.docx4j.convert.in.xhtml.XHTMLImporter;
import org.docx4j.openpackaging.exceptions.Docx4JException;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart;
import org.docx4j.wml.ObjectFactory;
import org.docx4j.wml.P;
import org.docx4j.wml.R;
import org.docx4j.wml.SdtPr.RichText;
import org.docx4j.wml.Text;



public class HTMLSnipperInWord {

    public static void main(String args[]) throws Exception
    {

        // input the file
        String inputfilepath = "C:\\temp\\test.docx";
        String outputFile = "C:\\temp\\test_UPDATE.docx";

        File inputFile = new File(inputfilepath);

        WordprocessingMLPackage wordPackage = WordprocessingMLPackage.load(inputFile);

        MainDocumentPart mainDocument = wordPackage.getMainDocumentPart();

        // get its contents using jaxb

        List<Object> jaxbNodes = mainDocument.getJAXBNodesViaXPath("//w:p",true);

        for (Object node : jaxbNodes) {

            String paragraphString = node.toString();

            if(paragraphString.equalsIgnoreCase("replace_text.2a"))
            {
                // get the index of P
                P indexOfP = (P)node;
                int index =0;
                index = mainDocument.getContent().indexOf(indexOfP);
                System.out.println(" Index "+index);
                String richText = "<body><div><font color='red'>RED COLOR</font></div></body>";
                replaceText(node, richText,wordPackage,index);
            }

           }


        // check the text and replace


        // save as new file
        File newFile = new File(outputFile);
        wordPackage.save(newFile);

        System.out.println(" New File Created :: "+newFile.exists());


    } // main


    public static void replaceText(Object jaxbNode, String newText, WordprocessingMLPackage wordPkg, int index) throws Exception {

        // checking whether this is instance of P



        if (jaxbNode instanceof P) {


            ((P) jaxbNode).getContent().clear();



            wordPkg.getMainDocumentPart().getContent().addAll(index,XHTMLImporter.convert(newText, null, wordPkg));
        } // if node is P

    } // add User name

}

0 个答案:

没有答案