Page 1 of 1

string to replace not found

PostPosted: Thu Feb 21, 2013 7:29 am
by fachhoch
I want to replace a place holder , for which I create placeholder like ${paceholder1} in the document , to replace i use the code below
Code: Select all
         List<Object> texts = getAllElementFromObject(template.getMainDocumentPart(), Text.class);
         replacePlaceHolders(texts, mappings);

   private static void replacePlaceHolders(List<?> texts,Map<String, String>  mappings){
      for (Object object : texts) {
         Text  textElement=(Text)object;
         String textToReplace=textElement.getValue();
         if(mappings.keySet().contains(textToReplace)){
            textElement.setValue(mappings.get(textToReplace));
         }
      }
   }




surprisingly in the above code textElement.getValue(); never returns ${paceholder1}.

below is document.xml , word replaces my place holder to below

Code: Select all
<w:r w:rsidR="006F02F0">
            <w:rPr>
               <w:b/>
               <w:szCs w:val="24"/>
            </w:rPr>
            <w:t>${</w:t>
         </w:r>
         <w:r w:rsidR="006E3760">
            <w:rPr>
               <w:szCs w:val="24"/>
            </w:rPr>
            <w:t>paceholder1</w:t>
         </w:r>
         <w:r w:rsidR="006F02F0">
            <w:rPr>
               <w:szCs w:val="24"/>
            </w:rPr>
            <w:t>}</w:t>
         </w:r>



please suggest me is there any way to avoid this, tell word not to split my placeholder ?

Re: string to replace not found

PostPosted: Thu Feb 21, 2013 7:50 am
by jason
That's the trap you need to avoid if you are using simple-minded string replacement; its one of several reasons I recommend content control data binding instead.

Having said that, you can clean up with https://github.com/plutext/docx4j/blob/ ... epare.java

Alternatively, in Word, you can turn off rsIds and spelling/grammar correction, to stop this happening a bit. It won't help if part of your variable name is bold or underlined.

Re: string to replace not found

PostPosted: Sat Feb 23, 2013 7:08 am
by fachhoch
Thanks, I tried with a test document it restored my placeholders. After running VariablePrepare for a document if I open again are there chances for word to mess it up again ?
should I always run it before replacing my placeholders or just run it once after editing a document ?

Re: string to replace not found

PostPosted: Sat Feb 23, 2013 7:28 am
by jason
fachhoch wrote:After running VariablePrepare for a document if I open again are there chances for word to mess it up again ?


Yes, but as I said, in Word, you can turn off rsIds and spelling/grammar correction

fachhoch wrote:should I always run it before replacing my placeholders or just run it once after editing a document ?


?

You can run it just once, provided you save the output docx and use that fixed one.