Reputation: 601
I have been trying to solve one problem in C# regarding updating paragraph text with some additional new text info:
I am not a C# developer, forgive me if the question is silly or easy to solve.
I have several paragraphs like this:
Alice is going to do some shopping.
Bob is a good guy.
Let's say, these paragraphs are written in Arial font with 11 pts. So I want to add some text after each paragraph.
The end result would be:
Alice is going to do some shopping.SomeText0
Bob is a good guy.SomeText1
I have tried this:
using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(document, true))
{
List<Paragraph> paragraphs = paragraphService.GetParagraphs(wordDoc);
foreach (Paragraph par in paragraphs)
{
string paragraphText = paragraphService.ParagraphToText(par);
paragraphText = textService.DeleteDoubleSpace(paragraphText);
if (paragraphText.Length != 0)
{
if (paragraphText == targetParagraph)
{
//Here I know that the added text will be corresponding to the my target paragraph.
//This paragraph comes from a JSON file but for simplicity I did not add that part.
par.Append(new Run(new Text("SomeText0")));
par.ParagraphProperties.CloneNode(true);
}
}
}
}
Adding the text works, but the style is not the same and some random style that I don't want. I want the newly added text to have the same font and size as the paragraph.
I have also tried several options, to make it Paragraph, just text, etc. But I could not find a solution.
Any help would be appreciated.
Upvotes: 0
Views: 906
Reputation: 7187
The open xml format stores paragraphs like the following
<w:p>
<w:r>
<w:t>String from WriteToWordDoc method.</w:t>
</w:r>
</w:p>
Here,
Paragraph
class,Run
class, and,Text
class.So you are appending a new <w:r> => Run
element which has its own format settings, and since you don't specify any formatting, defaults are used.
EDIT 1: And as it seems, when there are parts in this paragraph that are formatted differently, there can be multiple Run elements under a paragraph.
So, instead you can find the last Run element containing a Text element and modify its text.
foreach (Paragraph par in paragraphs)
{
Run[] runs = par.OfType<Run>().ToArray();
if (runs.Length == 0) continue;
Run[] runsWithText = runs.Where(x => x.OfType<Text>().ToArray().Length > 0).ToArray();
if (runsWithText.Length == 0) continue;
Text lastText = runsWithText.Last().OfType<Text>().Last();
lastText.Text += " Some Text 0";
}
Hope this helps.
Upvotes: 1