diff --git a/CHANGELOG.md b/CHANGELOG.md index 45e2e04d..dfde7de2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,21 @@ # Changelog +## 4.2.0 + +Ease of Use Improvements: + +- New `WordDocumentFactory.Create()` helper. +- New `HtmlConverter(WordProcessingDocument)` constructor overload. +- Automatic creation of missing document structure (`MainDocumentPart`, `Body`). +- New `PageOrientation` support for document creation. +- Introduce a new companion library: `HtmlToOpenXml.CssInliner` + +- Improve numbering list items which do not inherit styling from the parent list #252 +- Fix text-align: left being ignored- #263, thanks to @cyril265 +- Numbering list now support border style. +- Fix indentation and hanging of nested paragraph in numbering list. +- Improve code robustness and quality + ## 4.1.0 - Support CSS shorthand for `border` style, co-authored with @AyUsH18102001. diff --git a/Directory.Build.props b/Directory.Build.props index 67c07c88..77e8e3a6 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -2,13 +2,9 @@ Copyright 2009-$([System.DateTime]::Today.Year) Olivier Nizet enable - latest + preview enable - 4.1.0 - - - - 3.5.1 + 4.2.0 diff --git a/Directory.Packages.props b/Directory.Packages.props new file mode 100644 index 00000000..44f68469 --- /dev/null +++ b/Directory.Packages.props @@ -0,0 +1,39 @@ + + + true + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/HtmlToOpenXml.slnx b/HtmlToOpenXml.slnx index f1a0880a..4ec92b3c 100644 --- a/HtmlToOpenXml.slnx +++ b/HtmlToOpenXml.slnx @@ -1,10 +1,11 @@ + - + diff --git a/README.md b/README.md index 4f417c21..c573741e 100644 --- a/README.md +++ b/README.md @@ -22,9 +22,7 @@ When creating a blank document: await using var generatedDocument = new MemoryStream(); using var package = WordprocessingDocument.Create(generatedDocument, WordprocessingDocumentType.Document); -var mainPart = package.AddMainDocumentPart(); -new Document(new Body()).Save(mainPart); -HtmlConverter converter = new(mainPart); +HtmlConverter converter = new(package); await converter.ParseBody(html); ``` @@ -33,14 +31,9 @@ When inserting inside an existing document: ```csharp await using var generatedDocument = new MemoryStream(); await templateFileStream.CopyToAsync(generatedDocument); +generatedDocument.Position = 0L; using var package = WordprocessingDocument.Open(generatedDocument, true); -MainDocumentPart? mainPart = package.MainDocumentPart; -if (mainPart == null) -{ - mainPart = package.AddMainDocumentPart(); - new Document(new Body()).Save(mainPart); -} -HtmlConverter converter = new(mainPart); +HtmlConverter converter = new(package); await converter.ParseBody(html); ``` diff --git a/docs/.vuepress/public/nuspec-ai.txt b/docs/.vuepress/public/nuspec-ai.txt index 19d3e626..88ba80a5 100644 --- a/docs/.vuepress/public/nuspec-ai.txt +++ b/docs/.vuepress/public/nuspec-ai.txt @@ -1,7 +1,7 @@ -#NuSpec.AI/v2 HtmlToOpenXml 4.0.0 +#NuSpec.AI/v2 HtmlToOpenXml 4.2.0 #desc Convert simple or advanced HTML into OpenXML Word content while reusing existing document styles, numbering, and templates. #tfm netstandard2.0;net462;net8.0;net10.0 -#dep AngleSharp|1.8.0|0;DocumentFormat.OpenXml|3.5.1|0;Microsoft.Extensions.Logging.Abstractions|6.0.0|0;System.ValueTuple|4.5.0|0 +#dep AngleSharp|1.8.6|0;DocumentFormat.OpenXml|3.5.1|0;Microsoft.Extensions.Logging.Abstractions|6.0.0|0;System.ValueTuple|4.6.2|0 @e AcronymPosition "Controls where the definition of an acronym or abbreviation is rendered during conversion. AcronymFor example, the definition assocaited with an HTML abbr element can be rendered at the end of the page or collected at the end of the document." .ev PageEnd=0,DocumentEnd=1 @c DefaultStyles [entity] "Contains the default OpenXml style mappings used by HtmlToOpenXml.HtmlConverter. Styles selected through these mappings provide the base formatting. CSS attributes defined on HTML elements are still applied on top of the resulting Word style. Several commonly used Word styles such as headings, hyperlinks, captions, tables, footnotes and quotes can be created automatically when missing from the document. Customise these mappings to use your own style names during conversion." @@ -18,14 +18,12 @@ .p QuoteStyle:string "Default style for quotes (quote, cite)." .p IntenseQuoteStyle:string "Default style for intense quotes (blockquote)." .p TableStyle:string "Default style for tables (table)." - .p HeaderStyle:string "Default style for any paragraphs (p) in the header section (DocumentFormat.OpenXml.Packaging.HeaderPart )." .p ParagraphHeaderStyle:string "Default style for any paragraphs (p) in the header section (DocumentFormat.OpenXml.Packaging.HeaderPart )." - .p FooterStyle:string "Default style for any paragraphs (p) in the footer section (DocumentFormat.OpenXml.Packaging.FooterPart )." .p ParagraphFooterStyle:string "Default style for any paragraphs (p) in the footer section (DocumentFormat.OpenXml.Packaging.FooterPart )." - .p Paragraph:string "Default style for body paragraph (body or any top level tag in HTML source)." .p ParagraphBodyStyle:string "Default style for paragraph (p or body or any top level tag in HTML source) in the body section." @c HtmlConverter "Primary entry point for converting HTML into OpenXml Word document. The converter can be used with newly created documents as well as existing document templates. When a template is used, styles, themes, numbering definitions, bookmarks, and other Word settings are automatically reused. Supports both left-to-right (LTR) and right-to-left (LTR) visual flow content. Direction can be specified using the HTML dir attribute (recommended) or inferred from the lang attribute. When not specified, the converter preserves the layout defined by the target Word document. Supports full OpenXML table translation, including complex structural elements (nested tables, `colspan`/`rowspan`) and precise dimension mapping (`px`, `%`), column definitions, vertical text, and automatic conversion of table widths. Table widths can be specified using auto, percentages, or fixed dimensions (px/pt). Use HtmlToOpenXml.HtmlConverter.HtmlStyles to customise styling and HtmlToOpenXml.IO.IWebRequest to customise external resource retrieval. Typical usage: Create an HtmlConverter from a MainDocumentPart obtained from a WordProcessingDocument. Call ParseBody() to append the converted content to the document body. Advanced scenarios can use ParseAsync() to control where the generated OpenXml elements are inserted." .ctor (MainDocumentPart mainPart, IWebRequest? webRequester = null) "Create a converter bound to a Word document. Reuse the same HtmlConverter instance for the lifetime of a document to avoid reloading cached configuration such as styles and bookmarks. Do not use the same converter instance with multiple documents." + .ctor (WordprocessingDocument package, IWebRequest? webRequester = null) "Create a converter bound to a Word document. Reuse the same HtmlConverter instance for the lifetime of a document to avoid reloading cached configuration such as styles and bookmarks. Do not use the same converter instance with multiple documents." .m Parse:IList(string html) "Convert HTML into OpenXml elements and return them to the caller. Use this method when your HTML is simple and don't need to download any external resources. Parse() is equivalent to ParseAsync() and is retained for backward compatibility. New code should prefer ParseBody(), ParseHeader() or ParseFooter() to make the target document section explicit." .m ParseAsync:Task>(string html, CancellationToken cancellationToken = null) "Convert HTML into OpenXml elements and return them to the caller. However, the conversion process itself may still update the underlying document by creating styles, numbering definitions, image parts, bookmarks, or other resources required by the generated content. Use this method when you need full control over the insertion point or need to inspect or modify the generated elements before adding them to the document. For most scenarios, prefer ParseBody()." .m ParseAsync:Task>(string html, ParallelOptions parallelOptions) "Convert HTML into OpenXml elements and return them to the caller. Use this method when you need full control over the insertion point or need to inspect or modify the generated elements before adding them to the document. For most scenarios, prefer ParseBody()." @@ -43,11 +41,6 @@ .p SupportsHeadingNumbering:bool "Defines whether (h1-h6) elements are mapped to the corresponding Word heading style. Missing heading styles are added automatically when required. When heading text begins with a numbering pattern such as "1.", "1.1.", or "1 " or when the heading uses the `decimal-tiered` CSS class, the converter interprets it as a numbered heading. Any associated heading numbering is then managed by Word through the Heading styles. This feature is enabled by default." @e ImageProcessingMode "Controls whether images are embedded in the generated document or kept as external references." .ev Embed=0,LinkExternal=1,EmbedDataUriOnly=2 -@c DataUri "Represents a Data URI containing inline content encoded directly in the URI string, typically using Base64 encoding. Data URIs are commonly used to embed images in HTML without referencing an external resource, for example: data:image/png;base64,..." - .m TryCreate:bool(string uri, out DataUri? result) "Parse an instance of the Data URI scheme." - .m IsWellFormed:bool(string uri) "Indicates whether the string is well-formed by attempting to construct a DataUri with the string." - .p Mime:string "Gets the MIME type declared by the Data URI, such as image/png or image/jpeg." - .p Data:byte[] "Gets the decoded binary content extracted from the Data URI." @c DefaultWebRequest "Default implementation of HtmlToOpenXml.IO.IWebRequest. Supports http, https, local file and inline data (base64). Derive from this class to customise resource retrieval, authentication, image processing, URL resolution, or content transformation while reusing the built-in behaviour." .ctor (ILogger? logger = null) "Initialize a new instance of the HtmlToOpenXml.IO.DefaultWebRequest class." .ctor (HttpClient httpClient, ILogger? logger = null) "Initialize a new instance of the HtmlToOpenXml.IO.DefaultWebRequest class with the specified HttpClient. Supply your own HttpClient to customise how external resources are retrieved, for example to configure cookies, authentication headers, API keys, proxies, or message handlers." @@ -62,6 +55,8 @@ .p Headers:string> "Optional response Http headers. Content-Type is used when the resource type cannot be determined from the URL." .p Content:Stream "Gets the resource content stream. The stream must be readable.Resource type detection may inspect the beginning of the stream and reset its position afterwards, therefore the stream should support seeking." .m Dispose:void() +@e PageOrientation "Specifies the page orientation used when creating a new Word document. The orientation determines whether pages are laid out vertically (portrait) or horizontally (landscape)." + .ev Portrait=0,Landscape=1 @s QuoteChars "Predefined quote style as defined by the browser (used for the q HTML tag)." .ctor (string begin, string end) "Predefined quote style as defined by the browser (used for the q HTML tag)." .f IE:QuoteChars "Internet Explorer style: « abc »" @@ -70,6 +65,8 @@ @c StyleEventArgs [entity] "Provides information about a style requested during conversion that could not be found in the Word document. The HtmlToOpenXml.WordDocumentStyle.StyleMissing event uses these arguments to indicate which style should be dynamically provisioned and which OpenXml style type is expected." .p Name:string "Gets the identifier of the missing style. Use this value when creating and registering the style." .p Type:StyleValues "Gets the OpenXml style type expected by the converter, such as paragraph, table or character." +@c WordDocumentFactory [factory] "Provides helper methods for creating Word documents configured for use with HtmlToOpenXml.HtmlConverter. This factory simplifies the creation of new DOCX documents by configuring the required OpenXML package structure, document parts, and page settings. The generated documents can be used directly with HtmlToOpenXml.HtmlConverter to convert HTML content into WordProcessingML." + .m Create:WordprocessingDocument(Stream stream, PageOrientation orientation = Portrait) "Create a new Word document on the specified stream and configures its page settings. The created document contains the minimum required OpenXML structure, including a main document part and an empty body. The returned document can be passed directly to HtmlToOpenXml.HtmlConverter or further customised using the Open XML SDK." @c WordDocumentStyle "Provides style-related services used during HTML conversion. HTML class names may be mapped directly to Word styles with the same name (case insensitive). When a referenced style cannot be found, the HtmlToOpenXml.WordDocumentStyle.StyleMissing event allows it to be provisioned dynamically." .m AddStyle:void(Style style) "Adds a new style to the Word document and refreshes the converter's internal style cache. Use this method in conjunction with the HtmlToOpenXml.WordDocumentStyle.StyleMissing event to inject styles required by a template that are absent from the source document." .p DefaultStyles:DefaultStyles "Contains the default styles for new OpenXml elements, created during the conversion process." diff --git a/docs/guide/api.md b/docs/guide/api.md index 1c610b2d..fcf80f37 100644 --- a/docs/guide/api.md +++ b/docs/guide/api.md @@ -45,3 +45,41 @@ Purpose: Converts HTML into a standalone, actionable collection of OpenXML eleme * **Use Case:** You are building a custom element, merging snippets from multiple sources, or needing to inspect and modify the generated code before injecting it into a document. * **Note on Synchronicity**: Use `Parse()` for basic, non-resource-dependent conversions. Use `ParseAsync()` when the content requires external resource fetching (images, links) or longer processing time. + +## Advanced Extension Hooks (Optional) + +`HtmlConverter` can be extended by overriding two virtual methods that participate in the HTML parsing pipeline. +These hooks are intended for advanced scenarios such as CSS inlining, DOM transformations, custom AngleSharp integrations, URL rewriting, or document validation before conversion. + +### `GetParserConfiguration()` + +* **Purpose:** Provides the `AngleSharp` configuration used to parse the input HTML before conversion begins. + +* **Use Case:** Override this method to register AngleSharp extensions, services, or features required during +document parsing. Typical scenario include enabling support for CSS processing, custom resource loaders, or other AngleSharp integrations. + +* **Default Behavior:** Returns `Configuration.Default`, providing standard HTML parsing behaviour. + +```csharp +protected override IConfiguration GetParserConfiguration() +{ + return Configuration.Default + .WithCss(); +} +``` + +### `OnDocumentLoadedAsync()` + +* **Purpose:** Executes after the HTML has been parsed into an AngleSharp document but before any OpenXML elements or image resources are generated. + +* **Use Case:** Inspect or alter the DOM before conversion. Typical sccenarios include: + * Inlining CSS stylesheets + * Rewriting image URLs + * Removing unsupported elements + * Adding custom attributes + * Performing document validation + +* **Default Behavior:** Performs no action. + +* **Note:** Any changes made to the DOM are used by all subsequent conversion stages, including the image discovery, +resource loading, and OpenXML conversion. diff --git a/docs/guide/images.md b/docs/guide/images.md index 306945c8..9ec4ed63 100644 --- a/docs/guide/images.md +++ b/docs/guide/images.md @@ -96,7 +96,7 @@ class WebPWebRequest : DefaultWebRequest if (resource.Content is not null && requestUri.OriginalString.EndsWith(".webp")) { // Load, convert to PNG stream, and replace the original resource content. - using var img = await Image.LoadAsync(resource.Content, cancellationToken); + using var img = await SixLabors.ImageSharp.Image.LoadAsync(resource.Content, cancellationToken); var convertedStream = new MemoryStream(); await img.SaveAsPngAsync(convertedStream, cancellationToken); diff --git a/docs/guide/quickstart.md b/docs/guide/quickstart.md index 17ddbe24..14b4c384 100644 --- a/docs/guide/quickstart.md +++ b/docs/guide/quickstart.md @@ -29,19 +29,10 @@ using HtmlToOpenXml; using (var generatedDocumentStream = new MemoryStream()) { // Initialize the DOCX package structure. This must happen before conversion. - using (WordprocessingDocument package = WordprocessingDocument.Create(generatedDocumentStream, WordprocessingDocumentType.Document)) + using (WordprocessingDocument document = WordDocumentFactory.Create(generatedDocumentStream)) { - MainDocumentPart mainPart = package.MainDocumentPart; - - // Ensure the body is ready to receive content (optional, but robust). - if (mainPart?.Document == null) - { - mainPart = package.AddMainDocumentPart(); - new Document(new Body()).Save(mainPart); - } - // Initialize the Converter, binding it to the target document part. - HtmlConverter converter = new HtmlConverter(mainPart); + HtmlConverter converter = new HtmlConverter(document); // Perform the conversion into the document body. await converter.ParseBody(htmlInput); @@ -78,3 +69,36 @@ DemoHtml.html: ### Step 3: Visual generated output ![Quickstart output in MS Word](/images/quickstart.png) + +## Page Orientation + +Use the `PageOrientation` enumeration when creating a new document. + +```csharp +using var document = WordDocumentFactory.Create(stream, PageOrientation.Landscape); +HtmlConverter converter = new HtmlConverter(document); +await converter.ParseBody(htmlInput); +``` + +## Using an existing template + +HtmlToOpenXml can append content to an existing Word template while preserving its styles, themes, +numbering definitions, headers, footers, bookmarks and other document settings. + +```csharp +await using var templateStream = File.OpenRead("template.docx"); + +await using var generatedDocument = new MemoryStream(); +await templateStream.CopyToAsync(generatedDocument); +generatedDocument.Position = 0L; + +using var package = WordprocessingDocument.Open(generatedDocument, true); +HtmlConverter converter = new(package); +await converter.ParseBody(""" +

