Page 1 of 1

Replace place holder with HTML content

PostPosted: Sat Feb 09, 2013 9:34 am
by kvmc09302012
How to replace a place holder with html content inside a docx template. Please provide with a sample code.

Below is a sample code which replaces the place holders with values at run time. However, if one the values (DOB) has got html content, it doesn't do it. Kindly provide a sample code to replace a place holder with html.

Code: Select all
package sample;

import java.util.HashMap;

import javax.xml.bind.JAXBContext;

import org.docx4j.XmlUtils;
import org.docx4j.openpackaging.io.SaveToZipFile;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart;
import org.docx4j.wml.Document;

/**
*
*/
public class UnmarshallFromTemplate {

    public static JAXBContext context = org.docx4j.jaxb.Context.jc;

    /**
     * @param args
     */
    public static void main(String[] args) throws Exception {

        String inputfilepath = "input.docx";

        boolean save = true;
        String outputfilepath = "output.docx";


        // Open a document from the file system
        // 1. Load the Package
        WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(new java.io.File(inputfilepath));

        // 2. Fetch the document part           
        MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();

        org.docx4j.wml.Document wmlDocumentEl = (org.docx4j.wml.Document) documentPart
                .getJaxbElement();

        //xml --> string
        String xml = XmlUtils.marshaltoString(wmlDocumentEl, true);

        HashMap<String, String> mappings = new HashMap<>();

        mappings.put("name_last", "chocolate");
        mappings.put("name_first", "chocolate");
        mappings.put("DOB", "<b>1/10/2000</b>");
        mappings.put("address", "Street address");


        //valorize template
        Object obj = XmlUtils.unmarshallFromTemplate(xml, mappings);

        //change  JaxbElement
        documentPart.setJaxbElement((Document) obj);

        // Save it               
        if (save) {
            SaveToZipFile saver = new SaveToZipFile(wordMLPackage);
            saver.save(outputfilepath);
            System.out.println("Saved output to:" + outputfilepath);
        } else {
            // Display the Main Document Part.
        }
    }
}


thanks in advance.

Re: Replace place holder with HTML content

PostPosted: Sun Feb 10, 2013 7:25 pm
by jason
The content control data binding approach has support for XHTML substitution; see the recent post on this.