2

I want to create a Word file with GemBox.Document, but I get an InvalidOperationException:

Dim text As String = "Foo" + vbTab + "Bar"
Dim document As New DocumentModel()

document.Sections.Add(
    New Section(document,
        New Paragraph(document, text)))

System.InvalidOperationException: 'Text cannot contain new line ('\n'), carriage return ('\r') or tab ('\t') characters. If you want to break the text or insert a tab, insert SpecialCharacter instance with specific SpecialCharacterType to the parent's InlineCollection.'

How can I do that "break the text or insert a tab"?

4

1 回答 1

3

UPDATE:

In the current latest bug fix version for GemBox.Document this is no longer the case.
That Paragraph's constructor from now own handles the special characters for you.

However, note that nothing has changed regarding the Run's constructor and Run's Text property, they still do not accept special characters.


First note that using this Paragraph's constructor:

New Paragraph(document, text)

Is the same as using something like the following:

Dim paragraph As New Paragraph(document)
Dim run As New Run(document, text)
paragraph.Inlines.Add(run)

And the problem is that Run element cannot contain any special characters (see Run.Text property remarks).
Those characters are represented with their own elements so you need something like the following:

document.Sections.Add(
    New Section(document,
        New Paragraph(document,
            New Run(document, "Foo"),
            New SpecialCharacter(document, SpecialCharacterType.Tab),
            New Run(document, "Bar"))))

Or alternativaly you could take advantage of LoadText method which can handle those special characters for you, like the following:

Dim text As String = "Foo" + vbTab + "Bar" + vbNewLine + "Sample"
Dim document As New DocumentModel()

Dim section As New Section(document)
document.Sections.Add(section)

Dim paragraph As New Paragraph(document)
paragraph.Content.LoadText(text)
section.Blocks.Add(paragraph)

I hope this helps.

于 2017-09-21T15:02:13.983 回答