I'm using a content control in a Word template into which I programmatically add text (using java). This works fine. Now I would like to insert a new line at each new sentence in the text. Is there a way to configure the content control so that it automatically does this?
I am afraid you cannot configure Content Controls to do this automatically.
However, if you fill the Content Controls via the Word object model, you could simply use a Rich Text Content Control or a Plain Text Content Control, the latter with the option to "allow carriage returns (multiple paragraphs)" (MultiLine in the object model) activated, and fill it with text containing line breaks.
For a quick test I have added such a Plain Text Content Control to an empty document and used the following VBA code:
Sub FillContentControl()
ContentControls(1).Range.Text = "Sentence One." & vbNewLine & "Sentence Two."""
End Sub
In my example, this produced the following output:
Sentence One.
Sententce Two.
You should of course rather add the linebreaks in your Java code. You will just have to detect where your sentences end.
If, as your request for a docx4j-based solution indicates, you do not fill out your Content Control via Word but directly into the docx, I could think of another workaround involving a VBA Macro (which I usually would not recommend): You could add an event handler for the Document.Open event to update all flagged Content Controls in the document. It could look like this:
Private Sub Document_Open()
For Each ContentControl In ThisDocument.ContentControls
If ContentControl.Tag = "TODO_Add_Linebreaks" Then
ContentControl.Range.Text = Replace(ContentControl.Range.Text, ". ", "." & vbNewLine)
ContentControl.Tag = ""
End If
Next
End Sub
This second solution requires that you add your Content Controls with the Tag "TODO_Add_Linebreaks" (or whatever indication you prefer) and that you make your documents Macro-enabled.
You can use a w:br element, like so:
<w:p>
<w:sdt>
<w:sdtPr>
<w:id w:val="711844519"/>
</w:sdtPr>
<w:sdtContent>
<w:r>
<w:t>foo</w:t>
<w:br/>
<w:t>bar</w:t>
</w:r>
</w:sdtContent>
</w:sdt>
<w:r>
</w:p>
For how to add one of those using docx4j, see linebreaks-in-strings
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.