Skip to content

Commit

Permalink
Merge pull request #4 from Zt-freak/dev
Browse files Browse the repository at this point in the history
add multi-line support
  • Loading branch information
Zt-freak authored Apr 12, 2024
2 parents 2715621 + 8e5d4e6 commit fd1e33f
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 4 deletions.
48 changes: 48 additions & 0 deletions NPOI.WordTemplateMapper/Extensions/XWPF/XWPFParagraphExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
using NPOI.XWPF.UserModel;
using System.Text.RegularExpressions;

namespace NPOI.WordTemplateMapper.Extensions.XWPF;

public static class XWPFParagraphExtensions
{
public static void ReplaceTextKeepLineEndings(this XWPFParagraph xwpfParagraph, string textToReplace, string replacementText)
{
string paragraphText = xwpfParagraph.Text;

if (!paragraphText.Contains(textToReplace))
return;

if (!replacementText.Contains('\n'))
{
string textToInsert = paragraphText.Replace(textToReplace, replacementText);
if (!string.IsNullOrEmpty(xwpfParagraph.Text))
xwpfParagraph.ReplaceText(xwpfParagraph.Text, textToInsert);
return;
}

List<int> positionsOfOldTextOccurences = new();
positionsOfOldTextOccurences
.AddRange(
Regex.Matches(paragraphText, Regex.Escape(textToReplace))
.Select(match => match.Index)
);

for (int i = positionsOfOldTextOccurences.Count - 1; i >= 0; i--)
{
int currentPosition = positionsOfOldTextOccurences[i];
paragraphText = paragraphText
.Remove(currentPosition, textToReplace.Length)
.Insert(currentPosition, replacementText);
}

string[] newParagraphsToInsert = paragraphText.Split('\n');
xwpfParagraph.ReplaceText(xwpfParagraph.Text, string.Empty);

XWPFRun run = xwpfParagraph.CreateRun();
foreach (string newParagraph in newParagraphsToInsert)
{
run.AppendText(newParagraph);
run.AddCarriageReturn();
}
}
}
6 changes: 2 additions & 4 deletions NPOI.WordTemplateMapper/XWPF/XWPFParagraphMapper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
using NPOI.WordTemplateMapper.Interfaces.XWPF;
using System.Text.RegularExpressions;
using System.Collections;
using NPOI.WordTemplateMapper.Extensions.XWPF;

namespace NPOI.WordTemplateMapper.XWPF;

Expand Down Expand Up @@ -33,10 +34,7 @@ public XWPFParagraph MapParagraph(XWPFParagraph paragraph, IDictionary<string, o
KeyValuePair<string, string> mappedValue = GetMappedValue(paragraph, mapping);
string oldText = paragraph.Text;

// Workaround for malfunctioning ReplaceText from NPOI
string newText = paragraph.Text.Replace(mappedValue.Key, mappedValue.Value);
if (!string.IsNullOrEmpty(paragraph.Text))
paragraph.ReplaceText(paragraph.Text, newText);
paragraph.ReplaceTextKeepLineEndings(mappedValue.Key, mappedValue.Value);

if (oldText == paragraph.Text)
keepMapping = false;
Expand Down

0 comments on commit fd1e33f

Please sign in to comment.