Skip to content

Commit

Permalink
Preserve line break pre for OSX/Windows
Browse files Browse the repository at this point in the history
  • Loading branch information
onizet committed Jul 23, 2024
1 parent 042efa1 commit 0a27948
Show file tree
Hide file tree
Showing 5 changed files with 53 additions and 7 deletions.
8 changes: 8 additions & 0 deletions examples/Demo/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,15 @@ static async Task Main(string[] args)
const string filename = "test.docx";
string html = ResourceHelper.GetString("Resources.CompleteRunTest.html");
if (File.Exists(filename)) File.Delete(filename);
const string preformattedText = @"
^__^
(oo)\_______
(__)\ )\/\
||----w |
|| ||";

html = @$"<pre role='img' aria-label='ASCII COW'>
{preformattedText}</pre>";
using (MemoryStream generatedDocument = new MemoryStream())
{
// Uncomment and comment the second using() to open an existing template document
Expand Down
2 changes: 1 addition & 1 deletion src/Html2OpenXml/Expressions/ParsingContext.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ sealed class ParsingContext(HtmlConverter converter, MainDocumentPart mainPart)
private Dictionary<string, object?> propertyBag = [];

/// <summary>Whether the text content should preserve the line breaks.</summary>
public bool PreverseLinebreaks { get; set; }
public bool PreserveLinebreaks { get; set; }

/// <summary>Whether the text content should collapse the whitespaces.</summary>
public bool CollapseWhitespaces { get; set; } = true;
Expand Down
2 changes: 1 addition & 1 deletion src/Html2OpenXml/Expressions/PreElementExpression.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public override IEnumerable<OpenXmlElement> Interpret(ParsingContext context)
{
ComposeStyles(context);
var childContext = context.CreateChild(this);
childContext.PreverseLinebreaks = true;
childContext.PreserveLinebreaks = true;
childContext.CollapseWhitespaces = false;
var childElements = Interpret(childContext, node.ChildNodes);

Expand Down
35 changes: 31 additions & 4 deletions src/Html2OpenXml/Expressions/TextExpression.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ public override IEnumerable<OpenXmlElement> Interpret (ParsingContext context)
string text = node.TextContent.Normalize();
if (text.Trim().Length == 0) return [];

if (!context.PreverseLinebreaks)
if (!context.PreserveLinebreaks)
text = text.CollapseLineBreaks();
if (context.CollapseWhitespaces && text[0].IsWhiteSpaceCharacter() &&
node.PreviousSibling is IHtmlImageElement)
Expand All @@ -41,9 +41,36 @@ public override IEnumerable<OpenXmlElement> Interpret (ParsingContext context)
else if (context.CollapseWhitespaces)
text = text.CollapseAndStrip();

Run run = new(
new Text(text)
);
if (!context.PreserveLinebreaks)
return [new Run(new Text(text))];

var run = new Run();
char[] chars = text.ToCharArray();
int shift = 0, c = 0;
bool wasCR = false; // avoid adding 2 breaks for \r\n
for ( ; c < chars.Length ; c++)
{
if (!chars[c].IsLineBreak())
{
wasCR = false;
continue;
}

if (wasCR) continue;
wasCR = chars[c] == Symbols.CarriageReturn;

if (c > 1)
{
run.Append(new Text(new string(chars, shift, c - shift))
{ Space = SpaceProcessingModeValues.Preserve });
run.Append(new Break());
}
shift = c + 1;
}

if (c > shift)
run.Append(new Text(new string(chars, shift, c - shift))
{ Space = SpaceProcessingModeValues.Preserve });

return [run];
}
Expand Down
13 changes: 12 additions & 1 deletion test/HtmlToOpenXml.Tests/TableTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -387,11 +387,22 @@ public void ParsePreAsTable()
var cell = cells.First();
Assert.Multiple(() =>
{
Assert.That(cell.InnerText, Is.EqualTo(preformattedText));
Assert.That(cell.TableCellProperties?.TableCellBorders.ChildElements.Count(), Is.EqualTo(4));
Assert.That(cell.TableCellProperties?.TableCellBorders.ChildElements, Has.All.InstanceOf<BorderType>());
Assert.That(cell.TableCellProperties?.TableCellBorders.Elements<BorderType>().All(b => b.Val.Value == BorderValues.Single), Is.True);
});

var run = cell.GetFirstChild<Paragraph>()?.GetFirstChild<Run>();
Assert.Multiple(() =>
{
var odds = run.ChildElements.Where((item, index) => index % 2 != 0);
Assert.That(odds, Has.All.TypeOf<Break>());
Assert.That(run.ChildElements.ElementAt(0).InnerText, Is.EqualTo(" ^__^"));
Assert.That(run.ChildElements.ElementAt(2).InnerText, Is.EqualTo(" (oo)\\_______"));
Assert.That(run.ChildElements.ElementAt(4).InnerText, Is.EqualTo(" (__)\\ )\\/\\"));
Assert.That(run.ChildElements.ElementAt(6).InnerText, Is.EqualTo(" ||----w |"));
Assert.That(run.ChildElements.ElementAt(8).InnerText, Is.EqualTo(" || ||"));
});
}

[Test]
Expand Down

0 comments on commit 0a27948

Please sign in to comment.