From d31d51b66e3ce536d896f8c74c0736f995836678 Mon Sep 17 00:00:00 2001 From: Olivier Nizet Date: Mon, 16 Sep 2024 22:51:25 +0200 Subject: [PATCH] Fix detecting reserved __GoBack bookmark and ensure it remains after the appended output --- src/Html2OpenXml/HtmlConverter.cs | 3 ++- test/HtmlToOpenXml.Tests/BodyTests.cs | 24 ++++++++++++++++++++++++ 2 files changed, 26 insertions(+), 1 deletion(-) diff --git a/src/Html2OpenXml/HtmlConverter.cs b/src/Html2OpenXml/HtmlConverter.cs index 5b64b31..a274eec 100755 --- a/src/Html2OpenXml/HtmlConverter.cs +++ b/src/Html2OpenXml/HtmlConverter.cs @@ -125,8 +125,9 @@ public async Task ParseHtml(string html, CancellationToken cancellationToken = d body.Append(para); // move the paragraph with BookmarkStart `_GoBack` as the last child + // That bookmark is continuously moved after the last edit var p = body.GetFirstChild(); - if (p != null && p.GetFirstChild()?.Id == "_GoBack") + if (p != null && p.GetFirstChild()?.Name == "_GoBack") { p.Remove(); body.Append(p); diff --git a/test/HtmlToOpenXml.Tests/BodyTests.cs b/test/HtmlToOpenXml.Tests/BodyTests.cs index 2baeb46..187e2f2 100644 --- a/test/HtmlToOpenXml.Tests/BodyTests.cs +++ b/test/HtmlToOpenXml.Tests/BodyTests.cs @@ -55,5 +55,29 @@ public bool PageOrientation_OverrideExistingLayout_ReturnsLandscapeDimension(str var bidi = mainPart.Document.Body!.GetFirstChild()?.GetFirstChild(); return bidi?.Val?.Value; } + + [Test(Description = "Bookmark _GoBack is reserved and must stand after the last edit change")] + public async Task WithGoBackBookmark_ShouldBeAfterAppendedOutput() + { + using var generatedDocument = new MemoryStream(); + using (var buffer = ResourceHelper.GetStream("Resources.DocWithCustomStyle.docx")) + buffer.CopyTo(generatedDocument); + + generatedDocument.Position = 0L; + using WordprocessingDocument package = WordprocessingDocument.Open(generatedDocument, true); + MainDocumentPart mainPart = package.MainDocumentPart!; + + var goBackBookmark = mainPart.Document.Body!.Elements() + .FirstOrDefault(p => p.GetFirstChild()?.Name?.Value == "_GoBack"); + Assert.That(goBackBookmark, Is.Not.Null); + + HtmlConverter converter = new HtmlConverter(mainPart); + await converter.ParseHtml("

Placeholder

"); + + Assert.That(mainPart.Document.Body!.LastChild, Is.TypeOf()); + var paragrahs = mainPart.Document.Body!.Elements(); + Assert.That(paragrahs.Count(), Is.EqualTo(2)); + Assert.That(paragrahs.Last().GetFirstChild()?.Name?.Value, Is.EqualTo("_GoBack")); + } } } \ No newline at end of file