Page 1 of 1

Insert text on bookmark

PostPosted: Tue Aug 13, 2013 7:32 pm
by netdieter
Hi im new to docx4j.
My problem is how do I insert a text within an template containing some bookmarks.
I'm able to find the bookmarks but i stuck on finding a method to insert text right after the bookmark.

Is there a way to accomplish this?

Thanx

Re: Insert text on bookmark

PostPosted: Tue Aug 13, 2013 8:12 pm
by jason
Assuming you are using TraversalUtil (eg https://github.com/plutext/docx4j/blob/ ... inder.java ),
then you can get from the bookmarkStart to the list containing that object, via getParent.

Then you can delete the content between bookmarkStart and bookmarkEnd, and add a run containing your text.

I guess it would be useful to add a method which does this for you .. A robust version would handle the case where the bookmarkEnd is not in the same paragraph.

Note that for a simple looking sentence:

This is a sentence with a empty slot in it.

Word may generate rather verbose XML:

Syntax: [ Download ] [ Hide ]
Using xml Syntax Highlighting
    <w:p>
      <w:pPr>
        <w:rPr>
          <w:lang w:val="en-AU"/>
        </w:rPr>
      </w:pPr>
      <w:r>
        <w:rPr>
          <w:lang w:val="en-AU"/>
        </w:rPr>
        <w:t xml:space="preserve">This is a sentence with </w:t>
      </w:r>
      <w:proofErr w:type="gramStart"/>
      <w:r>
        <w:rPr>
          <w:lang w:val="en-AU"/>
        </w:rPr>
        <w:t>a</w:t>
      </w:r>
      <w:proofErr w:type="gramEnd"/>
      <w:r>
        <w:rPr>
          <w:lang w:val="en-AU"/>
        </w:rPr>
        <w:t xml:space="preserve"> </w:t>
      </w:r>
      <w:bookmarkStart w:id="0" w:name="bm1"/>
      <w:r>
        <w:rPr>
          <w:lang w:val="en-AU"/>
        </w:rPr>
        <w:t>e</w:t>
      </w:r>
      <w:r>
        <w:rPr>
          <w:lang w:val="en-AU"/>
        </w:rPr>
        <w:t xml:space="preserve">mpty slot </w:t>
      </w:r>
      <w:bookmarkEnd w:id="0"/>
      <w:r>
        <w:rPr>
          <w:lang w:val="en-AU"/>
        </w:rPr>
        <w:t>in it.</w:t>
      </w:r>
    </w:p>
 
Parsed in 0.007 seconds, using GeSHi 1.0.8.4


I'll write some code to do this for you, if you can hang on...

Re: Insert text on bookmark

PostPosted: Tue Aug 13, 2013 9:31 pm
by jason

Re: Insert text on bookmark

PostPosted: Wed Aug 14, 2013 12:19 am
by netdieter
Thanks alot for the quick reply.

Re: Insert text on bookmark

PostPosted: Wed May 21, 2014 12:02 am
by geoM
Hi Jason,

a small correction is necessary in BookmarksReplaceWithText.java
https://github.com/plutext/docx4j/blob/ ... hText.java,
if I am not mistaken.

Instead of:
Code: Select all
if (rangeStart > 0 && rangeEnd > rangeStart) {

should be:
Code: Select all
if (rangeStart >= 0 && rangeEnd > rangeStart) {