Project Report

+

This content uses the styles already defined in the template.

+"""); +``` + +This approach is recommended when your organisation already maintains a Word template containing +corporate branding, custom styles, predefined headers, footers or document settings. diff --git a/docs/guide/styling.md b/docs/guide/styling.md index 5cd085d6..92514bd4 100644 --- a/docs/guide/styling.md +++ b/docs/guide/styling.md @@ -1,7 +1,7 @@ --- lang: en-US title: Styling -description: +description: Documentation for HTML, CSS, and OpenXml style handling, including class mapping, default styles and CSS inlining. --- The `HtmlToOpenXml` converter serves as the bridge between the flexible structure of HTML and the rigorous object model of DOCX. The resulting fidelity depends on how you leverage the built-in style detection and mapping capabilities of the converter. @@ -41,7 +41,8 @@ To override the default behavior or apply a unique style, use the `class` attrib ...
``` -*The converter attempts to locate and apply styles matching the class names (`Standard_Table`, `TableWhite`).* +*The converter attempts to locate and apply styles matching the class names (`Standard_Table`, `TableWhite`), performing a runtime translation +between your HTML structure and the target DOCX.* ## OpenXml style mapping @@ -91,7 +92,7 @@ If it is not found, you can provide your own OpenXml style definition. In this sample, the converter will try to find a style with the name **Standard_Table** and if not found, **TableWhite**. -### Provision your style +### Advanced Workflow: Handling Missing Styles If you add this line of code in the startup example and run it again, you will not see the "Heading 1" style applied. @@ -102,8 +103,6 @@ If you add this line of code in the startup example and run it again, you will n In fact, the "Heading 1" style is well applied but this style does not exists in the document ; when you create a new document, no styles are defined : it's up to you. HtmlToOpenXml handles automatically the hyperlink style for you but it does not deal with every styles. You can subscribe to the StyleMissing event to be warned and add them yourself. - - Generally, you will load in memory an existing document template and append the Html conversion inside it. MS Word 2007 embeds a lot of informations (like styles, themes, document properties, ...) that you don't really want to bother with. ## Dynamic Style Provisioning @@ -131,11 +130,40 @@ converter.HtmlStyles.StyleMissing += delegate(object sender, StyleEventArgs args ## Note on External CSS -The converter does not process external stylesheets (``) or ` +

Black text

+

Colored text

+ """); + + Assert.That(elements, Has.Count.EqualTo(2)); + Assert.That(elements, Has.All.TypeOf()); + using (Assert.EnterMultipleScope()) + { + Assert.That(elements[0].GetFirstChild()?.RunProperties?.Color?.Val?.Value, Is.Null); + Assert.That(elements[1].GetFirstChild()?.RunProperties?.Color?.Val?.Value, Is.EqualTo("FF0000")); + } + } + + [Test] + public void ParsePriorityStyleTag_ShouldBeOverriden() + { + var elements = converter.Parse(""" + +

Black text

+

Colored text

+ """); + + Assert.That(elements, Has.Count.EqualTo(2)); + Assert.That(elements, Has.All.TypeOf()); + using (Assert.EnterMultipleScope()) + { + Assert.That(elements[0].GetFirstChild()?.RunProperties?.Color?.Val?.Value, Is.Null); + Assert.That(elements[1].GetFirstChild()?.RunProperties?.Color?.Val?.Value, Is.EqualTo("FF0000")); + } + } + + [Test] + public void ParseLowerPriorityStyleTag_ShouldBeIgnored() + { + var elements = converter.Parse(""" + +

Black text

+

Colored text

+ """); + + Assert.That(elements, Has.Count.EqualTo(2)); + Assert.That(elements, Has.All.TypeOf()); + using (Assert.EnterMultipleScope()) + { + Assert.That(elements[0].GetFirstChild()?.RunProperties?.Color?.Val?.Value, Is.Null); + Assert.That(elements[1].GetFirstChild()?.RunProperties?.Color?.Val?.Value, Is.EqualTo("008000")); + } + } +} \ No newline at end of file diff --git a/test/HtmlToOpenXml.CssInliner.Tests/StylesheetTests.cs b/test/HtmlToOpenXml.CssInliner.Tests/StylesheetTests.cs new file mode 100644 index 00000000..db99f89a --- /dev/null +++ b/test/HtmlToOpenXml.CssInliner.Tests/StylesheetTests.cs @@ -0,0 +1,92 @@ +using NUnit.Framework; +using DocumentFormat.OpenXml.Packaging; +using DocumentFormat.OpenXml.Wordprocessing; +using Moq; + +namespace HtmlToOpenXml.CssInliner.Tests; + +/// +/// CSS Tests parser for stylesheets. +/// +[TestFixture] +public class StylesheetTests +{ + private MemoryStream generatedDocument = default!; + private WordprocessingDocument package = default!; + private CssStyleHtmlConverter converter; + private Mock webRequest; + + + [SetUp] + public void Init () + { + webRequest = new Mock(); + webRequest.Setup(x => x.FetchAsync(It.IsAny(), It.IsAny())) + .Returns(Task.FromResult(new() { + Content = new MemoryStream(System.Text.Encoding.ASCII.GetBytes(""" + p#para2 { color: green } + """)), + StatusCode = System.Net.HttpStatusCode.OK + })); + webRequest.Setup(x => x.SupportsProtocol(It.Is(s => s == "http"))) + .Returns(true); + + generatedDocument = new MemoryStream(); + package = WordDocumentFactory.Create(generatedDocument); + converter = new CssStyleHtmlConverter(package, webRequest.Object); + } + + [TearDown] + public void Close () + { + package?.Dispose(); + generatedDocument?.Dispose(); + } + + [Test] + public void ExternalStylesheet_ShouldDownload() + { + var elements = converter.Parse(""" + +

