Page 1 of 1

Replace org.docx4j.wml.Text with Hyperlink

PostPosted: Mon Sep 28, 2015 2:45 am
by micealg
Hi there,

I have a template which contains the text %%WEBSITE%%. I would like to replace all occurrences of this text with a website.

I've been able to locate the org.docx4j.wml.Text object that contains this text; my attempts of replace the text with a hyperlink have failed.
Code: Select all
        WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(templateFile);
        MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();
        org.docx4j.wml.Document wmlDocumentEl = (org.docx4j.wml.Document) documentPart.getJaxbElement();

        String xpath = "//w:r[w:t[contains(text(),'%%WEBSITE%%')]]";

        System.out.println("XPATH " + xpath);
        List<Object> list = documentPart.getJAXBNodesViaXPath(xpath, true);

        for (Object obj : list) {
            org.docx4j.wml.ObjectFactory factory = new org.docx4j.wml.ObjectFactory();
            HyperlinkPlaceHolder placeHolder = new HyperlinkPlaceHolder("%%WEBSITE%%", "http://val", "http://url");
          P para = factory.createP();
          para.getContent().add(placeHolder.getValue(wordMLPackage)); // getValue() returns a Hyperlink
                ((R) obj).getParent().getContent().add(para);

Re: Replace org.docx4j.wml.Text with Hyperlink

PostPosted: Tue Sep 29, 2015 10:03 am
by jason
You are trying to replace something like:

Syntax: [ Download ] [ Hide ]
Using xml Syntax Highlighting
Parsed in 0.000 seconds, using GeSHi


Syntax: [ Download ] [ Hide ]
Using xml Syntax Highlighting
      <w:hyperlink r:id="rId5" >
        <w:r >
            <w:rStyle w:val="Hyperlink"/>
Parsed in 0.001 seconds, using GeSHi

So there are two parts to your problem:

(1) replacing w:r with w:hyperlink
(2) adding the r:id pointing to a new external rel, which you'll also need to add

At a glance, the code you pasted makes no attempt to insert your hyperlink in place of the identified w:r, but that should work, in which case you just need to take care of problem (2). For that you can adapt ...

An alternative approach to solving (1) is to use TraversalUtils. It may be more efficient if you have more than one hyperlink to insert.

Another way completely is to import XHTML containing hyperlinks, then rely on docx4j-ImportXHTML to handle them.

Re: Replace org.docx4j.wml.Text with Hyperlink

PostPosted: Tue Sep 29, 2015 11:49 pm
by micealg
Thanks for your detailed reply.

I opted created a dummy hyperlink in my document and replace it with the correct URL