Black text

+

Colored text

+ """); + + Assert.That(elements, Has.Count.EqualTo(2)); + Assert.That(elements, Has.All.TypeOf()); + using (Assert.EnterMultipleScope()) + { + Assert.That(elements[0].GetFirstChild()?.RunProperties?.Color?.Val?.Value, Is.Null); + Assert.That(elements[1].GetFirstChild()?.RunProperties?.Color?.Val?.Value, Is.EqualTo("008000")); + } + + webRequest.Verify(s => s.FetchAsync( + It.Is(u => u.AbsolutePath.EndsWith("style1.css")), + It.IsAny()), + Times.Once); + } + + [Test] + public void ExternalStylesheet_ShouldResolvePriorStyleTag() + { + var elements = converter.Parse(""" + + +

Black text

+

Colored text

+ """); + + Assert.That(elements, Has.Count.EqualTo(2)); + Assert.That(elements, Has.All.TypeOf()); + using (Assert.EnterMultipleScope()) + { + Assert.That(elements[0].GetFirstChild()?.RunProperties?.Color?.Val?.Value, Is.Null); + Assert.That(elements[1].GetFirstChild()?.RunProperties?.Color?.Val?.Value, Is.EqualTo("FF0000")); + } + + webRequest.Verify(s => s.FetchAsync( + It.Is(u => u.AbsolutePath.EndsWith("style1.css")), + It.IsAny()), + Times.Once); + } +} \ No newline at end of file diff --git a/test/HtmlToOpenXml.Tests/HeadingTests.cs b/test/HtmlToOpenXml.Tests/HeadingTests.cs index 387e0a88..6ec49472 100644 --- a/test/HtmlToOpenXml.Tests/HeadingTests.cs +++ b/test/HtmlToOpenXml.Tests/HeadingTests.cs @@ -14,19 +14,21 @@ public class HeadingTests : HtmlConverterTestBase [TestCase("

1. Heading 1

1.1 Heading Double Space

", Description = "Double space after number")] [TestCase("

1. Heading 1

1.2 Heading Tab

", Description = "Tab after number")] [TestCase("

1. Heading 1

1.3Heading No Space

", Description = "No space after number")] + [TestCase("

1. Heading 1

1.3Heading No Space

", Description = "Bold stripped out")] + [TestCase("

1. Heading 1

1.3Heading No Space

", Description = "Bold stripped out")] + public void OrderedPattern_ReturnsNumberingHeading(string html) { var elements = converter.Parse(html); var absNum = mainPart.NumberingDefinitionsPart?.Numbering? .Elements() - .Where(abs => abs.AbstractNumDefinitionName?.Val == NumberingExpressionBase.HeadingNumberingName) - .SingleOrDefault(); + .SingleOrDefault(abs => abs.AbstractNumDefinitionName?.Val == NumberingExpressionBase.HeadingNumberingName); Assert.That(absNum, Is.Not.Null); var inst = mainPart.NumberingDefinitionsPart?.Numbering? - .Elements().Where(i => i.AbstractNumId?.Val == absNum.AbstractNumberId) - .FirstOrDefault(); + .Elements() + .FirstOrDefault(i => i.AbstractNumId?.Val == absNum.AbstractNumberId); Assert.That(inst, Is.Not.Null); Assert.That(inst.NumberID?.Value, Is.Not.Null); @@ -62,8 +64,7 @@ public void OrderedPattern_DisableNumberingSupports_ReturnsSimpleHeading(string var absNum = mainPart.NumberingDefinitionsPart?.Numbering? .Elements() - .Where(abs => abs.AbstractNumDefinitionName?.Val == NumberingExpressionBase.HeadingNumberingName) - .SingleOrDefault(); + .SingleOrDefault(abs => abs.AbstractNumDefinitionName?.Val == NumberingExpressionBase.HeadingNumberingName); Assert.That(absNum, Is.Null); var paragraphs = elements.Cast(); @@ -109,8 +110,7 @@ public void NumberingWithNoTextPattern_ReturnsSimpleHeading() var absNum = mainPart.NumberingDefinitionsPart?.Numbering? .Elements() - .Where(abs => abs.AbstractNumDefinitionName?.Val == NumberingExpressionBase.HeadingNumberingName) - .SingleOrDefault(); + .SingleOrDefault(abs => abs.AbstractNumDefinitionName?.Val == NumberingExpressionBase.HeadingNumberingName); Assert.That(absNum, Is.Null); var paragraphs = elements.Cast(); @@ -123,5 +123,20 @@ public void NumberingWithNoTextPattern_ReturnsSimpleHeading() "First paragraph is not a numbering"); } } + + [Test] + public void HeadingSpanMultipleTextNodes_StripTheNumbering() + { + var run = new Run( + new Text(" "), + new Text("1."), + new Text("2 "), + new Text("Heading") + ); + var success = HeadingElementExpression.TryStripHeadingNumbering(run); + + Assert.That(success, Is.True); + Assert.That(run.InnerText, Is.EqualTo(" Heading")); + } } } \ No newline at end of file diff --git a/test/HtmlToOpenXml.Tests/HtmlConverterTestBase.cs b/test/HtmlToOpenXml.Tests/HtmlConverterTestBase.cs index 2b56cac0..3b7cbc02 100644 --- a/test/HtmlToOpenXml.Tests/HtmlConverterTestBase.cs +++ b/test/HtmlToOpenXml.Tests/HtmlConverterTestBase.cs @@ -1,7 +1,6 @@ using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Validation; -using DocumentFormat.OpenXml.Wordprocessing; using NUnit.Framework; namespace HtmlToOpenXml.Tests @@ -19,16 +18,10 @@ public abstract class HtmlConverterTestBase public void Init () { generatedDocument = new MemoryStream(); - package = WordprocessingDocument.Create(generatedDocument, WordprocessingDocumentType.Document); - + package = WordDocumentFactory.Create(generatedDocument); mainPart = package.MainDocumentPart!; - if (mainPart == null) - { - mainPart = package.AddMainDocumentPart(); - new Document(new Body()).Save(mainPart); - } - - this.converter = new HtmlConverter(mainPart); + Assume.That(mainPart, Is.Not.Null); + this.converter = new HtmlConverter(package); } [TearDown] diff --git a/test/HtmlToOpenXml.Tests/HtmlToOpenXml.Tests.csproj b/test/HtmlToOpenXml.Tests/HtmlToOpenXml.Tests.csproj index 06ac48ba..cd75158d 100755 --- a/test/HtmlToOpenXml.Tests/HtmlToOpenXml.Tests.csproj +++ b/test/HtmlToOpenXml.Tests/HtmlToOpenXml.Tests.csproj @@ -9,15 +9,15 @@ en
- + runtime; build; native; contentfiles; analyzers; buildtransitive all - - - - - + + + + + all runtime; build; native; contentfiles; analyzers @@ -26,6 +26,7 @@ + diff --git a/test/HtmlToOpenXml.Tests/ImgTests.cs b/test/HtmlToOpenXml.Tests/ImgTests.cs index dea1fb75..2e0695f0 100644 --- a/test/HtmlToOpenXml.Tests/ImgTests.cs +++ b/test/HtmlToOpenXml.Tests/ImgTests.cs @@ -40,6 +40,19 @@ await converter.ParseBody( Assert.That(imagePart.ContentType, Is.EqualTo(contentType)); } + [Test] + public async Task PercentSize_ReturnsDrawing_() + { + await converter.ParseBody( + @"", + TestContext.CurrentContext.CancellationToken); + + var paragraphs = mainPart.Document!.Body!.Elements(); + Assert.That(paragraphs.Count(), Is.EqualTo(1)); + var (_, imagePart) = AssertIsImg(mainPart, paragraphs.First()); + } + [Test] public void DataUri_ReturnsDrawing_WithDecryptedData() { @@ -239,7 +252,6 @@ public async Task ParseIntoDocumentPart_ReturnsImageParentedToPart (Type openXml } Assert.That(host, Is.Not.Null); - Assert.That(host.ChildElements, Has.Count.EqualTo(1)); var p = host.ChildElements.FirstOrDefault(c => c is Paragraph); Assert.That(p, Is.Not.Null); AssertIsImg(container, p); diff --git a/test/HtmlToOpenXml.Tests/LinkTests.cs b/test/HtmlToOpenXml.Tests/LinkTests.cs index 90f3cced..ebdfe20b 100644 --- a/test/HtmlToOpenXml.Tests/LinkTests.cs +++ b/test/HtmlToOpenXml.Tests/LinkTests.cs @@ -235,15 +235,18 @@ public async Task WithTopAnchoring_ReturnsAutoCreatedBookmark(string anchor) { await converter.ParseBody($"
Cell1
Move to top"); - Assert.That(mainPart.Document!.Body!.Elements().Count(), Is.EqualTo(3)); - Assert.That(mainPart.Document.Body!.FirstChild, Is.TypeOf()); - Assert.That(mainPart.Document.Body!.ElementAt(1), Is.TypeOf()); - Assert.That(mainPart.Document.Body!.LastChild, Is.TypeOf()); - - var p = mainPart.Document.Body!.GetFirstChild()!; + var body = mainPart.Document!.Body!; + Assert.That(body.Elements().Count(), Is.EqualTo(4)); + Assert.That(body.FirstChild, Is.TypeOf()); + Assert.That(body.ElementAt(1), Is.TypeOf
()); + Assert.That(body.ElementAt(2), Is.TypeOf()); + Assert.That(body.LastChild, Is.TypeOf(), + "SectionProperties must be pushed as last child"); + + var p = body.GetFirstChild()!; Assert.That(p.GetFirstChild()?.Name?.Value, Is.EqualTo("_top"), "Reserved keyword `_top`"); - p = mainPart.Document.Body!.GetLastChild()!; + p = body.GetLastChild()!; Assert.That(p.GetFirstChild()?.Anchor?.Value, Is.EqualTo("_top")); } @@ -258,7 +261,7 @@ await converter.ParseBody(@"

Heading 1

using (Assert.EnterMultipleScope()) { Assert.That(p.GetFirstChild()?.Name?.Value, Is.EqualTo("_top"), - "Expected `_top` bookmark in the first body paragraph"); + "Expected `_top` bookmark is merged into the first paragraph which is the heading"); Assert.That(p.GetFirstChild(), Is.Not.Null); Assert.That(p.ParagraphProperties?.ParagraphStyleId?.Val?.Value, Is.EqualTo("Heading1"), "Expected first paragraph is the heading"); @@ -281,10 +284,17 @@ await converter.ParseBody(@"Move to top Assert.That(rel.Uri.ToString(), Is.EqualTo("#_top")); } + [Test] + public void Empty_Link_ShouldBeIgnored () + { + var elements = converter.Parse(@""); + Assert.That(elements, Is.Empty); + } + private static void AssertHyperlink(OpenXmlPartContainer container, IEnumerable elements, string expectedUri) { - Assert.That(elements.Count(), Is.EqualTo(1)); + Assert.That(elements, Is.Not.Empty); using (Assert.EnterMultipleScope()) { Assert.That(elements.First(), Is.TypeOf()); diff --git a/test/HtmlToOpenXml.Tests/NumberingTests.cs b/test/HtmlToOpenXml.Tests/NumberingTests.cs index aa2d40c4..a820e357 100644 --- a/test/HtmlToOpenXml.Tests/NumberingTests.cs +++ b/test/HtmlToOpenXml.Tests/NumberingTests.cs @@ -1,6 +1,7 @@ using NUnit.Framework; using DocumentFormat.OpenXml.Wordprocessing; using DocumentFormat.OpenXml.Packaging; +using HtmlToOpenXml.Expressions; namespace HtmlToOpenXml.Tests { @@ -33,11 +34,11 @@ public void NonLiElement_ShouldBeIgnored() [Test(Description = "Two consecutive lists should restart numbering to 1")] public async Task ConsecutiveList_ReturnsList_RestartingOrder() { - await converter.ParseBody(@" + var elements = converter.Parse(@"
  1. Item 1.1

placeholder

  1. Item 2.1
"); - var elements = mainPart.Document!.Body!.ChildElements; + using (Assert.EnterMultipleScope()) { Assert.That(elements, Has.Count.EqualTo(3)); @@ -71,14 +72,14 @@ await converter.ParseBody(@" [Test] public async Task NestedNumberList_ReturnsMultilevelList() { - await converter.ParseBody( + var elements = converter.Parse( @"
  1. Item 1
    1. Item 1.1
  2. Item 2
"); - var elements = mainPart.Document!.Body!.ChildElements; + using (Assert.EnterMultipleScope()) { Assert.That(elements, Has.Count.EqualTo(3)); @@ -338,7 +339,7 @@ public async Task DisableContinueNumbering_ReturnsSecondList_RestartingOrder() [Test(Description = "Nested numbering (issue #81)")] public async Task DecimalTieredStyle_ReturnsListWithTieredNumbering() { - await converter.ParseBody( + var elements = converter.Parse( @"
  1. Item 1
    1. Item 1.1
    @@ -346,7 +347,6 @@ await converter.ParseBody(
  2. Item 2
"); - var elements = mainPart.Document!.Body!.ChildElements; var absNum = mainPart.NumberingDefinitionsPart?.Numbering? .Elements() .SingleOrDefault(); @@ -390,6 +390,29 @@ public void OverrideStartNumber_WithOl_ShouldSucceed() Is.EqualTo(startLevel)); } + [Test(Description = "Allow to specify another start value for the first item of a nested `ol` list")] + public void OverrideStartNumber_WithNestedOl_ShouldSucceed() + { + const short startLevel = 3; + var elements = converter.Parse($""" +
    +
  1. One +
    1. Three
    +
  2. +
+ """); + Assert.That(elements, Has.Count.EqualTo(2)); + Assert.That(elements, Has.All.TypeOf()); + + var instances = mainPart.NumberingDefinitionsPart?.Numbering? + .Elements(); + Assert.That(instances, Has.Exactly(2).Items); + Assert.That(instances.First().GetFirstChild()?.StartOverrideNumberingValue?.Val?.Value, + Is.EqualTo(startLevel + 1)); + Assert.That(instances.Last().GetFirstChild()?.StartOverrideNumberingValue?.Val?.Value, + Is.EqualTo(startLevel)); + } + [Test(Description = "Allow to specify another start value for the first item of a `ul` list")] public void OverrideStartNumber_WithUl_ShouldBeIgnored() { @@ -408,14 +431,13 @@ public void OverrideStartNumber_WithUl_ShouldBeIgnored() [Test] public async Task RomanList_ReturnsListWithCustomStyle() { - await converter.ParseBody(@"
    + var elements = await converter.ParseAsync(@"
    • Item 1
    "); - var elements = mainPart.Document!.Body!.ChildElements; Assert.That(elements, Is.Not.Empty); Assert.That(elements, Is.All.TypeOf()); - var numId = ((Paragraph) elements[0]).ParagraphProperties?.NumberingProperties?.NumberingId?.Val?.Value; + var numId = ((Paragraph) elements.First()).ParagraphProperties?.NumberingProperties?.NumberingId?.Val?.Value; Assert.That(numId, Is.Not.Null); var numInst = mainPart.NumberingDefinitionsPart!.Numbering! @@ -516,6 +538,35 @@ public void WithRtl_ReturnsBidi(string dir, bool? expectedValue) return bidi?.Val?.Value; } + [Test] + public async Task WithBorder_ReturnedFramedList() + { + var elements = converter.Parse(@" +
      +
    1. One

      Two

    2. +
    "); + + Assert.That(elements[0], Is.TypeOf
()); + + var framedTable = (Table) elements[0]; + var borders = framedTable.GetFirstChild()?.TableBorders; + Assert.That(borders, Is.Not.Null, "Assert that border is applied on table scope"); + Assert.That(borders.Elements()! + .Select(b => b.Val?.Value), + Has.All.EqualTo(BorderValues.Single)); + + var cell = framedTable.GetFirstChild()?.GetFirstChild(); + Assert.That(cell, Is.Not.Null); + var paragraphs = cell.Elements(); + Assert.That(paragraphs.Count(), Is.EqualTo(2)); + + using (Assert.EnterMultipleScope()) + { + Assert.That(paragraphs.First().ParagraphProperties?.NumberingProperties, Is.Not.Null); + Assert.That(paragraphs.ElementAt(1).ParagraphProperties?.NumberingProperties, Is.Null); + } + } + [Test] public void NestedNumberList_ReturnsIncrementalIndentation() { @@ -539,8 +590,8 @@ public void NestedNumberList_ReturnsIncrementalIndentation() { var level = levels.ElementAt(i); var ident = level.PreviousParagraphProperties?.Indentation; - Assert.That(ident?.Hanging?.Value, Is.EqualTo("360")); - Assert.That(Convert.ToInt32(ident?.Left?.Value), Is.EqualTo((i + 1) * 2 * 360)); + Assert.That(ident?.Hanging?.Value, Is.EqualTo(NumberingExpressionBase.HangingStr)); + Assert.That(Convert.ToInt32(ident?.Left?.Value), Is.EqualTo((i + 1) * NumberingExpressionBase.LevelIndent)); TestContext.Out.WriteLine($"{i}. {ident?.Left?.Value}"); } } @@ -548,11 +599,11 @@ public void NestedNumberList_ReturnsIncrementalIndentation() [Test(Description = "Nested list must be a children of a `li` tag but some editor are not respecting the W3C standard (issue #173)")] public async Task NestedNumberList_NonCompliant_ReturnsIncrementalIndentation() { - await converter.ParseBody(@"
    + var elements = converter.Parse(@"
    1. Item1
    2. Item2
      1. Item 2.1
      -
    ",TestContext.CurrentContext.CancellationToken); +
"); var absNum = mainPart.NumberingDefinitionsPart?.Numbering? .Elements() @@ -564,7 +615,6 @@ await converter.ParseBody(@"
    Assert.That(inst, Is.Not.Null); Assert.That(inst.NumberID?.Value, Is.Not.Null); - var elements = mainPart.Document!.Body!.ChildElements; using (Assert.EnterMultipleScope()) { Assert.That(elements, Has.Count.EqualTo(3)); @@ -591,7 +641,7 @@ public void NestedParagraph_ReturnsIndentedItems() var elements = converter.Parse(@"
    • Paragraph text

      -

      Paragraph text

      +

      Paragraph text bis

    "); @@ -611,7 +661,7 @@ public void NestedParagraph_ReturnsIndentedItems() Has.All.EqualTo("ListParagraph"), "All paragraphs use the same paragraph style"); Assert.That(elements.Last().GetFirstChild()?.Indentation?.Left?.Value, - Is.EqualTo("720"), + Is.EqualTo(NumberingExpressionBase.LevelIndent.ToString()), "Last standalone paragraph is aligned with the level 1"); } } @@ -639,7 +689,7 @@ public void NestedTable_ReturnsAlignedTable() var tableProperties = table.GetFirstChild(); Assert.That(tableProperties, Is.Not.Null); Assert.That(tableProperties.TableIndentation, Is.Not.Null); - Assert.That(tableProperties.TableIndentation.Width?.Value, Is.EqualTo(720 * (i+1))); + Assert.That(tableProperties.TableIndentation.Width?.Value, Is.EqualTo(NumberingExpressionBase.LevelIndent * (i+1))); Assert.That(tableProperties.TableWidth, Is.Not.Null); Assert.That(tableProperties.TableWidth.Type?.Value, Is.EqualTo(TableWidthUnitValues.Pct)); Assert.That(tableProperties.TableWidth.Width?.HasValue, Is.True); @@ -647,11 +697,12 @@ public void NestedTable_ReturnsAlignedTable() } } - [Test] - public async Task LowerGreekList_ReturnsListWithGreekNumbering() + [TestCase("lower-greek", nameof(NumberFormatValues.LowerLetter))] + [TestCase("upper-greek", nameof(NumberFormatValues.UpperLetter))] + public async Task GreekList_ReturnsListWithGreekNumbering(string listStyle, string numberFormat) { - await converter.ParseBody(@" -
      + await converter.ParseBody($@" +
      1. Item 1
      2. Item 2
      " @@ -664,49 +715,24 @@ await converter.ParseBody(@" var absNum = numbering.Elements().SingleOrDefault(); Assert.That(absNum, Is.Not.Null); - Assert.That(absNum.AbstractNumDefinitionName?.Val?.Value, Is.EqualTo("lower-greek")); + Assert.That(absNum.AbstractNumDefinitionName?.Val?.Value, Is.EqualTo(listStyle)); var level = absNum.Elements().First(); using (Assert.EnterMultipleScope()) { - Assert.That(level.NumberingFormat?.Val?.Value, Is.EqualTo(NumberFormatValues.LowerLetter)); + Assert.That(((DocumentFormat.OpenXml.IEnumValue) level.NumberingFormat?.Val?.Value!).Value, Is.EqualTo(numberFormat).IgnoreCase); Assert.That(level.LevelText?.Val?.Value, Is.EqualTo("%1.")); } } - [Test] - public async Task UpperGreekList_ReturnsListWithGreekNumbering() - { - await converter.ParseBody(@" -
        -
      1. Item 1
      2. -
      " - ); - - var numbering = mainPart.NumberingDefinitionsPart!.Numbering!; - var absNum = numbering.Elements().SingleOrDefault(); - - Assert.That(absNum, Is.Not.Null); - Assert.That(absNum.AbstractNumDefinitionName?.Val?.Value, Is.EqualTo("upper-greek")); - - var level = absNum.Elements().First(); - - using (Assert.EnterMultipleScope()) - { - Assert.That(level.NumberingFormat?.Val?.Value, Is.EqualTo(NumberFormatValues.UpperLetter)); - Assert.That(level.LevelText?.Val?.Value, Is.EqualTo("%1.")); - } - } - [Test] public async Task CustomBulletList_ReturnsListWithCustomStyle() { - await converter.ParseBody(@"
        + var elements = converter.Parse(@"
        • Item 1
        "); - var elements = mainPart.Document!.Body!.ChildElements; Assert.That(elements, Is.Not.Empty); Assert.That(elements, Is.All.TypeOf()); var numId = ((Paragraph) elements[0]).ParagraphProperties?.NumberingProperties?.NumberingId?.Val?.Value; @@ -732,9 +758,6 @@ await converter.ParseBody(@"
          AssertThatOpenXmlDocumentIsValid(); } - /// Level-1 list indent plus 18pt ol margin-left. - private const string Level1ListIndent_AddedWith_18PtMargin_DXA_Value = "1080"; - [Test(Description = "List container margin-left must not create a separate abstractNum for the same list-style-type")] public void ListContainerMarginLeft_SharesAbstractNumAcrossDifferentMargins() { @@ -755,93 +778,94 @@ public void ListContainerMarginLeft_SharesAbstractNumAcrossDifferentMargins() Assert.That(instances, Has.Count.GreaterThanOrEqualTo(2)); } - [Test(Description = "Nested ol margin-left stacks with numbering level indent on each list")] - public void ListContainerMarginLeft_NestedList_AppliesLevelAndMargin() + [Test(Description = "Continuation paragraphs inside a margined list item align with the numbered line")] + public void ListContainerMarginLeft_MultiParagraphListItem_Aligned() { var elements = converter.Parse(@" -
            -
          1. Outer -
            1. Inner
            +
              +
            1. One

              +

              Two

            "); var paragraphs = elements.OfType().ToList(); Assert.That(paragraphs, Has.Count.EqualTo(2)); - - var outer = paragraphs.Single(p => - p.ParagraphProperties?.NumberingProperties?.NumberingLevelReference?.Val?.Value == 0); - var inner = paragraphs.Single(p => - p.ParagraphProperties?.NumberingProperties?.NumberingLevelReference?.Val?.Value == 1); - - var numbering = mainPart.NumberingDefinitionsPart!.Numbering!; - var outerNumId = outer.ParagraphProperties!.NumberingProperties!.NumberingId!.Val!.Value; - var innerNumId = inner.ParagraphProperties!.NumberingProperties!.NumberingId!.Val!.Value; + Assert.That(elements.Cast().Select(e => + e.ParagraphProperties?.Indentation), + Has.All.Not.Null, + "All paragraphs have an indentation marker"); using (Assert.EnterMultipleScope()) { - Assert.That(GetListInstanceLevelIndentLeft(numbering, outerNumId), Is.EqualTo(Level1ListIndent_AddedWith_18PtMargin_DXA_Value)); - Assert.That(GetListInstanceLevelIndentLeft(numbering, innerNumId, ilvl: 1), Is.EqualTo("1800")); + var indentation0 = elements[0].GetFirstChild()?.Indentation!; + var indentation1 = elements[1].GetFirstChild()?.Indentation!; + + Assert.That(paragraphs[0].ParagraphProperties?.NumberingProperties, Is.Not.Null); + Assert.That(paragraphs[1].ParagraphProperties?.NumberingProperties, Is.Null); + + Assert.That(indentation0.Hanging?.Value, Is.EqualTo(NumberingExpressionBase.HangingStr)); + Assert.That(indentation0.Left?.Value, Is.EqualTo("1120"), "720 (LevelIndent) + 400 (20pt)"); + Assert.That(indentation1.Hanging?.Value, Is.EqualTo("0")); + Assert.That(indentation1.Left?.Value, Is.EqualTo("1120"), "720 (LevelIndent) + 400 (20pt)"); } } - [Test(Description = "Continuation paragraphs inside a margined list item align with the numbered line")] - public void ListContainerMarginLeft_MultiParagraphListItem_Aligned() + [Test(Description = "Nested ol margin-left stacks with numbering level indent on each list")] + public void ListContainerMarginLeft_NestedList_AppliesLevelAndMargin() { var elements = converter.Parse(@" -
              -
            1. One

              Two

            2. +
                +
              1. Outer +
                1. Inner
                +
              "); var paragraphs = elements.OfType().ToList(); Assert.That(paragraphs, Has.Count.EqualTo(2)); + Assert.That(elements.Cast().Select(e => + e.ParagraphProperties?.Indentation), + Has.All.Not.Null, + "All paragraphs have an indentation marker"); using (Assert.EnterMultipleScope()) { - Assert.That(paragraphs[0].ParagraphProperties?.NumberingProperties, Is.Not.Null); - Assert.That(paragraphs[1].ParagraphProperties?.NumberingProperties, Is.Null); - Assert.That(paragraphs[1].ParagraphProperties?.Indentation?.Left?.Value, Is.EqualTo(Level1ListIndent_AddedWith_18PtMargin_DXA_Value)); + Assert.That(elements.Cast().Select(e => + e.ParagraphProperties?.NumberingProperties?.NumberingId?.Val?.Value), + Has.All.Not.Null, + "All paragraphs are linked to list instances"); + + var indentation0 = elements[0].GetFirstChild()?.Indentation!; + var indentation1 = elements[1].GetFirstChild()?.Indentation!; + Assert.That(indentation0.Hanging?.Value, Is.EqualTo(NumberingExpressionBase.HangingStr)); + Assert.That(indentation0.Left?.Value, Is.EqualTo("1120"), "720 (LevelIndent) + 400 (20pt)"); + Assert.That(indentation1.Hanging?.Value, Is.EqualTo(NumberingExpressionBase.HangingStr)); + Assert.That(indentation1.Left?.Value, Is.EqualTo("1440"), "2*720 (LevelIndent) + 400 (20pt)"); } } - [Test(Description = "Unordered lists apply ol margin-left the same way as ordered lists")] - public void ListContainerMarginLeft_AppliesToUnorderedList() + [Test] + public async Task ListContainer_Styling_CascadeToListItems() { - var elements = converter.Parse(@"
              • Bullet
              "); - var p = (Paragraph)elements.Single(); - var numId = p.ParagraphProperties!.NumberingProperties!.NumberingId!.Val!.Value; - var numbering = mainPart.NumberingDefinitionsPart!.Numbering!; - Assert.That(p.ParagraphProperties?.NumberingProperties, Is.Not.Null); - Assert.That(GetListInstanceLevelIndentLeft(numbering, numId), Is.EqualTo(Level1ListIndent_AddedWith_18PtMargin_DXA_Value)); - var overrideLevel = GetListInstanceLevelOverride(numbering, numId); - Assert.That(overrideLevel?.NumberingFormat?.Val?.Value, Is.EqualTo(NumberFormatValues.Bullet), - "Level override must clone the template level so bullet markers still render"); - } + var elements = converter.Parse(@" +
                +
              1. One

                Two

              2. +
              "); - private static string? GetListInstanceLevelIndentLeft(Numbering numbering, int numId, int ilvl = 0) - { - return GetListInstanceLevelOverride(numbering, numId, ilvl)?.PreviousParagraphProperties?.Indentation?.Left?.Value; - } + var paragraphs = elements.OfType().ToList(); + Assert.That(paragraphs, Has.Count.EqualTo(2)); - private static Level? GetListInstanceLevelOverride(Numbering numbering, int numId, int ilvl = 0) - { - var instance = numbering.Elements().Single(i => i.NumberID!.Value == numId); - foreach (var levelOverride in instance.Elements()) + using (Assert.EnterMultipleScope()) { - foreach (var level in levelOverride.Elements()) - { - if (level.LevelIndex?.Value == ilvl) - return level; - } + Assert.That(paragraphs[0].ParagraphProperties?.NumberingProperties, Is.Not.Null); + Assert.That(paragraphs[1].ParagraphProperties?.NumberingProperties, Is.Null); + Assert.That(paragraphs[0].GetFirstChild()?.RunProperties?.Color?.Val?.Value, Is.EqualTo("FF0000")); + Assert.That(paragraphs[1].GetFirstChild()?.RunProperties?.Color?.Val?.Value, Is.EqualTo("0000FF")); } - return null; } /// /// A nested ul type attribute must use its own bullet, not the parent marker /// - /// - /// - /// [TestCase("disc", "square", ExpectedResult = "•,▪")] [TestCase("disc", "circle", ExpectedResult = "•,\u25CB")] public async Task NestedUnorderedList_TypeAttribute_UsesOwnBullet(string listType, string nestedListType) @@ -859,7 +883,10 @@ await converter.ParseBody($@" Assert.That(paragraphs, Has.Count.EqualTo(2)); AssertThatOpenXmlDocumentIsValid(); - return string.Join(",", paragraphs.Select(GetBulletText).Select(BulletTextUnicode)); + return string.Join(",", paragraphs.Select(GetBulletText).Select(bulletText => bulletText switch { + "o" => "\u25CB", // ○ circle + _ => bulletText + })); } [Test(Description = "CSS list-style-type takes precedence over the ul type attribute")] @@ -872,6 +899,37 @@ public async Task UnorderedList_CssListStyleType_OverridesTypeAttribute() AssertThatOpenXmlDocumentIsValid(); } + [Test(Description = "Paragraph margin-left inside a list item must be applied independently of the list item indentation")] + public async Task ListContainerAndParagraphs_AppliesExtraMargin() + { + var elements = converter.Parse(""" +
                +
              1. +

                First

                +

                Last

                +
              2. +
              + """); + + var paragraphs = elements.OfType().ToList(); + Assert.That(paragraphs, Has.Count.EqualTo(2)); + Assert.That(elements.Cast().Select(e => + e.ParagraphProperties?.Indentation), + Has.All.Not.Null, + "All paragraphs have an indentation marker"); + + using (Assert.EnterMultipleScope()) + { + var indentation0 = elements[0].GetFirstChild()?.Indentation!; + var indentation1 = elements[1].GetFirstChild()?.Indentation!; + + Assert.That(indentation0.Hanging?.Value, Is.EqualTo(NumberingExpressionBase.HangingStr)); + Assert.That(indentation0.Left?.Value, Is.EqualTo("1120"), "720 (LevelIndent) + 400 (20pt)"); + Assert.That(indentation1.Hanging?.Value, Is.EqualTo("0")); + Assert.That(indentation1.Left?.Value, Is.EqualTo("1520"), "720 (LevelIndent) + 400 (20pt) + 400 (20pt)"); + } + } + private string? GetBulletText(Paragraph paragraph) { var numberingProperties = paragraph.ParagraphProperties?.NumberingProperties; @@ -882,14 +940,5 @@ public async Task UnorderedList_CssListStyleType_OverridesTypeAttribute() var abstractNum = numbering.Elements().Single(a => a.AbstractNumberId?.Value == instance.AbstractNumId!.Val!.Value); return abstractNum.Elements().First(l => l.LevelIndex?.Value == level).LevelText?.Val?.Value; } - - private string? BulletTextUnicode(string? bulletText) - { - return bulletText switch - { - "o" => "\u25CB", // ○ circle - _ => bulletText - }; - } } } diff --git a/test/HtmlToOpenXml.Tests/ParserTests.cs b/test/HtmlToOpenXml.Tests/ParserTests.cs index 745335c7..c8379de1 100644 --- a/test/HtmlToOpenXml.Tests/ParserTests.cs +++ b/test/HtmlToOpenXml.Tests/ParserTests.cs @@ -13,7 +13,7 @@ public class ParserTests : HtmlConverterTestBase { [TestCase("")] [TestCase("")] - [TestCase("")] [TestCase("")] [TestCase("")] [TestCase("")] @@ -130,7 +130,7 @@ public void EmptyText_ShouldBeIgnored() [Test(Description = "Provided mainPart is null")] public void ProvidedMainPart_WithNull_ShouldFail() { - Assert.Throws(() => new HtmlConverter(null!)); + Assert.Throws(() => new HtmlConverter((MainDocumentPart) null!)); } [Test(Description = "Provided mainPart.Document is empty")] diff --git a/test/HtmlToOpenXml.Tests/TableTests.cs b/test/HtmlToOpenXml.Tests/TableTests.cs index 92366e63..a265bfef 100644 --- a/test/HtmlToOpenXml.Tests/TableTests.cs +++ b/test/HtmlToOpenXml.Tests/TableTests.cs @@ -53,7 +53,7 @@ public void EmptyTablePart_ShouldBeIgnored() public void RowWithNoCell_ReturnsCompletelyFilledRow() { var elements = converter.Parse(@"
- +
Cell 1.1Cell 1.2
Cell 1.1Cell 1.2Cell 1.3
Cell 2.1
"); @@ -61,8 +61,8 @@ public void RowWithNoCell_ReturnsCompletelyFilledRow() Assert.That(elements, Has.All.TypeOf()); var rows = elements[0].Elements(); Assert.That(rows.Count(), Is.EqualTo(2), "Row with no cells should be skipped"); - Assert.That(rows.Select(r => r.Elements().Count()), - Has.All.EqualTo(2), + Assert.That(rows.Select(r => r.Elements().Count()), + Has.All.EqualTo(3), "All rows should have the same number of cells"); } @@ -96,7 +96,7 @@ public void ColSpan_ReturnsGridSpan(uint colSpan, int? expectedColSpan) { var elements = converter.Parse(@$"
- {("").Repeat(Math.Max(1, colSpan))} + {"".Repeat(Math.Max(1, colSpan))}
Cell 1.1
Cell
Cell
"); Assert.That(elements, Has.Count.EqualTo(1)); Assert.That(elements, Has.All.TypeOf()); @@ -713,10 +713,10 @@ public void CellBorders_ShouldNotPropagate_OnRuns() Assert.That(runs.First().RunProperties?.Border, Is.Null); } - [TestCase("100%", "pct", "5000")] + [TestCase("100%", "pct", Expressions.BlockElementExpression.FullPageWidthPct)] [TestCase("auto", "auto", "0")] [TestCase("120px", "dxa", "1800")] - [TestCase("", "pct", "5000", Description = "Defaults to 100%")] + [TestCase("", "pct", Expressions.BlockElementExpression.FullPageWidthPct, Description = "Defaults to 100%")] public void Width_ReturnsRefineTableWidth(string width, string expectedUnit, string expectedValue) { var elements = converter.Parse(@$"
@@ -776,7 +776,7 @@ public void ColWithPercentWidth_ReturnsRefineTableWidth() Assert.That(cells.Last().TableCellProperties?.TableCellWidth?.Width?.Value, Is.EqualTo("4346")); } } - + [Test] public void CellPadding_ReturnsTableCellMargin() {