From 2e6b89c9592403388a5b69898005b574836b9325 Mon Sep 17 00:00:00 2001 From: Olivier Nizet Date: Sat, 31 Oct 2026 23:50:50 +0100 Subject: [PATCH 01/18] Provide some high-level entrypoints --- README.md | 13 +- docs/guide/quickstart.md | 46 +++++-- examples/Demo/Program.cs | 11 +- src/Html2OpenXml/Configuration enum.cs | 27 ++++ .../Expressions/BodyExpression.cs | 56 ++------ src/Html2OpenXml/HtmlConverter.cs | 27 +++- src/Html2OpenXml/WordDocumentFactory.cs | 126 ++++++++++++++++++ test/HtmlToOpenXml.Tests/ParserTests.cs | 2 +- 8 files changed, 232 insertions(+), 76 deletions(-) create mode 100644 src/Html2OpenXml/WordDocumentFactory.cs 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/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/examples/Demo/Program.cs b/examples/Demo/Program.cs index fccd4693..8d174b77 100644 --- a/examples/Demo/Program.cs +++ b/examples/Demo/Program.cs @@ -26,16 +26,9 @@ static async Task Main(string[] args) generatedDocument.Position = 0L; //using (WordprocessingDocument package = WordprocessingDocument.Open(generatedDocument, true)) - using (WordprocessingDocument package = WordprocessingDocument.Create(generatedDocument, WordprocessingDocumentType.Document)) + using (WordprocessingDocument package = WordDocumentFactory.Create(generatedDocument, PageOrientation.Landscape)) //WordprocessingDocument.Create(generatedDocument, WordprocessingDocumentType.Document)) { - MainDocumentPart? mainPart = package.MainDocumentPart; - if (mainPart == null) - { - mainPart = package.AddMainDocumentPart(); - new Document(new Body()).Save(mainPart); - } - - HtmlConverter converter = new(mainPart, new HtmlToOpenXml.IO.DefaultWebRequest(){ + HtmlConverter converter = new(package, new HtmlToOpenXml.IO.DefaultWebRequest(){ BaseImageUrl = new Uri(Path.Combine(Environment.CurrentDirectory, "images")) }); converter.RenderPreAsTable = true; diff --git a/src/Html2OpenXml/Configuration enum.cs b/src/Html2OpenXml/Configuration enum.cs index e39a3ba6..27d17afa 100755 --- a/src/Html2OpenXml/Configuration enum.cs +++ b/src/Html2OpenXml/Configuration enum.cs @@ -74,3 +74,30 @@ public enum ImageProcessingMode /// EmbedDataUriOnly = 2, } + +/// +/// Specifies the page orientation used when creating a new Word document. +/// The orientation determines whether pages are laid out vertically (portrait) +/// or horizontally (landscape). +/// +public enum PageOrientation +{ + /// + /// Pages are taller than they are wide. + /// + /// + /// This is the default orientation for most documents such as letters, reports, + /// contracts, and articles. + /// + /// + Portrait, + /// + /// Pages are wider than they are tall. + /// + /// + /// This orientation is commonly used for wide tables, spreadsheets, diagrams, + /// and content requiring additional horizontal space. + /// + /// + Landscape +} \ No newline at end of file diff --git a/src/Html2OpenXml/Expressions/BodyExpression.cs b/src/Html2OpenXml/Expressions/BodyExpression.cs index b372628b..9e546968 100644 --- a/src/Html2OpenXml/Expressions/BodyExpression.cs +++ b/src/Html2OpenXml/Expressions/BodyExpression.cs @@ -24,8 +24,6 @@ namespace HtmlToOpenXml.Expressions; sealed class BodyExpression(IHtmlElement node, ParagraphStyleId? defaultStyle) : BlockElementExpression(node, defaultStyle) { - private const uint PortraitPageWidth = 11906U; - private const uint PortraitPageHeight = 16838U; private bool shouldRegisterTopBookmark; @@ -37,7 +35,7 @@ public override IEnumerable Interpret(ParsingContext context) var sectionProperties = body.Descendants().LastOrDefault(); if (sectionProperties != null) { - context.IsLandscape = sectionProperties.GetFirstChild()?.Width?.Value >= PortraitPageHeight; + context.IsLandscape = WordDocumentFactory.IsLandscape(sectionProperties.GetFirstChild()); } var elements = base.Interpret(context); @@ -71,25 +69,23 @@ protected override void ComposeStyles(ParsingContext context) // orientation is applied on the whole document if (styleAttributes.TryGetValue("page-orientation", out var attrValue)) { - PageOrientationValues orientation = PageOrientationValues.Portrait; - if ("landscape".Equals(attrValue, StringComparison.InvariantCultureIgnoreCase)) - orientation = PageOrientationValues.Landscape; + PageOrientation orientation = attrValue.Is("landscape")? + PageOrientation.Landscape : PageOrientation.Portrait; var sectionProperties = mainPart.Document!.Body!.GetFirstChild(); - if (sectionProperties == null || sectionProperties.GetFirstChild() == null) + var pageSize = sectionProperties?.GetFirstChild(); + if (pageSize == null) { - context.IsLandscape = orientation == PageOrientationValues.Landscape; - mainPart.Document.Body.Append(ChangePageOrientation(orientation)); + context.IsLandscape = orientation == PageOrientation.Landscape; + mainPart.Document.Body.Append(WordDocumentFactory.CreateSectionProperties(orientation)); } - else + else if (WordDocumentFactory.IsLandscape(pageSize) != (orientation == PageOrientation.Landscape)) { - var pageSize = sectionProperties.GetFirstChild(); - if (pageSize == null || !pageSize.Compare(orientation)) - { - SectionProperties validSectionProp = ChangePageOrientation(orientation); - pageSize?.Remove(); - sectionProperties.PrependChild(validSectionProp.GetFirstChild()!.CloneNode(true)); - } + PageSize newPageSize = WordDocumentFactory.CreateSectionProperties(orientation) + .GetFirstChild()!; + + pageSize.Width = newPageSize.Width; + pageSize.Height = newPageSize.Height; } } @@ -105,32 +101,6 @@ protected override void ComposeStyles(ParsingContext context) } } - /// - /// Generate the required OpenXml element for handling page orientation. - /// - private static SectionProperties ChangePageOrientation(PageOrientationValues orientation) - { - PageSize pageSize = new() { Width = PortraitPageWidth, Height = PortraitPageHeight }; - if (orientation == PageOrientationValues.Portrait) - { - pageSize.Orient = orientation; - } - else - { - (pageSize.Height, pageSize.Width) = (pageSize.Width, pageSize.Height); - } - - return new SectionProperties ( - pageSize, - new PageMargin() { - Top = 1417, Right = (UInt32Value) 1417U, Bottom = 1417, Left = (UInt32Value) 1417U, - Header = (UInt32Value) 708U, Footer = (UInt32Value) 708U, Gutter = (UInt32Value) 0U - }, - new Columns() { Space = "708" }, - new DocGrid() { LinePitch = 360 } - ); - } - /// /// Detect all bookmarks (in-document) and mark the nodes for future processing. /// diff --git a/src/Html2OpenXml/HtmlConverter.cs b/src/Html2OpenXml/HtmlConverter.cs index c62bc5b3..8a041b17 100755 --- a/src/Html2OpenXml/HtmlConverter.cs +++ b/src/Html2OpenXml/HtmlConverter.cs @@ -91,6 +91,27 @@ public HtmlConverter(MainDocumentPart mainPart, IWebRequest? webRequester = null this.webRequester = webRequester ?? new DefaultWebRequest(); } + /// + /// 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. + /// + /// The top-level class of a Word document where converted content will be inserted. + /// Control retrieval of external resources such as images. + public HtmlConverter(WordprocessingDocument package, IWebRequest? webRequester = null) + { + if (package is null) + throw new ArgumentNullException(nameof(package)); + + this.mainPart = WordDocumentFactory.GetOrCreateMainDocumentPart(package, PageOrientation.Portrait); + this.htmlStyles = new WordDocumentStyle(this.mainPart); + this.webRequester = webRequester ?? new DefaultWebRequest(); + } + /// /// Convert HTML into OpenXml elements and return them to the caller. /// @@ -244,7 +265,9 @@ public async Task ParseBody(string html, CancellationToken cancellationToken = d return; Body body = mainPart.Document!.Body!; - SectionProperties? sectionProperties = body.GetLastChild(); + SectionProperties? sectionProperties = body.GetLastChild() + ?? WordDocumentFactory.CreateSectionProperties(PageOrientation.Portrait); + foreach (var para in paragraphs) body.Append(para); @@ -262,7 +285,7 @@ public async Task ParseBody(string html, CancellationToken cancellationToken = d // Push the sectionProperties as the last element of the Body // (required by OpenXml schema to avoid the bad formatting of the document) - if (sectionProperties != null) + if (sectionProperties != null && sectionProperties.Parent != null) { sectionProperties.Remove(); body.AddChild(sectionProperties); diff --git a/src/Html2OpenXml/WordDocumentFactory.cs b/src/Html2OpenXml/WordDocumentFactory.cs new file mode 100644 index 00000000..5e0c7545 --- /dev/null +++ b/src/Html2OpenXml/WordDocumentFactory.cs @@ -0,0 +1,126 @@ +/* Copyright (C) Olivier Nizet https://github.com/onizet/html2openxml - All Rights Reserved + * + * This source is subject to the Microsoft Permissive License. + * Please see the License.txt file for more information. + * All other rights reserved. + * + * THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY + * KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A + * PARTICULAR PURPOSE. + */ +using DocumentFormat.OpenXml; +using DocumentFormat.OpenXml.Packaging; +using DocumentFormat.OpenXml.Wordprocessing; + +namespace HtmlToOpenXml; + +/// +/// Provides helper methods for creating Word documents configured for use with . +/// +/// +/// 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 to convert HTML content into WordProcessingML. +/// +/// +/// +/// +/// Basic quick start: +/// +/// +/// await using var generatedDocument = new MemoryStream(); +/// using var package = WordDocumentFactory.Create(generatedDocument, PageOrientation.Portrait); +/// HtmlConverter converter = new(package); +/// await converter.ParseBody(html); +/// +/// +public static class WordDocumentFactory +{ + private const uint A4PortraitWidth = 11906U; + private const uint A4PortraitHeight = 16838U; + + /// + /// 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 or + /// further customised using the Open XML SDK. + /// + /// + /// The destination stream that will receive the generated DOCX package + /// The stream must be writable. + /// The page orientation to apply to the document. + /// Thrown when "stream" is null reference. + /// Thrown when "stream" is not opened with Write access. + public static WordprocessingDocument Create(Stream stream, + PageOrientation orientation = PageOrientation.Portrait) + { + var package = WordprocessingDocument.Create(stream, WordprocessingDocumentType.Document); + + GetOrCreateMainDocumentPart(package, orientation); + return package; + } + + /// + /// Gets the main document part associated with the document, creating it when it does not already exist. + /// + internal static MainDocumentPart GetOrCreateMainDocumentPart(WordprocessingDocument package, + PageOrientation orientation) + { + var mainPart = package.MainDocumentPart; + if (mainPart is null) + { + mainPart = package.AddMainDocumentPart(); + new Document(new Body()).Save(mainPart); + } + + var sectionProperties = CreateSectionProperties(orientation); + mainPart.Document!.Body!.AddChild(sectionProperties); + return mainPart; + } + + /// + /// Generate the required OpenXml element for handling page orientation. + /// + internal static SectionProperties CreateSectionProperties(PageOrientation orientation) + { + PageSize pageSize; + if (orientation == PageOrientation.Portrait) + { + pageSize = new() { + Width = A4PortraitWidth, Height = A4PortraitHeight, + Orient = PageOrientationValues.Portrait + }; + } + else + { + pageSize = new() { + Width = A4PortraitHeight, Height = A4PortraitWidth, + Orient = PageOrientationValues.Landscape + }; + } + + return new SectionProperties ( + pageSize, + new PageMargin() { + Top = 1440, Right = (UInt32Value) 1440U, Bottom = 1440, Left = (UInt32Value) 1440U, + Header = (UInt32Value) 720U, Footer = (UInt32Value) 720U, Gutter = (UInt32Value) 0U + }, + new Columns() { Space = "720" }, + new DocGrid() { LinePitch = 360 } + ); + } + + /// + /// Determines whether the specified page size represents a landscape orientation. + /// + internal static bool IsLandscape(PageSize? pageSize) + { + if (pageSize is null) + return false; + + return pageSize.Width?.Value >= A4PortraitHeight; + } +} diff --git a/test/HtmlToOpenXml.Tests/ParserTests.cs b/test/HtmlToOpenXml.Tests/ParserTests.cs index 745335c7..db547621 100644 --- a/test/HtmlToOpenXml.Tests/ParserTests.cs +++ b/test/HtmlToOpenXml.Tests/ParserTests.cs @@ -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")] From d9c921f25f513a5d18c00215da7050f56100f81d Mon Sep 17 00:00:00 2001 From: Olivier Nizet Date: Sun, 1 Nov 2026 00:17:37 +0100 Subject: [PATCH 02/18] Fix a bug on landscape being reset, and document the new feature --- CHANGELOG.md | 9 +++++++++ Directory.Build.props | 2 +- docs/.vuepress/public/nuspec-ai.txt | 17 +++++++---------- examples/Demo/Program.cs | 3 +-- src/Html2OpenXml/HtmlConverter.cs | 2 +- src/Html2OpenXml/WordDocumentFactory.cs | 9 ++++----- 6 files changed, 23 insertions(+), 19 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 45e2e04d..e405bc95 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,14 @@ # 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. + ## 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..a5e00870 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -4,7 +4,7 @@ enable latest enable - 4.1.0 + 4.2.0 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/examples/Demo/Program.cs b/examples/Demo/Program.cs index 8d174b77..20eff855 100644 --- a/examples/Demo/Program.cs +++ b/examples/Demo/Program.cs @@ -2,7 +2,6 @@ using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Validation; -using DocumentFormat.OpenXml.Wordprocessing; using HtmlToOpenXml; namespace Demo @@ -26,7 +25,7 @@ static async Task Main(string[] args) generatedDocument.Position = 0L; //using (WordprocessingDocument package = WordprocessingDocument.Open(generatedDocument, true)) - using (WordprocessingDocument package = WordDocumentFactory.Create(generatedDocument, PageOrientation.Landscape)) //WordprocessingDocument.Create(generatedDocument, WordprocessingDocumentType.Document)) + using (WordprocessingDocument package = WordDocumentFactory.Create(generatedDocument)) { HtmlConverter converter = new(package, new HtmlToOpenXml.IO.DefaultWebRequest(){ BaseImageUrl = new Uri(Path.Combine(Environment.CurrentDirectory, "images")) diff --git a/src/Html2OpenXml/HtmlConverter.cs b/src/Html2OpenXml/HtmlConverter.cs index 8a041b17..4c626f76 100755 --- a/src/Html2OpenXml/HtmlConverter.cs +++ b/src/Html2OpenXml/HtmlConverter.cs @@ -107,7 +107,7 @@ public HtmlConverter(WordprocessingDocument package, IWebRequest? webRequester = if (package is null) throw new ArgumentNullException(nameof(package)); - this.mainPart = WordDocumentFactory.GetOrCreateMainDocumentPart(package, PageOrientation.Portrait); + this.mainPart = WordDocumentFactory.GetOrCreateMainDocumentPart(package); this.htmlStyles = new WordDocumentStyle(this.mainPart); this.webRequester = webRequester ?? new DefaultWebRequest(); } diff --git a/src/Html2OpenXml/WordDocumentFactory.cs b/src/Html2OpenXml/WordDocumentFactory.cs index 5e0c7545..2785ccd0 100644 --- a/src/Html2OpenXml/WordDocumentFactory.cs +++ b/src/Html2OpenXml/WordDocumentFactory.cs @@ -59,15 +59,16 @@ public static WordprocessingDocument Create(Stream stream, { var package = WordprocessingDocument.Create(stream, WordprocessingDocumentType.Document); - GetOrCreateMainDocumentPart(package, orientation); + var mainPart = GetOrCreateMainDocumentPart(package); + var sectionProperties = CreateSectionProperties(orientation); + mainPart.Document!.Body!.AddChild(sectionProperties); return package; } /// /// Gets the main document part associated with the document, creating it when it does not already exist. /// - internal static MainDocumentPart GetOrCreateMainDocumentPart(WordprocessingDocument package, - PageOrientation orientation) + internal static MainDocumentPart GetOrCreateMainDocumentPart(WordprocessingDocument package) { var mainPart = package.MainDocumentPart; if (mainPart is null) @@ -76,8 +77,6 @@ internal static MainDocumentPart GetOrCreateMainDocumentPart(WordprocessingDocum new Document(new Body()).Save(mainPart); } - var sectionProperties = CreateSectionProperties(orientation); - mainPart.Document!.Body!.AddChild(sectionProperties); return mainPart; } From ff826ae7af1810a74f9edc382d70e5ac6aff7ab3 Mon Sep 17 00:00:00 2001 From: Olivier Nizet Date: Sun, 1 Nov 2026 22:05:57 +0100 Subject: [PATCH 03/18] More exclusion of html tags --- src/Html2OpenXml/Expressions/HtmlDomExpression.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/Html2OpenXml/Expressions/HtmlDomExpression.cs b/src/Html2OpenXml/Expressions/HtmlDomExpression.cs index d74ec2c1..1bd42748 100644 --- a/src/Html2OpenXml/Expressions/HtmlDomExpression.cs +++ b/src/Html2OpenXml/Expressions/HtmlDomExpression.cs @@ -24,7 +24,9 @@ abstract class HtmlDomExpression static readonly Dictionary> knownTags = InitKnownTags(); static readonly HashSet ignoreTags = new(StringComparer.OrdinalIgnoreCase) { TagNames.Xml, TagNames.AnnotationXml, TagNames.Button, TagNames.Progress, - TagNames.Select, TagNames.Input, TagNames.Textarea, TagNames.Meter }; + TagNames.Select, TagNames.Input, TagNames.Textarea, TagNames.Meter, TagNames.Applet, + TagNames.Style, TagNames.NoFrames, TagNames.NoEmbed, TagNames.NoScript, + TagNames.Script, TagNames.Bgsound, TagNames.Menu, TagNames.MenuItem, }; private static Dictionary> InitKnownTags() { From bf14190ebd16ad1b00065dd7532513184954f261 Mon Sep 17 00:00:00 2001 From: Olivier Nizet Date: Sun, 1 Nov 2026 23:24:43 +0100 Subject: [PATCH 04/18] Fix full namespace in the sample for converting webP --- docs/guide/images.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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); From 22c64740f33fd7186c558196c2a94254e19e5182 Mon Sep 17 00:00:00 2001 From: Olivier Nizet Date: Mon, 2 Nov 2026 18:12:46 +0100 Subject: [PATCH 05/18] Align the comment with the real code location --- src/Html2OpenXml/Expressions/Image/ImageExpression.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Html2OpenXml/Expressions/Image/ImageExpression.cs b/src/Html2OpenXml/Expressions/Image/ImageExpression.cs index ca12e9eb..66378057 100644 --- a/src/Html2OpenXml/Expressions/Image/ImageExpression.cs +++ b/src/Html2OpenXml/Expressions/Image/ImageExpression.cs @@ -35,11 +35,11 @@ class ImageExpression(IHtmlImageElement node) : ImageExpressionBase(node) { string? src = imgNode.GetAttribute("src"); - // Bug reported by Erik2014. Inline 64 bit images can be too big and Uri.TryCreate will fail silently with a SizeLimit error. - // To circumvent this buffer size, we will work either on the Uri, either on the original src. if (src == null) return null; + // Bug reported by Erik2014. Inline 64 bit images can be too big and Uri.TryCreate will fail silently with a SizeLimit error. + // To circumvent this buffer size, we will work either on the Uri, either on the original src. var isDataUri = DataUri.IsDataUri(src); if (!isDataUri && !AngleSharpExtensions.TryParseUrl(src, UriKind.RelativeOrAbsolute, out var _)) From 67412c0dae1e04495bfc105b814ebde9cd51145e Mon Sep 17 00:00:00 2001 From: Olivier Nizet Date: Mon, 2 Nov 2026 21:07:11 +0100 Subject: [PATCH 06/18] Fix list items which do not inherit styling from the parent list #252 --- .../Expressions/Numbering/ListExpression.cs | 3 +- test/HtmlToOpenXml.Tests/NumberingTests.cs | 37 ++++++++++++------- 2 files changed, 26 insertions(+), 14 deletions(-) diff --git a/src/Html2OpenXml/Expressions/Numbering/ListExpression.cs b/src/Html2OpenXml/Expressions/Numbering/ListExpression.cs index 7efe5d79..85576c7e 100644 --- a/src/Html2OpenXml/Expressions/Numbering/ListExpression.cs +++ b/src/Html2OpenXml/Expressions/Numbering/ListExpression.cs @@ -75,13 +75,14 @@ public override IEnumerable Interpret(ParsingContext context) } context.Properties("listContext", listContext); + var numberingContext = context.CreateChild(this, isStyleScoped: true); // +1 because index starts on 1 and not 0 var level = Math.Min(listContext.Level, MaxLevel+1); foreach (IHtmlElement liNode in liNodes.Cast()) { var expression = new BlockElementExpression(liNode); - var childElements = expression.Interpret(context); + var childElements = expression.Interpret(numberingContext); if (!childElements.Any()) continue; // table must be aligned to the list item diff --git a/test/HtmlToOpenXml.Tests/NumberingTests.cs b/test/HtmlToOpenXml.Tests/NumberingTests.cs index aa2d40c4..a1af0cb0 100644 --- a/test/HtmlToOpenXml.Tests/NumberingTests.cs +++ b/test/HtmlToOpenXml.Tests/NumberingTests.cs @@ -817,6 +817,26 @@ public void ListContainerMarginLeft_AppliesToUnorderedList() "Level override must clone the template level so bullet markers still render"); } + [Test] + public async Task ListContainer_Styling_CascadeToListItems() + { + var elements = converter.Parse(@" +
    +
  1. One

    Two

  2. +
"); + + var paragraphs = elements.OfType().ToList(); + Assert.That(paragraphs, Has.Count.EqualTo(2)); + + using (Assert.EnterMultipleScope()) + { + 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")); + } + } + private static string? GetListInstanceLevelIndentLeft(Numbering numbering, int numId, int ilvl = 0) { return GetListInstanceLevelOverride(numbering, numId, ilvl)?.PreviousParagraphProperties?.Indentation?.Left?.Value; @@ -839,9 +859,6 @@ public void ListContainerMarginLeft_AppliesToUnorderedList() /// /// 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 +876,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")] @@ -882,14 +902,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 - }; - } } } From 60a5531ab31671ba0f633e5d7ca402ff13984059 Mon Sep 17 00:00:00 2001 From: Olivier Nizet Date: Mon, 2 Nov 2026 21:17:47 +0100 Subject: [PATCH 07/18] Numbering list with borders returned a framed table containing the list items --- .../Expressions/BlockElementExpression.cs | 2 +- .../Expressions/Numbering/ListExpression.cs | 12 +++++++- .../Numbering/NumberingExpressionBase.cs | 2 +- test/HtmlToOpenXml.Tests/NumberingTests.cs | 29 +++++++++++++++++++ 4 files changed, 42 insertions(+), 3 deletions(-) diff --git a/src/Html2OpenXml/Expressions/BlockElementExpression.cs b/src/Html2OpenXml/Expressions/BlockElementExpression.cs index 05ce820e..a46a4d64 100644 --- a/src/Html2OpenXml/Expressions/BlockElementExpression.cs +++ b/src/Html2OpenXml/Expressions/BlockElementExpression.cs @@ -383,7 +383,7 @@ private static Paragraph CreateParagraph(ParsingContext context, IList /// Group all the paragraph inside a framed table. ///
- private Table CreateFrame(IEnumerable childElements) + protected Table CreateFrame(IEnumerable childElements) { List childrens = childElements.ToList(); if (childrens.LastOrDefault() is not Paragraph) diff --git a/src/Html2OpenXml/Expressions/Numbering/ListExpression.cs b/src/Html2OpenXml/Expressions/Numbering/ListExpression.cs index 85576c7e..62a87a27 100644 --- a/src/Html2OpenXml/Expressions/Numbering/ListExpression.cs +++ b/src/Html2OpenXml/Expressions/Numbering/ListExpression.cs @@ -42,8 +42,18 @@ public override IEnumerable Interpret(ParsingContext context) { ComposeStyles(context); var liNodes = node.Children.Where(n => n.LocalName.Equals("li", StringComparison.OrdinalIgnoreCase)); - if (!liNodes.Any()) yield break; + if (!liNodes.Any()) return []; + if (renderAsFramed) + { + return [CreateFrame(InterpretListItems(context, liNodes))]; + } + + return InterpretListItems(context, liNodes); + } + + private IEnumerable InterpretListItems(ParsingContext context, IEnumerable liNodes) + { // W3C requires that nested list stands below a `li` element but some editors // don't care to respect the standard. Let's reparent those lists var nestedList = node.Children.Where(n => diff --git a/src/Html2OpenXml/Expressions/Numbering/NumberingExpressionBase.cs b/src/Html2OpenXml/Expressions/Numbering/NumberingExpressionBase.cs index 98375379..74944b28 100644 --- a/src/Html2OpenXml/Expressions/Numbering/NumberingExpressionBase.cs +++ b/src/Html2OpenXml/Expressions/Numbering/NumberingExpressionBase.cs @@ -222,7 +222,7 @@ private void InitNumberingIds(ParsingContext context) /// /// The custom character or string to be used as the list bullet. /// An instance configured with the custom bullet symbol across all levels. - private AbstractNum CreateCustomBulletAbstractNum(string customSymbol) + private static AbstractNum CreateCustomBulletAbstractNum(string customSymbol) { var abstractNum = new AbstractNum { AbstractNumDefinitionName = new() { Val = customSymbol }, diff --git a/test/HtmlToOpenXml.Tests/NumberingTests.cs b/test/HtmlToOpenXml.Tests/NumberingTests.cs index a1af0cb0..48687006 100644 --- a/test/HtmlToOpenXml.Tests/NumberingTests.cs +++ b/test/HtmlToOpenXml.Tests/NumberingTests.cs @@ -516,6 +516,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() { From 9070019e41df84389b44342fae9c8c1ad24e87ba Mon Sep 17 00:00:00 2001 From: Olivier Nizet Date: Mon, 2 Nov 2026 21:18:46 +0100 Subject: [PATCH 08/18] Optimised way to copy the stream to a filestream --- examples/Demo/Program.cs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/examples/Demo/Program.cs b/examples/Demo/Program.cs index 20eff855..55d605d9 100644 --- a/examples/Demo/Program.cs +++ b/examples/Demo/Program.cs @@ -11,7 +11,7 @@ static class Program static async Task Main(string[] args) { const string filename = "test.docx"; - string html = ResourceHelper.GetString("Resources.UlStyles.html"); + string html = ResourceHelper.GetString("Resources.CompleteRunTest.html"); if (File.Exists(filename)) File.Delete(filename); using (MemoryStream generatedDocument = new()) @@ -36,7 +36,9 @@ static async Task Main(string[] args) AssertThatOpenXmlDocumentIsValid(package); } - await File.WriteAllBytesAsync(filename, generatedDocument.ToArray()); + generatedDocument.Position = 0L; + await using var fileStream = new FileStream(filename, FileMode.Create); + await generatedDocument.CopyToAsync(fileStream); } Process.Start(new ProcessStartInfo(filename) { UseShellExecute = true }); From 4cee80e76e25163b7b9cb34b24a542b87b513e02 Mon Sep 17 00:00:00 2001 From: Olivier Nizet Date: Mon, 2 Nov 2026 21:21:22 +0100 Subject: [PATCH 09/18] The unit test for `style` tag was invalid. Fix the unit test --- test/HtmlToOpenXml.Tests/ParserTests.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/HtmlToOpenXml.Tests/ParserTests.cs b/test/HtmlToOpenXml.Tests/ParserTests.cs index db547621..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("")] From 9a02d49f13e0341a1f92a3397daf0492440e34ef Mon Sep 17 00:00:00 2001 From: Olivier Nizet Date: Mon, 2 Nov 2026 22:40:21 +0100 Subject: [PATCH 10/18] Add missing Trim(), thanks to @AyUsH18102001 --- src/Html2OpenXml/Collections/HtmlAttributeCollection.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Html2OpenXml/Collections/HtmlAttributeCollection.cs b/src/Html2OpenXml/Collections/HtmlAttributeCollection.cs index f231c285..d114fded 100755 --- a/src/Html2OpenXml/Collections/HtmlAttributeCollection.cs +++ b/src/Html2OpenXml/Collections/HtmlAttributeCollection.cs @@ -413,7 +413,7 @@ public HtmlFont GetFont() } else if (stringSuffix.Is("-weight")) { - if (Converter.TryParseFontWeight(rawValue.AsSpan()[decl.Value], out var w)) + if (Converter.TryParseFontWeight(rawValue.AsSpan()[decl.Value].Trim(), out var w)) weight = w; } else if (stringSuffix.Is("-family")) From 72fcd3399846fce0e13a8210f43f797e6843fdbe Mon Sep 17 00:00:00 2001 From: Olivier Nizet Date: Mon, 2 Nov 2026 23:19:12 +0100 Subject: [PATCH 11/18] Early resolve the Word document body and ensure SectionProperties is last, while top anchor is first --- .../Expressions/BodyExpression.cs | 2 +- src/Html2OpenXml/HtmlConverter.cs | 50 ++++++++----------- src/Html2OpenXml/WordDocumentFactory.cs | 13 +++++ .../HtmlConverterTestBase.cs | 11 +--- test/HtmlToOpenXml.Tests/ImgTests.cs | 1 - test/HtmlToOpenXml.Tests/LinkTests.cs | 21 ++++---- test/HtmlToOpenXml.Tests/NumberingTests.cs | 26 ++++------ 7 files changed, 61 insertions(+), 63 deletions(-) diff --git a/src/Html2OpenXml/Expressions/BodyExpression.cs b/src/Html2OpenXml/Expressions/BodyExpression.cs index 9e546968..597cccf6 100644 --- a/src/Html2OpenXml/Expressions/BodyExpression.cs +++ b/src/Html2OpenXml/Expressions/BodyExpression.cs @@ -50,7 +50,7 @@ public override IEnumerable Interpret(ParsingContext context) var bookmarkId = IncrementBookmarkId(context).ToString(CultureInfo.InvariantCulture); // this is expected to stand in the 1st paragraph - Paragraph? p = body.FirstChild as Paragraph; + Paragraph? p = body.GetFirstChild(); p ??= body.PrependChild(new Paragraph()); p.InsertAfter(new BookmarkEnd() { Id = bookmarkId }, p.ParagraphProperties); p.InsertAfter(new BookmarkStart() { Id = bookmarkId, Name = "_top" }, p.ParagraphProperties); diff --git a/src/Html2OpenXml/HtmlConverter.cs b/src/Html2OpenXml/HtmlConverter.cs index 4c626f76..9317e245 100755 --- a/src/Html2OpenXml/HtmlConverter.cs +++ b/src/Html2OpenXml/HtmlConverter.cs @@ -67,9 +67,10 @@ namespace HtmlToOpenXml; public partial class HtmlConverter { internal readonly MainDocumentPart mainPart; + private readonly Body body; + // Cache all the ImagePart processed to avoid downloading the same image private IImageLoader? headerImageLoader, bodyImageLoader, footerImageLoader; - private readonly WordDocumentStyle htmlStyles; private readonly IWebRequest webRequester; @@ -87,7 +88,8 @@ public partial class HtmlConverter public HtmlConverter(MainDocumentPart mainPart, IWebRequest? webRequester = null) { this.mainPart = mainPart ?? throw new ArgumentNullException(nameof(mainPart)); - this.htmlStyles = new WordDocumentStyle(mainPart); + this.body = WordDocumentFactory.GetOrCreateDocumentBody(mainPart); + HtmlStyles = new WordDocumentStyle(mainPart); this.webRequester = webRequester ?? new DefaultWebRequest(); } @@ -108,7 +110,8 @@ public HtmlConverter(WordprocessingDocument package, IWebRequest? webRequester = throw new ArgumentNullException(nameof(package)); this.mainPart = WordDocumentFactory.GetOrCreateMainDocumentPart(package); - this.htmlStyles = new WordDocumentStyle(this.mainPart); + this.body = WordDocumentFactory.GetOrCreateDocumentBody(mainPart); + HtmlStyles = new WordDocumentStyle(this.mainPart); this.webRequester = webRequester ?? new DefaultWebRequest(); } @@ -196,7 +199,7 @@ public async Task ParseHeader(string html, HeaderFooterValues? headerType = null var paragraphs = await ParseCoreAsync(html, headerPart, headerImageLoader, new ParallelOptions() { CancellationToken = cancellationToken }, - htmlStyles.GetParagraphStyle(htmlStyles.DefaultStyles.ParagraphHeaderStyle)) + HtmlStyles.GetParagraphStyle(HtmlStyles.DefaultStyles.ParagraphHeaderStyle)) .ConfigureAwait(false); headerPart.Header.Append(paragraphs); @@ -226,7 +229,7 @@ public async Task ParseFooter(string html, HeaderFooterValues? footerType = null var paragraphs = await ParseCoreAsync(html, footerPart, footerImageLoader, new ParallelOptions() { CancellationToken = cancellationToken }, - htmlStyles.GetParagraphStyle(htmlStyles.DefaultStyles.ParagraphFooterStyle)) + HtmlStyles.GetParagraphStyle(HtmlStyles.DefaultStyles.ParagraphFooterStyle)) .ConfigureAwait(false); footerPart.Footer.Append(paragraphs); @@ -258,23 +261,30 @@ public async Task ParseBody(string html, CancellationToken cancellationToken = d bodyImageLoader ??= new ImagePrefetcher(mainPart, webRequester, ImageProcessing); var paragraphs = await ParseCoreAsync(html, mainPart, bodyImageLoader, new ParallelOptions() { CancellationToken = cancellationToken }, - htmlStyles.GetParagraphStyle(htmlStyles.DefaultStyles.ParagraphBodyStyle)) + HtmlStyles.GetParagraphStyle(HtmlStyles.DefaultStyles.ParagraphBodyStyle)) .ConfigureAwait(false); if (!paragraphs.Any()) return; - Body body = mainPart.Document!.Body!; SectionProperties? sectionProperties = body.GetLastChild() ?? WordDocumentFactory.CreateSectionProperties(PageOrientation.Portrait); foreach (var para in paragraphs) body.Append(para); + // Push the sectionProperties as the last element of the Body + // (required by OpenXml schema to avoid the bad formatting of the document) + if (sectionProperties?.Parent != null) + { + sectionProperties.Remove(); + body.AddChild(sectionProperties); + } + // we automatically create the _top bookmark if missing. To avoid having an empty paragrah, // let's try to merge with its next paragraph. var p = body.GetFirstChild(); - if (p != null && p.GetFirstChild()?.Name == "_top" + if (p?.GetFirstChild()?.Name == "_top" && !p.HasChild() && p.NextSibling() is Paragraph nextPara) { @@ -282,14 +292,6 @@ public async Task ParseBody(string html, CancellationToken cancellationToken = d nextPara.PrependChild(p.GetFirstChild()!.CloneNode(false)); p.Remove(); } - - // Push the sectionProperties as the last element of the Body - // (required by OpenXml schema to avoid the bad formatting of the document) - if (sectionProperties != null && sectionProperties.Parent != null) - { - sectionProperties.Remove(); - body.AddChild(sectionProperties); - } } /// @@ -300,7 +302,7 @@ public async Task ParseBody(string html, CancellationToken cancellationToken = d /// from event. public void RefreshStyles() { - htmlStyles.PrepareStyles(mainPart); + HtmlStyles.PrepareStyles(mainPart); } /// @@ -325,11 +327,6 @@ private async Task> ParseCoreAsync(string h if (htmlDocument == null) return []; - if (mainPart.Document == null) - new Document(new Body()).Save(mainPart); - else if (mainPart.Document.Body == null) - mainPart.Document.Body = new Body(); - await PreloadImages(htmlDocument, imageLoader, parallelOptions).ConfigureAwait(false); Expressions.HtmlDomExpression expression; @@ -377,11 +374,11 @@ private TPart ResolveHeaderFooterPart(HeaderFooterValues? type) bool wasRefSet = false; TPart? part = null; - var sectionProps = mainPart.Document!.Body!.Elements(); + var sectionProps = body.Elements(); if (!sectionProps.Any()) { sectionProps = [new SectionProperties()]; - mainPart.Document.Body!.AddChild(sectionProps.First()); + body.AddChild(sectionProps.First()); } else { @@ -452,10 +449,7 @@ private TPart ResolveHeaderFooterPart(HeaderFooterValues? type) /// and react when a referenced style is missing from the document. /// /// - public WordDocumentStyle HtmlStyles - { - get { return htmlStyles; } - } + public WordDocumentStyle HtmlStyles { get; } /// /// Defines where the Legend tag (caption) should be rendered above or below the table. diff --git a/src/Html2OpenXml/WordDocumentFactory.cs b/src/Html2OpenXml/WordDocumentFactory.cs index 2785ccd0..1cf0f513 100644 --- a/src/Html2OpenXml/WordDocumentFactory.cs +++ b/src/Html2OpenXml/WordDocumentFactory.cs @@ -80,6 +80,19 @@ internal static MainDocumentPart GetOrCreateMainDocumentPart(WordprocessingDocum return mainPart; } + /// + /// Gets the document body part associated with the document, creating it when it does not already exist. + /// + internal static Body GetOrCreateDocumentBody(MainDocumentPart mainPart) + { + if (mainPart.Document == null) + new Document(new Body()).Save(mainPart); + else if (mainPart.Document.Body == null) + mainPart.Document.Body = new Body(); + + return mainPart.Document!.Body!; + } + /// /// Generate the required OpenXml element for handling page orientation. /// diff --git a/test/HtmlToOpenXml.Tests/HtmlConverterTestBase.cs b/test/HtmlToOpenXml.Tests/HtmlConverterTestBase.cs index 2b56cac0..7c9c361b 100644 --- a/test/HtmlToOpenXml.Tests/HtmlConverterTestBase.cs +++ b/test/HtmlToOpenXml.Tests/HtmlConverterTestBase.cs @@ -19,16 +19,9 @@ 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); + this.converter = new HtmlConverter(package); } [TearDown] diff --git a/test/HtmlToOpenXml.Tests/ImgTests.cs b/test/HtmlToOpenXml.Tests/ImgTests.cs index dea1fb75..e07d4303 100644 --- a/test/HtmlToOpenXml.Tests/ImgTests.cs +++ b/test/HtmlToOpenXml.Tests/ImgTests.cs @@ -239,7 +239,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..c9d0daa3 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"); @@ -284,7 +287,7 @@ await converter.ParseBody(@"Move to top 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 48687006..1de8f7e8 100644 --- a/test/HtmlToOpenXml.Tests/NumberingTests.cs +++ b/test/HtmlToOpenXml.Tests/NumberingTests.cs @@ -33,11 +33,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 +71,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 +338,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 +346,6 @@ await converter.ParseBody(
  2. Item 2
"); - var elements = mainPart.Document!.Body!.ChildElements; var absNum = mainPart.NumberingDefinitionsPart?.Numbering? .Elements() .SingleOrDefault(); @@ -408,14 +407,13 @@ public void OverrideStartNumber_WithUl_ShouldBeIgnored() [Test] public async Task RomanList_ReturnsListWithCustomStyle() { - await converter.ParseBody(@"
- - - - - - - - - - - - -
Header 1Header 2
Cell 1Cell 2
Cell 3Cell 4
- - -
- - - - - - - -
- - - -

- Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. -

-

- Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. -

-

- Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. -

-

- Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. -

-

- Curabitur pretium tincidunt lacus. Nulla gravida orci a odio. Nullam varius, turpis et commodo pharetra, est eros bibendum elit, nec luctus magna felis sollicitudin mauris. -

-

- Integer in mauris eu nibh euismod gravida. Duis ac tellus et risus vulputate vehicula. Donec lobortis risus a elit. Etiam tempor. Ut ullamcorper, ligula eu tempor congue, eros est euismod turpis, id tincidunt sapien risus a quam. -

-

- Maecenas fermentum consequat mi. Donec fermentum. Pellentesque malesuada nulla a mi. Duis sapien sem, aliquet nec, commodo eget, consequat quis, neque. Aliquam faucibus, elit ut dictum aliquet, felis nisl adipiscing sapien, sed malesuada diam lacus eget erat. -

-

- Cras mollis scelerisque nunc. Nullam arcu. Aliquam consequat. Curabitur augue lorem, dapibus quis, laoreet et, pretium ac, nisi. Aenean magna nisl, mollis quis, molestie eu, feugiat in, orci. In hac habitasse platea dictumst. -

-

- Fusce convallis, mauris imperdiet gravida bibendum, nisl turpis suscipit mauris, sed placerat ipsum ligula sed magna. Maecenas nisl est, ultrices nec, congue eget, auctor vitae, massa. -

-

- Fusce luctus vestibulum augue ut aliquet. Nunc sagittis dictum nisi. Sed id blandit purus. Proin quis orci. Quisque convallis libero in sapien pharetra tincidunt. -

- - - -

- Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. -

-

- Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. -

-

- Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. -

-

- Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. -

-

- Curabitur pretium tincidunt lacus. Nulla gravida orci a odio. Nullam varius, turpis et commodo pharetra, est eros bibendum elit, nec luctus magna felis sollicitudin mauris. -

-

- Integer in mauris eu nibh euismod gravida. Duis ac tellus et risus vulputate vehicula. Donec lobortis risus a elit. Etiam tempor. Ut ullamcorper, ligula eu tempor congue, eros est euismod turpis, id tincidunt sapien risus a quam. -

-

- Maecenas fermentum consequat mi. Donec fermentum. Pellentesque malesuada nulla a mi. Duis sapien sem, aliquet nec, commodo eget, consequat quis, neque. Aliquam faucibus, elit ut dictum aliquet, felis nisl adipiscing sapien, sed malesuada diam lacus eget erat. -

-

- Cras mollis scelerisque nunc. Nullam arcu. Aliquam consequat. Curabitur augue lorem, dapibus quis, laoreet et, pretium ac, nisi. Aenean magna nisl, mollis quis, molestie eu, feugiat in, orci. In hac habitasse platea dictumst. -

-

- Fusce convallis, mauris imperdiet gravida bibendum, nisl turpis suscipit mauris, sed placerat ipsum ligula sed magna. Maecenas nisl est, ultrices nec, congue eget, auctor vitae, massa. -

-

- Fusce luctus vestibulum augue ut aliquet. Nunc sagittis dictum nisi. Sed id blandit purus. Proin quis orci. Quisque convallis libero in sapien pharetra tincidunt. -

- - - From a45210088a66f5b101d2d18d7d3c58add0905cae Mon Sep 17 00:00:00 2001 From: Ayush Hiremani <76835968+AyUsH18102001@users.noreply.github.com> Date: Sat, 7 Nov 2026 01:54:58 +0530 Subject: [PATCH 14/18] Nested List Start Attribute & Indentation Regression (#264) Co-authored-by: Ayush Hiremani --- .../Expressions/Numbering/ListExpression.cs | 24 +++++------- test/HtmlToOpenXml.Tests/NumberingTests.cs | 37 +++++++++++++++++++ 2 files changed, 47 insertions(+), 14 deletions(-) diff --git a/src/Html2OpenXml/Expressions/Numbering/ListExpression.cs b/src/Html2OpenXml/Expressions/Numbering/ListExpression.cs index 62a87a27..636f312e 100644 --- a/src/Html2OpenXml/Expressions/Numbering/ListExpression.cs +++ b/src/Html2OpenXml/Expressions/Numbering/ListExpression.cs @@ -23,7 +23,9 @@ namespace HtmlToOpenXml.Expressions; sealed class ListExpression(IHtmlElement node) : NumberingExpressionBase(node) { readonly record struct ListContext(string Name, int AbsNumId, int InstanceId, int Level, DirectionMode? Dir); - private long _listIndentationOffset; + private readonly bool isOrderedTag = node.NodeName.Equals("ol", StringComparison.OrdinalIgnoreCase); + private long leftIndentation; + private int startValue = 1; // https://www.w3schools.com/cssref/playdemo.php?filename=playcss_list-style-type @@ -68,14 +70,16 @@ private IEnumerable InterpretListItems(ParsingContext context, I var listContext = context.Properties("listContext"); var parentContext = listContext; var listStyle = GetListName(node, listContext.Name); + if (isOrderedTag && int.TryParse(node.GetAttribute("start"), out int val)) + startValue = val; bool listMarginOnNumberingInstance = false; - if (listContext.InstanceId == 0 || listContext.Name != listStyle || _listIndentationOffset > 0) + if (listContext.InstanceId == 0 || listContext.Name != listStyle || leftIndentation > 0 || startValue != 1 ) { var abstractNumId = GetOrCreateListTemplate(context, listStyle); - listContext = ConcretiseInstance(context, abstractNumId, listStyle, listContext.Level, _listIndentationOffset); + listContext = ConcretiseInstance(context, abstractNumId, listStyle, listContext.Level, leftIndentation); listParagraphStyleId = GetStyleIdForListItem(context.DocumentStyle, node, defaultIfEmpty: false); - listMarginOnNumberingInstance = _listIndentationOffset > 0; + listMarginOnNumberingInstance = leftIndentation > 0; } else { @@ -142,7 +146,7 @@ private IEnumerable InterpretListItems(ParsingContext context, I p.ParagraphProperties ??= new(); p.ParagraphProperties.ParagraphStyleId ??= (ParagraphStyleId?) listItemStyleId!.CloneNode(true); - SetListItemElementParagraphIndentationLeft(p.ParagraphProperties, level, _listIndentationOffset); + SetListItemElementParagraphIndentationLeft(p.ParagraphProperties, level, leftIndentation); } foreach (var child in childElements) @@ -192,14 +196,6 @@ private ListContext ConcretiseInstance(ParsingContext context, int abstractNumId return new ListContext(listStyle, abstractNumId, instanceId.Value, currentLevel + 1, dir); } - int startValue = 1; - if (isOrderedTag) - { - var startAttribute = node.GetAttribute("start"); - if (startAttribute != null && int.TryParse(startAttribute, out var val) && val > 1) - startValue = val; - } - var numbering = context.MainPart.NumberingDefinitionsPart!.Numbering!; var levelOverride = CreateLevelOverride(numbering, abstractNumId, listContext.Level, startValue, listMarginLeft); numbering.Append( @@ -329,7 +325,7 @@ protected override void ComposeStyles(ParsingContext context) base.ComposeStyles(context); var margin = styleAttributes.GetMargin(); if (!margin.IsEmpty && margin.Left.IsFixed && margin.Left.Value > 0) - _listIndentationOffset = margin.Left.ValueInDxa; + leftIndentation = margin.Left.ValueInDxa; } /// diff --git a/test/HtmlToOpenXml.Tests/NumberingTests.cs b/test/HtmlToOpenXml.Tests/NumberingTests.cs index 1de8f7e8..75ab3a29 100644 --- a/test/HtmlToOpenXml.Tests/NumberingTests.cs +++ b/test/HtmlToOpenXml.Tests/NumberingTests.cs @@ -917,6 +917,33 @@ public async Task UnorderedList_CssListStyleType_OverridesTypeAttribute() AssertThatOpenXmlDocumentIsValid(); } + [Test(Description = "Nested ordered list start value is reflected in the marker value")] + public async Task NestedOrderedList_StartValue_IsAddedToMarkerValue() + { + await converter.ParseBody(@"
  1. One
    1. Ten
"); + + var paragraphs = mainPart.Document!.Body!.Elements().ToList(); + Assert.That(GetListMarkerNumberingValue(paragraphs.Last()), Is.EqualTo("10")); + AssertThatOpenXmlDocumentIsValid(); + } + + [Test(Description = "Paragraph margin-left inside a list item must be applied independently of the list item indentation")] + public async Task ListItemWithMultipleParagraphs_AppliesIndependentParagraphIndentation() + { + await converter.ParseBody(@"
  1. First

    Last

"); + var paragraphs = mainPart.Document?.Body!.Elements().ToList(); + var firstParagraph = paragraphs?.First(); + var lastParagraph = paragraphs?.Last(); + + var firstParaIndent = firstParagraph?.ParagraphProperties?.Indentation?.Left?.Value; + var lastParaIndent = lastParagraph?.ParagraphProperties?.Indentation?.Left?.Value; + + Assert.That(firstParaIndent, Is.Null, "The first paragraph should not have direct indentation because indentation is assigned through the list levelOverride instance."); + Assert.That(lastParaIndent, Is.Not.Null); + // i.e. level indentation + paragraph indentation + list left indentation = 720+360+360 = 1440 + Assert.That(lastParaIndent, Is.EqualTo("1440"), "The last paragraph must have its own additional indentation from its margin-left. qith value equal to 360 dxa"); + } + private string? GetBulletText(Paragraph paragraph) { var numberingProperties = paragraph.ParagraphProperties?.NumberingProperties; @@ -927,5 +954,15 @@ 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? GetListMarkerNumberingValue(Paragraph paragraph) + { + var numberingProperties = paragraph.ParagraphProperties?.NumberingProperties; + var numId = numberingProperties?.NumberingId?.Val?.Value; + var level = numberingProperties?.NumberingLevelReference?.Val?.Value; + var numbering = mainPart.NumberingDefinitionsPart!.Numbering!; + var instance = numbering.Elements().Single(i => i.NumberID?.Value == numId); + return instance.GetFirstChild()?.GetFirstChild()?.Val; + } } } From b2ddd5d34a9cb81f2e920ca9ec24cdd2498e939e Mon Sep 17 00:00:00 2001 From: Olivier Nizet Date: Fri, 13 Nov 2026 18:46:28 +0100 Subject: [PATCH 15/18] Fix numbering indentation (#267) --- Directory.Build.props | 2 +- .../Expressions/BlockElementExpression.cs | 64 ++-- .../Expressions/Numbering/ListContext.cs | 28 ++ .../Expressions/Numbering/ListExpression.cs | 279 +++++++++--------- .../Numbering/NumberingExpressionBase.cs | 37 ++- .../Utilities/AngleSharpExtensions.cs | 2 +- test/HtmlToOpenXml.Tests/NumberingTests.cs | 226 +++++++------- test/HtmlToOpenXml.Tests/TableTests.cs | 4 +- 8 files changed, 334 insertions(+), 308 deletions(-) create mode 100644 src/Html2OpenXml/Expressions/Numbering/ListContext.cs diff --git a/Directory.Build.props b/Directory.Build.props index a5e00870..be7f02c7 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -2,7 +2,7 @@ Copyright 2009-$([System.DateTime]::Today.Year) Olivier Nizet enable - latest + preview enable 4.2.0 diff --git a/src/Html2OpenXml/Expressions/BlockElementExpression.cs b/src/Html2OpenXml/Expressions/BlockElementExpression.cs index a46a4d64..fc9558ee 100644 --- a/src/Html2OpenXml/Expressions/BlockElementExpression.cs +++ b/src/Html2OpenXml/Expressions/BlockElementExpression.cs @@ -22,6 +22,8 @@ namespace HtmlToOpenXml.Expressions; ///
class BlockElementExpression: PhrasingElementExpression { + // 100% A4 page width expressed in Pct + internal const string FullPageWidthPct = "5000"; private readonly OpenXmlLeafElement[]? defaultStyleProperties; protected readonly ParagraphProperties paraProperties = new(); protected TableProperties? tableProperties; @@ -89,25 +91,8 @@ protected override IEnumerable Interpret ( ParsingContext context, IEnumerable childNodes) { return ComposeChildren(context, childNodes, paraProperties, - (runs) => { - if (styleAttributes.RequiresPageBreakBefore()) - { - runs.Add( - new Run( - new Break() { Type = BreakValues.Page }) - ); - runs.Add(new Run( - new LastRenderedPageBreak()) - ); - } - }, - (runs) => { - if (styleAttributes.RequiresPageBreakAfter()) - { - runs.Add(new Run( - new Break() { Type = BreakValues.Page })); - } - }); + prefixRuns: CreatePageBreakBeforeRuns(), + suffiRuns: CreatePageBreakAfterRuns()); } public override void CascadeStyles(OpenXmlElement element) @@ -301,18 +286,19 @@ protected override void ComposeStyles (ParsingContext context) /// The child parsing context. /// The list of child nodes. /// The parent paragraph properties to apply. - /// Optionally insert new runs at the beginning of the processing. - /// Optionally insert new runs at the end of the processing. + /// Prepend runs at the beginning of the processing (optional). + /// Append runs at the end of the processing (optional). internal static IEnumerable ComposeChildren(ParsingContext context, IEnumerable childNodes, ParagraphProperties paragraphProperties, - Action>? preAction = null, - Action>? postAction = null) + IEnumerable? prefixRuns = null, + IEnumerable? suffiRuns = null) { var runs = new List(); var flowElements = new List(); - preAction?.Invoke(runs); + if (prefixRuns != null) + runs.AddRange(prefixRuns); OpenXmlElement? previousElement = null; foreach (var child in childNodes) @@ -346,7 +332,8 @@ internal static IEnumerable ComposeChildren(ParsingContext conte } } - postAction?.Invoke(runs); + if (suffiRuns != null) + runs.AddRange(suffiRuns); if (runs.Count > 0) flowElements.Add(CreateParagraph(context, runs, paragraphProperties)); @@ -379,7 +366,6 @@ private static Paragraph CreateParagraph(ParsingContext context, IList /// Group all the paragraph inside a framed table. /// @@ -393,7 +379,10 @@ protected Table CreateFrame(IEnumerable childElements) TableProperties tableProperties; Table framedTable = new( tableProperties = new TableProperties { - TableWidth = new() { Type = TableWidthUnitValues.Pct, Width = "5000" } // 100% + TableWidth = new() { + Type = TableWidthUnitValues.Pct, + Width = FullPageWidthPct + } }, new TableGrid( new GridColumn() { Width = "9442" }), @@ -442,4 +431,25 @@ protected static int IncrementBookmarkId(ParsingContext context) context.Properties("bookmarkRef", bookmarkRef); return bookmarkRef.Value; } + + private IEnumerable CreatePageBreakBeforeRuns() + { + if (!styleAttributes.RequiresPageBreakBefore()) + yield break; + + yield return new Run( + new Break() { Type = BreakValues.Page }); + + yield return new Run( + new LastRenderedPageBreak()); + } + + private IEnumerable CreatePageBreakAfterRuns() + { + if (!styleAttributes.RequiresPageBreakAfter()) + yield break; + + yield return new Run( + new Break() { Type = BreakValues.Page }); + } } diff --git a/src/Html2OpenXml/Expressions/Numbering/ListContext.cs b/src/Html2OpenXml/Expressions/Numbering/ListContext.cs new file mode 100644 index 00000000..b28f3841 --- /dev/null +++ b/src/Html2OpenXml/Expressions/Numbering/ListContext.cs @@ -0,0 +1,28 @@ +/* Copyright (C) Olivier Nizet https://github.com/onizet/html2openxml - All Rights Reserved + * + * This source is subject to the Microsoft Permissive License. + * Please see the License.txt file for more information. + * All other rights reserved. + * + * THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY + * KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A + * PARTICULAR PURPOSE. + */ +using AngleSharp.Dom; + +namespace HtmlToOpenXml.Expressions; + +/// +/// Represents the current numbering state while traversing nested HTML lists. +/// +readonly record struct ListContext(string Name, int AbsNumId, int InstanceId, + int Level, DirectionMode? Dir, long MarginLeftDxa) +{ + public ListContext NextLevel(DirectionMode? dir, long extraMargin) + => this with { + Level = Level+1, + Dir = dir ?? Dir, + MarginLeftDxa = MarginLeftDxa + extraMargin + }; +} \ No newline at end of file diff --git a/src/Html2OpenXml/Expressions/Numbering/ListExpression.cs b/src/Html2OpenXml/Expressions/Numbering/ListExpression.cs index 636f312e..6cb94878 100644 --- a/src/Html2OpenXml/Expressions/Numbering/ListExpression.cs +++ b/src/Html2OpenXml/Expressions/Numbering/ListExpression.cs @@ -22,22 +22,22 @@ namespace HtmlToOpenXml.Expressions; /// sealed class ListExpression(IHtmlElement node) : NumberingExpressionBase(node) { - readonly record struct ListContext(string Name, int AbsNumId, int InstanceId, int Level, DirectionMode? Dir); - private readonly bool isOrderedTag = node.NodeName.Equals("ol", StringComparison.OrdinalIgnoreCase); - private long leftIndentation; - private int startValue = 1; - - - // https://www.w3schools.com/cssref/playdemo.php?filename=playcss_list-style-type + // https://developer.mozilla.org/en-US/docs/Web/CSS/Reference/Properties/list-style-type // https://answers.microsoft.com/en-us/msoffice/forum/all/custom-list-number-style/21a54399-4404-4c37-8843-2ccaaf827485 // Image bullet: http://officeopenxml.com/WPnumbering-imagesAsSymbol.php private static readonly HashSet supportedListTypes = - ["disc", "decimal", "square", "circle", "dash", + [with(StringComparer.OrdinalIgnoreCase), "disc", "decimal", "square", "circle", "dash", "lower-alpha", "upper-alpha", "lower-latin", "upper-latin", "lower-greek", "upper-greek", "lower-roman", "upper-roman", "decimal-tiered" /* not W3C compliant */]; + private const string StandaloneParagraphMarker = "list-marker"; private ParagraphStyleId? listParagraphStyleId; + private readonly bool isOrderedTag = node.NodeName.Equals("ol", StringComparison.OrdinalIgnoreCase); + private long listMarginLeftDxa; + private int startValue = 1, leftIndentation; + private bool isNestedList; + public override IEnumerable Interpret(ParsingContext context) @@ -46,16 +46,17 @@ public override IEnumerable Interpret(ParsingContext context) var liNodes = node.Children.Where(n => n.LocalName.Equals("li", StringComparison.OrdinalIgnoreCase)); if (!liNodes.Any()) return []; - if (renderAsFramed) + if (isOrderedTag && int.TryParse(node.GetAttribute("start"), out int val) && val > 1) + startValue = val; + + var margin = styleAttributes.GetMargin(); + if (margin.Left.IsFixed && margin.Left.Value != 0) { - return [CreateFrame(InterpretListItems(context, liNodes))]; + listMarginLeftDxa = margin.Left.ValueInDxa; + paraProperties.Indentation = null; // clear to prevent cascading on children } - return InterpretListItems(context, liNodes); - } - private IEnumerable InterpretListItems(ParsingContext context, IEnumerable liNodes) - { // W3C requires that nested list stands below a `li` element but some editors // don't care to respect the standard. Let's reparent those lists var nestedList = node.Children.Where(n => @@ -69,172 +70,204 @@ private IEnumerable InterpretListItems(ParsingContext context, I var listContext = context.Properties("listContext"); var parentContext = listContext; + + var numberingContext = context.CreateChild(this, isStyleScoped: !isNestedList); + var liParagraphs = InterpretListItems(numberingContext, listContext, liNodes).ToList(); + + // restore parent context + context.Properties("listContext", parentContext); + + // this marker is used to process only once any potential standalone para. + // we remove this as DivId requires a proper registration in WebSettings.DivIds + if (parentContext.Level == 0) + { + foreach (var p in liParagraphs.OfType().Where(p => p.ParagraphProperties?.DivId is not null)) + p.ParagraphProperties!.DivId!.Remove(); + } + + if (renderAsFramed) + { + return [CreateFrame(liParagraphs)]; + } + + return liParagraphs; + } + + private IEnumerable InterpretListItems(ParsingContext context, ListContext listContext, IEnumerable liNodes) + { var listStyle = GetListName(node, listContext.Name); - if (isOrderedTag && int.TryParse(node.GetAttribute("start"), out int val)) - startValue = val; - bool listMarginOnNumberingInstance = false; - if (listContext.InstanceId == 0 || listContext.Name != listStyle || leftIndentation > 0 || startValue != 1 ) + + if (listContext.InstanceId == 0 || listContext.Name != listStyle || startValue != 1) { var abstractNumId = GetOrCreateListTemplate(context, listStyle); - listContext = ConcretiseInstance(context, abstractNumId, listStyle, listContext.Level, leftIndentation); + listContext = ConcretiseInstance(context, abstractNumId, listStyle, listContext.Level, + listContext.MarginLeftDxa + listMarginLeftDxa); + leftIndentation = (int) (listContext.Level * LevelIndent + listMarginLeftDxa); listParagraphStyleId = GetStyleIdForListItem(context.DocumentStyle, node, defaultIfEmpty: false); - listMarginOnNumberingInstance = leftIndentation > 0; } else { - var dir = node.GetTextDirection(); - listContext = new ListContext(listContext.Name, listContext.AbsNumId, - listContext.InstanceId, listContext.Level + 1, dir ?? listContext.Dir); + listContext = listContext.NextLevel(node.GetTextDirection(), listMarginLeftDxa); + leftIndentation = listContext.Level * LevelIndent; } context.Properties("listContext", listContext); - var numberingContext = context.CreateChild(this, isStyleScoped: true); + isNestedList = listContext.Level > 1; - // +1 because index starts on 1 and not 0 - var level = Math.Min(listContext.Level, MaxLevel+1); foreach (IHtmlElement liNode in liNodes.Cast()) { var expression = new BlockElementExpression(liNode); - var childElements = expression.Interpret(numberingContext); + var childElements = expression.Interpret(context); if (!childElements.Any()) continue; // table must be aligned to the list item var tables = childElements.OfType(); - var tableIndentation = level * Indentation; - foreach (var table in tables) - { - var tableProperties = table.GetFirstChild(); - if (tableProperties == null) - table.PrependChild(tableProperties = new()); - - tableProperties.TableIndentation ??= new() { Width = tableIndentation * 2 }; - // ensure to restrain the table width to the list item - if (tableProperties.TableWidth?.Type?.Value == TableWidthUnitValues.Pct - && tableProperties.TableWidth?.Width?.Value == "5000") - { - tableProperties.TableWidth.Width = (5000 - tableIndentation).ToString(); - } - } + AdjustTableIndent(tables); // ensure to filter out any non-paragraph like any nested table var paragraphs = childElements.OfType(); var listItemStyleId = GetStyleIdForListItem(context.DocumentStyle, liNode); - if (paragraphs.Any()) - { - var p = paragraphs.First(); - p.ParagraphProperties ??= new(); - p.ParagraphProperties.ParagraphStyleId = listItemStyleId; - p.ParagraphProperties!.NumberingProperties ??= new NumberingProperties { - NumberingLevelReference = new() { Val = level - 1 }, - NumberingId = new() { Val = listContext.InstanceId } - }; - if (listContext.Dir.HasValue) { - p.ParagraphProperties.BiDi = new() { - Val = OnOffValue.FromBoolean(listContext.Dir == DirectionMode.Rtl) - }; - } - } - - // any standalone paragraphs must be aligned (indented) along its current level - foreach (var p in paragraphs.Skip(1)) + var firstPara = paragraphs.FirstOrDefault(); + if (firstPara != null) { - // if this is a list item paragraph, skip it - if (p.ParagraphProperties?.NumberingProperties is not null) - continue; + AdjustListItemParagraphIndent(firstPara, listContext, listItemStyleId); - p.ParagraphProperties ??= new(); - p.ParagraphProperties.ParagraphStyleId ??= (ParagraphStyleId?) listItemStyleId!.CloneNode(true); - SetListItemElementParagraphIndentationLeft(p.ParagraphProperties, level, leftIndentation); + // any standalone paragraphs must be aligned (indented) along its current level + AdjustStandaloneParagraphIndent(paragraphs.Skip(1), listItemStyleId); } foreach (var child in childElements) yield return child; } + } - context.Properties("listContext", parentContext); + private void AdjustTableIndent(IEnumerable
tables) + { + foreach (var table in tables) + { + var tableProperties = table.GetFirstChild(); + if (tableProperties == null) + table.PrependChild(tableProperties = new()); + + tableProperties.TableIndentation ??= new() { Width = leftIndentation }; + // ensure to restrain the table width to the list item + if (tableProperties.TableWidth?.Type?.Value == TableWidthUnitValues.Pct + && tableProperties.TableWidth?.Width?.Value == FullPageWidthPct) + { + tableProperties.TableWidth.Width = (5000 - leftIndentation).ToString(); + } + } + } + + private void AdjustListItemParagraphIndent(Paragraph p, ListContext listContext, ParagraphStyleId? listItemStyleId) + { + p.ParagraphProperties ??= new(); + p.ParagraphProperties.ParagraphStyleId = listItemStyleId; + p.ParagraphProperties.NumberingProperties ??= new NumberingProperties { + NumberingLevelReference = new() { Val = listContext.Level - 1 }, + NumberingId = new() { Val = listContext.InstanceId } + }; + + if (listContext.Dir.HasValue) + { + p.ParagraphProperties.BiDi = new() { + Val = OnOffValue.FromBoolean(listContext.Dir == DirectionMode.Rtl) + }; + } + + // if this
  • paragraph contains its own padding, this add to hanging + // if the container list contains its own padding, this add to left indent + var liExtraMargin = ParseIndentationLeft(p.ParagraphProperties); // parsed paragraph left indentation (if any) + if (liExtraMargin > 0 || listMarginLeftDxa > 0) + { + p.ParagraphProperties.Indentation ??= new(); + p.ParagraphProperties.Indentation.Hanging = (Hanging + liExtraMargin).ToString(CultureInfo.InvariantCulture); + p.ParagraphProperties.Indentation.Left = leftIndentation.ToString(CultureInfo.InvariantCulture); + } + } + + private void AdjustStandaloneParagraphIndent(IEnumerable paragraphs, ParagraphStyleId? listItemStyleId) + { + foreach (var p in paragraphs) + { + // if this is a list item paragraph, skip it + if (p.ParagraphProperties?.NumberingProperties is not null) + { + continue; + } + + p.ParagraphProperties ??= new(); + + // this iteration could encounter nested paragraphs. We detect when this is DivId + if (p.ParagraphProperties.DivId != null) + continue; + + p.ParagraphProperties.DivId = new DivId() { Val = StandaloneParagraphMarker }; + p.ParagraphProperties.ParagraphStyleId ??= (ParagraphStyleId?) listItemStyleId!.CloneNode(true); + + // if this paragraph contains its own padding, this add to left indent + var liExtraMargin = ParseIndentationLeft(p.ParagraphProperties); // parsed paragraph left indentation (if any) + + p.ParagraphProperties.Indentation ??= new(); + p.ParagraphProperties.Indentation.Hanging = "0"; + p.ParagraphProperties.Indentation.Left = (leftIndentation + liExtraMargin).ToString(CultureInfo.InvariantCulture); + } } /// /// Create a new instance of a list template. /// - private ListContext ConcretiseInstance(ParsingContext context, int abstractNumId, string listStyle, int currentLevel, long listMarginLeft) + private ListContext ConcretiseInstance(ParsingContext context, int abstractNumId, string listStyle, + int currentLevel, long listMarginLeftDxa) { ListContext listContext; var instanceId = GetListInstance(abstractNumId); - int overrideLevelIndex = 0; - var isOrderedTag = node.NodeName.Equals("ol", StringComparison.OrdinalIgnoreCase); var dir = node.GetTextDirection(); + var newLevel = Math.Min(currentLevel + 1, MaxLevel); // be sure to restart to 1 any nested ordered list if (currentLevel > 0 && isOrderedTag) { instanceId = IncrementInstanceId(context, abstractNumId, isReusable: false); - overrideLevelIndex = currentLevel; - listContext = new ListContext(listStyle, abstractNumId, instanceId.Value, currentLevel + 1, dir); + listContext = new ListContext(listStyle, abstractNumId, instanceId.Value, newLevel, dir, listMarginLeftDxa); } - else if (!instanceId.HasValue || !context.Converter.ContinueNumbering || listMarginLeft > 0) + else if (!instanceId.HasValue || !context.Converter.ContinueNumbering) { // create a new instance of that list template - bool isReusable = context.Converter.ContinueNumbering && listMarginLeft <= 0; + bool isReusable = context.Converter.ContinueNumbering; instanceId = IncrementInstanceId(context, abstractNumId, isReusable: isReusable); - listContext = new ListContext(listStyle, abstractNumId, instanceId.Value, currentLevel + 1, dir); + listContext = new ListContext(listStyle, abstractNumId, instanceId.Value, newLevel, dir, listMarginLeftDxa); } else // if the previous element is the same list style, - // we must restart the ordering to 0 + // we must restart the ordering to 1 if (node.IsPrecededByListElement(out var precedingElement) - && GetListName(precedingElement!) == listStyle) + && GetListName(precedingElement) == listStyle) { instanceId = IncrementInstanceId(context, abstractNumId, isReusable: false); - listContext = new ListContext(listStyle, abstractNumId, instanceId.Value, 1, dir); + listContext = new ListContext(listStyle, abstractNumId, instanceId.Value, 1, dir, listMarginLeftDxa); } else { - return new ListContext(listStyle, abstractNumId, instanceId.Value, currentLevel + 1, dir); + return new ListContext(listStyle, abstractNumId, instanceId.Value, newLevel, dir, listMarginLeftDxa); } var numbering = context.MainPart.NumberingDefinitionsPart!.Numbering!; - var levelOverride = CreateLevelOverride(numbering, abstractNumId, listContext.Level, startValue, listMarginLeft); numbering.Append( new NumberingInstance( new AbstractNumId() { Val = abstractNumId }, - levelOverride + new LevelOverride( + new StartOverrideNumberingValue() { Val = startValue } + ) { LevelIndex = newLevel - 1 } ) { NumberID = instanceId.Value }); return listContext; } - /// - /// Builds the list instance level-override (start value and optional indent from list margin-left). - /// - private static LevelOverride CreateLevelOverride(Numbering numbering, int abstractNumId, int listLevel, int startValue, long listMarginLeftDxa) - { - int ilvl = Math.Max(0, Math.Min(listLevel, MaxLevel + 1) - 1); - var levelOverride = new LevelOverride( - new StartOverrideNumberingValue() { Val = startValue } - ) { LevelIndex = ilvl }; - - if (listMarginLeftDxa <= 0) - return levelOverride; - - long leftDxa = listLevel * Indentation * 2L + listMarginLeftDxa; - var abstractNum = numbering.Elements().First(a => a.AbstractNumberId!.Value == abstractNumId); - var templateLevel = abstractNum.Elements().First(l => l.LevelIndex!.Value == ilvl); - var overrideLevel = (Level)templateLevel.CloneNode(true); - overrideLevel.PreviousParagraphProperties ??= new PreviousParagraphProperties(); - overrideLevel.PreviousParagraphProperties.Indentation = new Indentation { - Left = leftDxa.ToString(CultureInfo.InvariantCulture), - Hanging = Indentation.ToString() - }; - levelOverride.Append(overrideLevel); - - return levelOverride; - } - /// /// Resolve the list style to determine which NumberList style to apply. /// @@ -298,9 +331,6 @@ private static string GetListName(IElement listNode, string? parentName = null) /// private ParagraphStyleId? GetStyleIdForListItem(WordDocumentStyle documentStyle, IHtmlElement liNode, bool defaultIfEmpty = true) { - if (listParagraphStyleId != null) - return (ParagraphStyleId) listParagraphStyleId.Clone(); - foreach(var clsName in liNode.ClassList) { var styleId = documentStyle.GetStyle(clsName, StyleValues.Paragraph, ignoreCase: true); @@ -308,6 +338,9 @@ private static string GetListName(IElement listNode, string? parentName = null) return new ParagraphStyleId { Val = styleId }; } + if (listParagraphStyleId != null) + return (ParagraphStyleId) listParagraphStyleId.Clone(); + if (!defaultIfEmpty) return null; return documentStyle.GetParagraphStyle(documentStyle.DefaultStyles.ListParagraphStyle); } @@ -320,30 +353,10 @@ private static bool IsCascadingStyle(string styleName) return styleName == "decimal-tiered"; } - protected override void ComposeStyles(ParsingContext context) - { - base.ComposeStyles(context); - var margin = styleAttributes.GetMargin(); - if (!margin.IsEmpty && margin.Left.IsFixed && margin.Left.Value > 0) - leftIndentation = margin.Left.ValueInDxa; - } - - /// - /// Align non-numbered paragraphs with the listnode (level + list margin + li margin). - /// - private static void SetListItemElementParagraphIndentationLeft(ParagraphProperties pPr, int level, long listMarginLeftDxa) - { - long levelLeftDxa = level * Indentation * 2; - long liExtraDxa = ParseIndentationLeft(pPr); // parsed paragraph left indentation (if any) - long total = levelLeftDxa + listMarginLeftDxa + liExtraDxa; - - pPr.Indentation ??= new Indentation(); - pPr.Indentation.Left = total.ToString(CultureInfo.InvariantCulture); - } - private static long ParseIndentationLeft(ParagraphProperties? pPr) { - if (pPr?.Indentation?.Left?.Value is { } left && long.TryParse(left, NumberStyles.Integer, CultureInfo.InvariantCulture, out var dxa)) + if (pPr?.Indentation?.Left?.Value is { } left + && long.TryParse(left, NumberStyles.Integer, CultureInfo.InvariantCulture, out var dxa)) return dxa; return 0; } diff --git a/src/Html2OpenXml/Expressions/Numbering/NumberingExpressionBase.cs b/src/Html2OpenXml/Expressions/Numbering/NumberingExpressionBase.cs index 74944b28..ea5912fe 100644 --- a/src/Html2OpenXml/Expressions/Numbering/NumberingExpressionBase.cs +++ b/src/Html2OpenXml/Expressions/Numbering/NumberingExpressionBase.cs @@ -25,7 +25,9 @@ abstract class NumberingExpressionBase(IHtmlElement node) : BlockElementExpressi { /// Hard-coded value from Word public const int MaxLevel = 8; - protected const int Indentation = 360; + internal const int LevelIndent = 720; + internal const int Hanging = 360; + internal const string HangingStr = "360"; public const string HeadingNumberingName = "decimal-heading-multi"; private static readonly IReadOnlyDictionary predefinedNumberingLists = InitKnownLists(); /// Contains the list of templated list along with the AbstractNumbId @@ -49,22 +51,15 @@ protected int GetOrCreateListTemplate(ParsingContext context, string listName) } Numbering numberingPart = context.MainPart.NumberingDefinitionsPart!.Numbering!; - AbstractNum abstractNum; // at this stage, we have sanitized the list style so it's safe to grab them from the predefined template lists - if (predefinedNumberingLists.TryGetValue(listName, out var predefined)) - { + abstractNum = predefinedNumberingLists.TryGetValue(listName, out var predefined)? // If it's a predefined style, we clone it as usual - abstractNum = (AbstractNum)predefined.CloneNode(true); - } - else - { + (AbstractNum)predefined.CloneNode(true) : // If not found in predefined lists, listName contains a custom bullet character (e.g., "-") - abstractNum = CreateCustomBulletAbstractNum(listName); - } - - abstractNum = (AbstractNum) abstractNum.CloneNode(true); + CreateCustomBulletAbstractNum(listName); + abstractNum.AbstractNumberId = IncrementAbstractNumId(context, numberingPart); var level1 = abstractNum.GetFirstChild()!; @@ -180,14 +175,18 @@ protected int IncrementInstanceId(ParsingContext context, int abstractNumId, boo } /// - /// Discover the list of existing templates and instances, already registred in the document. + /// Discover the list of existing templates and instances, already registered in the document. /// private void InitNumberingIds(ParsingContext context) { if (isInitialized) return; knownAbsNumIds = context.Properties>("knownAbsNumIds"); knownInstanceIds = context.Properties>("knownInstanceIds"); - if (knownAbsNumIds != null && knownInstanceIds != null) return; + if (knownAbsNumIds != null && knownInstanceIds != null) + { + isInitialized = true; + return; + } knownAbsNumIds = []; knownInstanceIds = []; @@ -239,8 +238,8 @@ private static AbstractNum CreateCustomBulletAbstractNum(string customSymbol) LevelJustification = new() { Val = LevelJustificationValues.Left }, PreviousParagraphProperties = new() { Indentation = new() { - Left = ((lvlIndex + 1) * Indentation * 2).ToString(), - Hanging = Indentation.ToString() + Left = ((lvlIndex + 1) * LevelIndent).ToString(), + Hanging = HangingStr } } }); @@ -288,8 +287,8 @@ private static IReadOnlyDictionary InitKnownLists() LevelJustification = new() { Val = LevelJustificationValues.Left }, PreviousParagraphProperties = new() { Indentation = new() { - Left = ((lvlIndex + 1) * Indentation * 2).ToString(), - Hanging = Indentation.ToString() + Left = ((lvlIndex + 1) * LevelIndent).ToString(), + Hanging = HangingStr } }, NumberingSymbolRunProperties = useSymbol? new () { @@ -320,7 +319,7 @@ private static IReadOnlyDictionary InitKnownLists() LevelIndex = lvlIndex, LevelText = new() { Val = lvlText.ToString() }, PreviousParagraphProperties = new() { - Indentation = new() { Left = "0", Hanging = Indentation.ToString() } + Indentation = new() { Left = "0", Hanging = HangingStr } } }); } diff --git a/src/Html2OpenXml/Utilities/AngleSharpExtensions.cs b/src/Html2OpenXml/Utilities/AngleSharpExtensions.cs index 05ed18b4..711eb959 100644 --- a/src/Html2OpenXml/Utilities/AngleSharpExtensions.cs +++ b/src/Html2OpenXml/Utilities/AngleSharpExtensions.cs @@ -52,7 +52,7 @@ public static bool IsTopAnchor(this IHtmlAnchorElement element) /// /// Gets whether the given child is preceded by any list element (ol or ul). /// - public static bool IsPrecededByListElement(this INode child, out IElement? precedingElement) + public static bool IsPrecededByListElement(this INode child, [NotNullWhen(true)] out IElement? precedingElement) { precedingElement = null; diff --git a/test/HtmlToOpenXml.Tests/NumberingTests.cs b/test/HtmlToOpenXml.Tests/NumberingTests.cs index 75ab3a29..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 { @@ -389,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() { @@ -566,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}"); } } @@ -617,7 +641,7 @@ public void NestedParagraph_ReturnsIndentedItems() var elements = converter.Parse(@"
    • Paragraph text

      -

      Paragraph text

      +

      Paragraph text bis

    "); @@ -637,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"); } } @@ -665,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); @@ -673,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
      " @@ -690,41 +715,17 @@ 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() { @@ -757,9 +758,6 @@ public async Task CustomBulletList_ReturnsListWithCustomStyle() 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() { @@ -780,68 +778,71 @@ 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() - { - 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"); - } - [Test] public async Task ListContainer_Styling_CascadeToListItems() { @@ -862,25 +863,6 @@ public async Task ListContainer_Styling_CascadeToListItems() } } - private static string? GetListInstanceLevelIndentLeft(Numbering numbering, int numId, int ilvl = 0) - { - return GetListInstanceLevelOverride(numbering, numId, ilvl)?.PreviousParagraphProperties?.Indentation?.Left?.Value; - } - - 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()) - { - foreach (var level in levelOverride.Elements()) - { - if (level.LevelIndex?.Value == ilvl) - return level; - } - } - return null; - } - /// /// A nested ul type attribute must use its own bullet, not the parent marker /// @@ -917,31 +899,35 @@ public async Task UnorderedList_CssListStyleType_OverridesTypeAttribute() AssertThatOpenXmlDocumentIsValid(); } - [Test(Description = "Nested ordered list start value is reflected in the marker value")] - public async Task NestedOrderedList_StartValue_IsAddedToMarkerValue() - { - await converter.ParseBody(@"
          1. One
            1. Ten
          "); - - var paragraphs = mainPart.Document!.Body!.Elements().ToList(); - Assert.That(GetListMarkerNumberingValue(paragraphs.Last()), Is.EqualTo("10")); - AssertThatOpenXmlDocumentIsValid(); - } - [Test(Description = "Paragraph margin-left inside a list item must be applied independently of the list item indentation")] - public async Task ListItemWithMultipleParagraphs_AppliesIndependentParagraphIndentation() + public async Task ListContainerAndParagraphs_AppliesExtraMargin() { - await converter.ParseBody(@"
          1. First

            Last

          "); - var paragraphs = mainPart.Document?.Body!.Elements().ToList(); - var firstParagraph = paragraphs?.First(); - var lastParagraph = paragraphs?.Last(); + 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"); - var firstParaIndent = firstParagraph?.ParagraphProperties?.Indentation?.Left?.Value; - var lastParaIndent = lastParagraph?.ParagraphProperties?.Indentation?.Left?.Value; + using (Assert.EnterMultipleScope()) + { + var indentation0 = elements[0].GetFirstChild()?.Indentation!; + var indentation1 = elements[1].GetFirstChild()?.Indentation!; - Assert.That(firstParaIndent, Is.Null, "The first paragraph should not have direct indentation because indentation is assigned through the list levelOverride instance."); - Assert.That(lastParaIndent, Is.Not.Null); - // i.e. level indentation + paragraph indentation + list left indentation = 720+360+360 = 1440 - Assert.That(lastParaIndent, Is.EqualTo("1440"), "The last paragraph must have its own additional indentation from its margin-left. qith value equal to 360 dxa"); + 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) @@ -954,15 +940,5 @@ public async Task ListItemWithMultipleParagraphs_AppliesIndependentParagraphInde 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? GetListMarkerNumberingValue(Paragraph paragraph) - { - var numberingProperties = paragraph.ParagraphProperties?.NumberingProperties; - var numId = numberingProperties?.NumberingId?.Val?.Value; - var level = numberingProperties?.NumberingLevelReference?.Val?.Value; - var numbering = mainPart.NumberingDefinitionsPart!.Numbering!; - var instance = numbering.Elements().Single(i => i.NumberID?.Value == numId); - return instance.GetFirstChild()?.GetFirstChild()?.Val; - } } } diff --git a/test/HtmlToOpenXml.Tests/TableTests.cs b/test/HtmlToOpenXml.Tests/TableTests.cs index 92366e63..292c8a5c 100644 --- a/test/HtmlToOpenXml.Tests/TableTests.cs +++ b/test/HtmlToOpenXml.Tests/TableTests.cs @@ -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(@$"
  • From 33811e1ca8ef27b3cdacd90632f5e04718ed01d6 Mon Sep 17 00:00:00 2001 From: Olivier Nizet Date: Fri, 13 Nov 2026 18:49:51 +0100 Subject: [PATCH 16/18] Css inliner --- Directory.Build.props | 4 - Directory.Packages.props | 39 +++ HtmlToOpenXml.slnx | 2 + docs/guide/api.md | 38 +++ docs/guide/styling.md | 40 ++- examples/Demo/Demo.csproj | 2 +- .../CssProcessingMode.cs | 30 +++ .../CssStyleHtmlConverter.cs | 167 ++++++++++++ .../HtmlToOpenXml.CssInliner.csproj | 50 ++++ .../WebRequestRequester.cs | 49 ++++ src/Html2OpenXml/HtmlConverter.cs | 252 +++++++++++++----- src/Html2OpenXml/HtmlToOpenXml.csproj | 22 +- src/Html2OpenXml/Utilities/HtmlEntities.cs | 5 +- .../HtmlToOpenXml.CssInliner.Tests.csproj | 33 +++ .../InlineCssTests.cs | 87 ++++++ .../StylesheetTests.cs | 92 +++++++ .../HtmlConverterTestBase.cs | 2 +- .../HtmlToOpenXml.Tests.csproj | 13 +- test/HtmlToOpenXml.Tests/ImgTests.cs | 13 + 19 files changed, 843 insertions(+), 97 deletions(-) create mode 100644 Directory.Packages.props create mode 100644 src/Html2OpenXml.CssInliner/CssProcessingMode.cs create mode 100644 src/Html2OpenXml.CssInliner/CssStyleHtmlConverter.cs create mode 100644 src/Html2OpenXml.CssInliner/HtmlToOpenXml.CssInliner.csproj create mode 100644 src/Html2OpenXml.CssInliner/WebRequestRequester.cs create mode 100644 test/HtmlToOpenXml.CssInliner.Tests/HtmlToOpenXml.CssInliner.Tests.csproj create mode 100644 test/HtmlToOpenXml.CssInliner.Tests/InlineCssTests.cs create mode 100644 test/HtmlToOpenXml.CssInliner.Tests/StylesheetTests.cs diff --git a/Directory.Build.props b/Directory.Build.props index be7f02c7..77e8e3a6 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -7,10 +7,6 @@ 4.2.0 - - 3.5.1 - - $(PackageVersion) 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 0fd1647a..4ec92b3c 100644 --- a/HtmlToOpenXml.slnx +++ b/HtmlToOpenXml.slnx @@ -1,9 +1,11 @@ + + 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/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/HtmlConverterTestBase.cs b/test/HtmlToOpenXml.Tests/HtmlConverterTestBase.cs index 7c9c361b..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 @@ -21,6 +20,7 @@ public void Init () generatedDocument = new MemoryStream(); package = WordDocumentFactory.Create(generatedDocument); mainPart = package.MainDocumentPart!; + Assume.That(mainPart, Is.Not.Null); this.converter = new HtmlConverter(package); } 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 e07d4303..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() { From 533d2744b11d654f9c2fc465f3424259cff40b97 Mon Sep 17 00:00:00 2001 From: Olivier Nizet Date: Fri, 13 Nov 2026 22:17:03 +0100 Subject: [PATCH 17/18] Serious code review: - materialize enumerable to avoid lazy-iteration running twice - heading and hyperlink are more defensive - fix logic on some rare cases - optimisation - improve comment on code - fix typo --- .../OpenXmlDocumentStyleCollection.cs | 3 +- .../Collections/RowSpanCollection.cs | 11 ++- .../Expressions/BlockElementExpression.cs | 42 +++++------ .../Expressions/BlockQuoteExpression.cs | 8 +-- .../Expressions/BodyExpression.cs | 19 ++--- .../Expressions/FigureCaptionExpression.cs | 32 ++++----- .../Expressions/HorizontalLineExpression.cs | 20 +++--- .../Expressions/HtmlDomExpression.cs | 7 +- .../Expressions/HyperlinkExpression.cs | 22 +++--- .../Expressions/Image/ImageExpression.cs | 2 +- .../Expressions/Image/ImageExpressionBase.cs | 10 +-- .../Numbering/HeadingElementExpression.cs | 70 ++++++++++++++----- .../Expressions/Numbering/ListExpression.cs | 2 +- .../Expressions/PhrasingElementExpression.cs | 17 ++--- .../Expressions/QuoteElementExpression.cs | 5 +- .../Table/TableCaptionExpression.cs | 15 ++-- .../Expressions/Table/TableColExpression.cs | 15 ++-- .../Table/TableElementExpressionBase.cs | 8 +-- .../Expressions/Table/TableExpression.cs | 13 ++-- .../Expressions/Table/TablePartExpression.cs | 1 - .../Expressions/Table/TableRowExpression.cs | 23 +++--- src/Html2OpenXml/Primitives/Size.cs | 6 ++ src/Html2OpenXml/Primitives/Unit.cs | 31 +++----- .../Utilities/AngleSharpExtensions.cs | 14 +++- test/HtmlToOpenXml.Tests/HeadingTests.cs | 31 +++++--- test/HtmlToOpenXml.Tests/LinkTests.cs | 7 ++ test/HtmlToOpenXml.Tests/TableTests.cs | 10 +-- 27 files changed, 250 insertions(+), 194 deletions(-) diff --git a/src/Html2OpenXml/Collections/OpenXmlDocumentStyleCollection.cs b/src/Html2OpenXml/Collections/OpenXmlDocumentStyleCollection.cs index c7e81e8e..6a8aa777 100755 --- a/src/Html2OpenXml/Collections/OpenXmlDocumentStyleCollection.cs +++ b/src/Html2OpenXml/Collections/OpenXmlDocumentStyleCollection.cs @@ -49,7 +49,8 @@ public bool TryGetValueIgnoreCase(string name, StyleValues styleType, out Style? style = this.Values[mid]; Style firstFoundStyle = style; - // we have found the named style but maybe the style doesn't match (Paragraph is not Character) + // Multiple styles may share a name but differ by type (Paragraph, Character, Table). + // Scan adjacent entries with the same name to find the requested type for (int i = mid; i < keys.Count && !styleType.Equals(style.Type!); i++) { style = this.Values[i]; diff --git a/src/Html2OpenXml/Collections/RowSpanCollection.cs b/src/Html2OpenXml/Collections/RowSpanCollection.cs index fd1f4199..a5b60b14 100644 --- a/src/Html2OpenXml/Collections/RowSpanCollection.cs +++ b/src/Html2OpenXml/Collections/RowSpanCollection.cs @@ -21,7 +21,7 @@ sealed class RowSpanCollection : IEnumerableHold the remaining row span value per colum index + /// Hold the remaining row span value per column index private readonly SortedDictionary spans = []; /// @@ -39,7 +39,7 @@ public void Add(int index, int rowSpan, int columnSpan = 1) } /// - /// Carry on the rown span on the next row. + /// Carry the rown span to the next row. /// public int Decrement(int columnIndex) { @@ -54,7 +54,7 @@ public int Decrement(int columnIndex) /// /// Reconciliate the carried row span from previous rows with the current spans. /// - public void UnionWith(IEnumerable> other) + public void CarryForward(IEnumerable> other) { foreach (var span in other) spans.Add(span.Key, span.Value); @@ -73,8 +73,5 @@ IEnumerator IEnumerable.GetEnumerator() /// /// Iterate through the column indexes of carried row span. /// - public IEnumerable Columns - { - get => spans.Keys; - } + public IReadOnlyCollection Columns => spans.Keys; } \ No newline at end of file diff --git a/src/Html2OpenXml/Expressions/BlockElementExpression.cs b/src/Html2OpenXml/Expressions/BlockElementExpression.cs index fc9558ee..b8364feb 100644 --- a/src/Html2OpenXml/Expressions/BlockElementExpression.cs +++ b/src/Html2OpenXml/Expressions/BlockElementExpression.cs @@ -28,7 +28,7 @@ class BlockElementExpression: PhrasingElementExpression protected readonly ParagraphProperties paraProperties = new(); protected TableProperties? tableProperties; // some style attributes, such as borders or bgcolor, will convert this node to a framed container - protected bool renderAsFramed; + protected bool mustRenderAsFrame; private HtmlBorder styleBorder; @@ -58,16 +58,16 @@ public override IEnumerable Interpret (ParsingContext context) p.AppendChild(new BookmarkEnd() { Id = bookmarkId }); } - if (!renderAsFramed) + if (!mustRenderAsFrame) return childElements; - var paragraphs = childElements.OfType(); - if (!paragraphs.Any()) return childElements; + var paragraphs = childElements.OfType().ToList(); + if (paragraphs.Count == 0) return childElements; // if we have only 1 paragraph, just inline the styles - if (paragraphs.Count() == 1) + if (paragraphs.Count == 1) { - var p = paragraphs.First(); + var p = paragraphs[0]; if (!styleBorder.IsEmpty && p.ParagraphProperties?.ParagraphBorders is null) { @@ -92,7 +92,7 @@ protected override IEnumerable Interpret ( { return ComposeChildren(context, childNodes, paraProperties, prefixRuns: CreatePageBreakBeforeRuns(), - suffiRuns: CreatePageBreakAfterRuns()); + suffixRuns: CreatePageBreakAfterRuns()); } public override void CascadeStyles(OpenXmlElement element) @@ -125,14 +125,15 @@ public override void CascadeStyles(OpenXmlElement element) return; var knownTags = new HashSet(); - foreach (var prop in props.Where(p => !knownTags.Contains(p.LocalName))) + foreach (var prop in props) { knownTags.Add(prop.LocalName); } - foreach (var prop in tableProperties.Where(p => !knownTags.Contains(p.LocalName))) + foreach (var prop in tableProperties) { - props.AddChild(prop.CloneNode(true)); + if (!knownTags.Contains(prop.LocalName)) + props.AddChild(prop.CloneNode(true)); } } } @@ -163,7 +164,7 @@ protected override void ComposeStyles (ParsingContext context) } } - // according to w3c, dir should be used in conjonction with lang. But whatever happens, we'll apply the RTL layout + // according to w3c, dir should be used in conjunction with lang. But whatever happens, we'll apply the RTL layout var dir = node.GetTextDirection(); if (dir.HasValue) { paraProperties.BiDi = new() { @@ -184,7 +185,7 @@ protected override void ComposeStyles (ParsingContext context) styleBorder = styleAttributes.GetBorders(); if (!styleBorder.IsEmpty) { - renderAsFramed = true; + mustRenderAsFrame = true; runProperties.Border = null; } @@ -277,22 +278,22 @@ protected override void ComposeStyles (ParsingContext context) } if (runProperties.Shading != null) - renderAsFramed = true; + mustRenderAsFrame = true; } /// - /// Intrepret all the child nodes and combine them. + /// Interpret all the child nodes and combine them. /// /// The child parsing context. /// The list of child nodes. /// The parent paragraph properties to apply. /// Prepend runs at the beginning of the processing (optional). - /// Append runs at the end of the processing (optional). + /// Append runs at the end of the processing (optional). internal static IEnumerable ComposeChildren(ParsingContext context, IEnumerable childNodes, ParagraphProperties paragraphProperties, IEnumerable? prefixRuns = null, - IEnumerable? suffiRuns = null) + IEnumerable? suffixRuns = null) { var runs = new List(); var flowElements = new List(); @@ -314,10 +315,9 @@ internal static IEnumerable ComposeChildren(ParsingContext conte runs.Add(element); continue; } - // if 2 tables are consecutives, we insert a paragraph in between - // or Word will merge the two tables else if (element is Table && previousElement is Table) { + // Word merges adjacent tables if no pargraph separates them flowElements.Add(new Paragraph()); } @@ -332,8 +332,8 @@ internal static IEnumerable ComposeChildren(ParsingContext conte } } - if (suffiRuns != null) - runs.AddRange(suffiRuns); + if (suffixRuns != null) + runs.AddRange(suffixRuns); if (runs.Count > 0) flowElements.Add(CreateParagraph(context, runs, paragraphProperties)); @@ -344,7 +344,7 @@ internal static IEnumerable ComposeChildren(ParsingContext conte /// /// Create a new Paragraph and combine all the runs. /// - private static Paragraph CreateParagraph(ParsingContext context, IList runs, ParagraphProperties paraProperties) + private static Paragraph CreateParagraph(ParsingContext context, List runs, ParagraphProperties paraProperties) { Paragraph p = new(); if (paraProperties.HasChildren) diff --git a/src/Html2OpenXml/Expressions/BlockQuoteExpression.cs b/src/Html2OpenXml/Expressions/BlockQuoteExpression.cs index adeb706d..a2f21501 100644 --- a/src/Html2OpenXml/Expressions/BlockQuoteExpression.cs +++ b/src/Html2OpenXml/Expressions/BlockQuoteExpression.cs @@ -25,16 +25,16 @@ sealed class BlockQuoteExpression(IHtmlElement node) : BlockElementExpression(no /// public override IEnumerable Interpret(ParsingContext context) { - var childElements = base.Interpret(context); - if (!childElements.Any()) + var childElements = base.Interpret(context).ToList(); + if (childElements.Count == 0) return []; - + // Footnote or endnote are invalid inside header and footer if (context.HostingPart is not MainDocumentPart) return childElements; // Transform the inline acronym/abbreviation to a reference to a foot note. - if (childElements.First() is Paragraph paragraph) + if (childElements[0] is Paragraph paragraph) { string? description = node.GetAttribute("cite"); diff --git a/src/Html2OpenXml/Expressions/BodyExpression.cs b/src/Html2OpenXml/Expressions/BodyExpression.cs index 597cccf6..e40a31c6 100644 --- a/src/Html2OpenXml/Expressions/BodyExpression.cs +++ b/src/Html2OpenXml/Expressions/BodyExpression.cs @@ -29,7 +29,7 @@ sealed class BodyExpression(IHtmlElement node, ParagraphStyleId? defaultStyle) public override IEnumerable Interpret(ParsingContext context) { - MarkAllBookmarks(); + MarBookmarkTargets(); var body = context.MainPart.Document!.Body!; var sectionProperties = body.Descendants().LastOrDefault(); @@ -38,9 +38,9 @@ public override IEnumerable Interpret(ParsingContext context) context.IsLandscape = WordDocumentFactory.IsLandscape(sectionProperties.GetFirstChild()); } - var elements = base.Interpret(context); + var elements = base.Interpret(context).ToList(); - if (shouldRegisterTopBookmark && elements.Any()) + if (shouldRegisterTopBookmark && elements.Count > 0) { // Check whether it already exists if (body.Descendants().Any(b => b.Name?.Value == "_top")) @@ -94,17 +94,20 @@ protected override void ComposeStyles(ParsingContext context) var sectionProperties = mainPart.Document!.Body!.GetFirstChild(); if (sectionProperties == null || sectionProperties.GetFirstChild() == null) { - mainPart.Document.Body.Append(sectionProperties = new()); + mainPart.Document.Body.Append(sectionProperties = new()); } - sectionProperties.AddChild(paraProperties.BiDi.CloneNode(true)); + if (!sectionProperties.HasChild()) + { + sectionProperties.AddChild(paraProperties.BiDi.CloneNode(true)); + } } } /// - /// Detect all bookmarks (in-document) and mark the nodes for future processing. + /// Detect all bookmarks (in-document) and modify the DOM to mark the nodes for future processing. /// - private void MarkAllBookmarks() + private void MarBookmarkTargets() { var links = node.QuerySelectorAll("a[href^='#']"); if (links.Length == 0) return; @@ -114,7 +117,7 @@ private void MarkAllBookmarks() if (link.IsTopAnchor()) { shouldRegisterTopBookmark = true; - return; + continue; } var id = link.Hash.Substring(1); diff --git a/src/Html2OpenXml/Expressions/FigureCaptionExpression.cs b/src/Html2OpenXml/Expressions/FigureCaptionExpression.cs index c5770716..d188c2cd 100644 --- a/src/Html2OpenXml/Expressions/FigureCaptionExpression.cs +++ b/src/Html2OpenXml/Expressions/FigureCaptionExpression.cs @@ -26,7 +26,7 @@ sealed class FigureCaptionExpression(IHtmlElement node) : BlockElementExpression public override IEnumerable Interpret (ParsingContext context) { ComposeStyles(context); - var childElements = Interpret(context.CreateChild(this), node.ChildNodes); + var childElements = Interpret(context.CreateChild(this), node.ChildNodes).ToList(); var figNumRef = new List() { new Run( @@ -39,7 +39,7 @@ public override IEnumerable Interpret (ParsingContext context) }; - if (!childElements.Any()) + if (childElements.Count == 0) { return [new Paragraph(figNumRef) { ParagraphProperties = new ParagraphProperties { @@ -49,27 +49,28 @@ public override IEnumerable Interpret (ParsingContext context) }]; } - //Add the figure number references to the start of the first paragraph. - if(childElements.First() is Paragraph p) + // Add the figure number references to the start of the first paragraph. + if(childElements[0] is Paragraph p) { - var properties = p.GetFirstChild(); - p.InsertAfter(new Run( - new Text(" ") { Space = SpaceProcessingModeValues.Preserve } - ), properties); - p.InsertAfter(figNumRef[1], properties); - p.InsertAfter(figNumRef[0], properties); + var properties = p.GetFirstChild(); + p.InsertAfter(new Run( + new Text(" ") { Space = SpaceProcessingModeValues.Preserve } + ), properties); + p.InsertAfter(figNumRef[1], properties); + p.InsertAfter(figNumRef[0], properties); } else { // The first child of the figure caption is a table or something. // Just prepend a new paragraph with the figure number reference. - childElements = [ + childElements = [ new Paragraph(figNumRef), ..childElements ]; } - foreach (var paragraph in childElements.OfType()) + var paragraphs = childElements.OfType().ToList(); + foreach (var paragraph in paragraphs) { paragraph.ParagraphProperties ??= new ParagraphProperties(); paragraph.ParagraphProperties.ParagraphStyleId ??= context.DocumentStyle.GetParagraphStyle(context.DocumentStyle.DefaultStyles.CaptionStyle); @@ -77,10 +78,7 @@ public override IEnumerable Interpret (ParsingContext context) paragraph.ParagraphProperties.KeepNext = new KeepNext(); } - if(childElements.OfType().LastOrDefault() is Paragraph lastPara) - { - lastPara.ParagraphProperties!.KeepNext = DetermineKeepNext(node); - } + paragraphs[^1].ParagraphProperties!.KeepNext = DetermineKeepNext(node); return childElements; } @@ -108,7 +106,7 @@ private static int AddFigureCaption(ParsingContext context) } /// - /// Determines whether the KeepNext property should apply this this caption. + /// Determines whether the KeepNext property should apply to this caption. /// /// A new or null. private static KeepNext? DetermineKeepNext(IHtmlElement node) diff --git a/src/Html2OpenXml/Expressions/HorizontalLineExpression.cs b/src/Html2OpenXml/Expressions/HorizontalLineExpression.cs index 88e8513a..a9e955cb 100644 --- a/src/Html2OpenXml/Expressions/HorizontalLineExpression.cs +++ b/src/Html2OpenXml/Expressions/HorizontalLineExpression.cs @@ -21,12 +21,14 @@ namespace HtmlToOpenXml.Expressions; /// sealed class HorizontalLineExpression(IHtmlElement node) : HtmlDomExpression { + const string BorderSpacingTwips = "240"; + /// public override IEnumerable Interpret (ParsingContext context) { var paragraph = new Paragraph(); HtmlAttributeCollection styleAttributes; - HtmlBorder border; + HtmlBorder border = HtmlBorder.Empty; var previousElement = node.PreviousElementSibling; if (previousElement != null) @@ -44,31 +46,33 @@ public override IEnumerable Interpret (ParsingContext context) if (shouldAddSpacing) { - paragraph.ParagraphProperties = new ParagraphProperties { - SpacingBetweenLines = new() { Before = "240" } + paragraph.ParagraphProperties = new ParagraphProperties { + SpacingBetweenLines = new() { Before = BorderSpacingTwips } }; } } - // as this paragraph has no children, it will be deleted in RemoveEmptyParagraphs() - // in order to kept the
    , we force an empty run + // as this paragraph has no children, we force an empty run paragraph.Append(new Run()); styleAttributes = node.GetStyles(); - border = new HtmlBorder(); if (!styleAttributes.IsEmpty) border = styleAttributes.GetBorders(); // Get style from border (only top) or use Default style - TopBorder? hrBorderStyle; + TopBorder hrBorderStyle; if (!border.IsEmpty && border.Top.IsValid) + { hrBorderStyle = new TopBorder { - Val = border.Top.Style, + Val = border.Top.Style, Color = StringValue.FromString(border.Top.Color.ToHexString()), Size = (uint)border.Top.Width.ValueInPoint }; + } else + { hrBorderStyle = new TopBorder() { Val = BorderValues.Single, Size = 4U }; + } paragraph.ParagraphProperties ??= new(); paragraph.ParagraphProperties.ParagraphBorders = new ParagraphBorders { diff --git a/src/Html2OpenXml/Expressions/HtmlDomExpression.cs b/src/Html2OpenXml/Expressions/HtmlDomExpression.cs index 1bd42748..4f44063e 100644 --- a/src/Html2OpenXml/Expressions/HtmlDomExpression.cs +++ b/src/Html2OpenXml/Expressions/HtmlDomExpression.cs @@ -22,11 +22,11 @@ namespace HtmlToOpenXml.Expressions; abstract class HtmlDomExpression { static readonly Dictionary> knownTags = InitKnownTags(); - static readonly HashSet ignoreTags = new(StringComparer.OrdinalIgnoreCase) { + static readonly HashSet ignoreTags = [with(StringComparer.OrdinalIgnoreCase), TagNames.Xml, TagNames.AnnotationXml, TagNames.Button, TagNames.Progress, TagNames.Select, TagNames.Input, TagNames.Textarea, TagNames.Meter, TagNames.Applet, TagNames.Style, TagNames.NoFrames, TagNames.NoEmbed, TagNames.NoScript, - TagNames.Script, TagNames.Bgsound, TagNames.Menu, TagNames.MenuItem, }; + TagNames.Script, TagNames.Bgsound, TagNames.Menu, TagNames.MenuItem]; private static Dictionary> InitKnownTags() { @@ -101,7 +101,8 @@ private static Dictionary> InitKnownTa { return new TextExpression(node); } - else if (node.NodeType == NodeType.Element + + if (node.NodeType == NodeType.Element && !ignoreTags.Contains(node.NodeName)) { if (knownTags.TryGetValue(node.NodeName, out Func? handler)) diff --git a/src/Html2OpenXml/Expressions/HyperlinkExpression.cs b/src/Html2OpenXml/Expressions/HyperlinkExpression.cs index fe9750f3..b368bc5c 100644 --- a/src/Html2OpenXml/Expressions/HyperlinkExpression.cs +++ b/src/Html2OpenXml/Expressions/HyperlinkExpression.cs @@ -30,8 +30,11 @@ sealed class HyperlinkExpression(IHtmlAnchorElement node) : PhrasingElementExpre /// public override IEnumerable Interpret (ParsingContext context) { + var childElements = Interpret(context.CreateChild(this), linkNode.ChildNodes).ToList(); + if (childElements.Count == 0) + return []; + var h = CreateHyperlink(context); - var childElements = Interpret(context.CreateChild(this), linkNode.ChildNodes); if (h is null) { return childElements; @@ -40,10 +43,9 @@ public override IEnumerable Interpret (ParsingContext context) // Let's see whether the link tag include an image inside its body. // If so, the Hyperlink OpenXmlElement is lost and we'll keep only the images // and applied a HyperlinkOnClick attribute. - IEnumerable imagesInLink; + var imagesInLink = childElements.Where(e => e.HasChild()).ToList(); // Clickable image is only supported in body but not in header/footer - if (context.HostingPart is MainDocumentPart && - (imagesInLink = childElements.Where(e => e.HasChild())).Any()) + if (context.HostingPart is MainDocumentPart && imagesInLink.Count > 0) { foreach (var img in imagesInLink) { @@ -51,15 +53,13 @@ public override IEnumerable Interpret (ParsingContext context) Drawing? d = img.GetFirstChild(); if (d == null) continue; - var enDp = d.Descendants().GetEnumerator(); - string? alt; - if (enDp.MoveNext()) alt = enDp.Current.Description; - else alt = null; + string? alt = d.Descendants() + .FirstOrDefault()?.Description; d.Inline ??= new a.Wordprocessing.Inline(); d.Inline.DocProperties ??= new a.Wordprocessing.DocProperties(); - if (h.Anchor == "_top") + if (AngleSharpExtensions.IsTopAnchor(h.Anchor)) { // exception case: clickable image requires the _top bookmark get registred with a relationship var extLink = context.HostingPart.AddHyperlinkRelationship(new Uri("#_top", UriKind.Relative), false); @@ -79,13 +79,15 @@ public override IEnumerable Interpret (ParsingContext context) foreach (var el in childElements) { if (el is Run r) runs.Add(r); - // unroll paragraphs. CloneNode is need to unparent the run + // unroll paragraphs. CloneNode is needed to unparent the run else runs.AddRange(el.Elements().Select(r => (Run) r.CloneNode(true))); } foreach (var run in runs.Where(run => !run.HasChild())) { run.RunProperties ??= new(); + + // always override the style run.RunProperties.RunStyle = context.DocumentStyle.GetRunStyle( context.DocumentStyle.DefaultStyles.HyperlinkStyle); } diff --git a/src/Html2OpenXml/Expressions/Image/ImageExpression.cs b/src/Html2OpenXml/Expressions/Image/ImageExpression.cs index 66378057..4cbb1efb 100644 --- a/src/Html2OpenXml/Expressions/Image/ImageExpression.cs +++ b/src/Html2OpenXml/Expressions/Image/ImageExpression.cs @@ -89,7 +89,7 @@ class ImageExpression(IHtmlImageElement node) : ImageExpressionBase(node) { preferredSize = iinfo.Size; } - else if (preferredSize.Width <= 0 || preferredSize.Height <= 0) + else if (preferredSize.HasInvalidDimension) { Size actualSize = iinfo.Size; // Image perspective skewed. Bug fixed by ddeforge on github.com/onizet/html2openxml/discussions/350500 diff --git a/src/Html2OpenXml/Expressions/Image/ImageExpressionBase.cs b/src/Html2OpenXml/Expressions/Image/ImageExpressionBase.cs index e4f14f44..31422941 100644 --- a/src/Html2OpenXml/Expressions/Image/ImageExpressionBase.cs +++ b/src/Html2OpenXml/Expressions/Image/ImageExpressionBase.cs @@ -28,7 +28,7 @@ abstract class ImageExpressionBase(AngleSharp.Dom.IElement node) : HtmlDomExpre private readonly RunProperties runProperties = new(); private readonly ParagraphProperties paraProperties = new(); // some style attributes, such as borders, will convert this node to a framed container - private bool renderAsFramed; + private bool mustRenderAsFrame; /// @@ -45,7 +45,7 @@ public override IEnumerable Interpret (ParsingContext context) if (runProperties.HasChildren) run.RunProperties = runProperties; - if (renderAsFramed) + if (mustRenderAsFrame) return [new Paragraph(paraProperties, run)]; return [run]; } @@ -86,17 +86,17 @@ private void ComposeStyles () && !AngleSharpExtensions.IsInlineLayout(styleAttributes["display"], "inline-block")) { paraProperties.Justification = new() { Val = JustificationValues.Center }; - renderAsFramed = true; + mustRenderAsFrame = true; } } /// - /// Create the Drawing model referencing the iamge part. + /// Create the Drawing model referencing the image part. /// protected abstract Drawing? CreateDrawing(ParsingContext context); /// - /// Resolve the next available (they must be unique and ordered). + /// Resolve the next available drawing (they must be unique and ordered). /// protected static GraphicObjectIds IncrementDrawingObjId(ParsingContext context) { diff --git a/src/Html2OpenXml/Expressions/Numbering/HeadingElementExpression.cs b/src/Html2OpenXml/Expressions/Numbering/HeadingElementExpression.cs index 452ad1dc..1ae36d5f 100644 --- a/src/Html2OpenXml/Expressions/Numbering/HeadingElementExpression.cs +++ b/src/Html2OpenXml/Expressions/Numbering/HeadingElementExpression.cs @@ -21,7 +21,7 @@ namespace HtmlToOpenXml.Expressions; /// sealed class HeadingElementExpression(IHtmlElement node) : NumberingExpressionBase(node) { - private static readonly Regex numberingRegex = new(@"^\s*(?[0-9\.]+\s*)[^0-9]", + private static readonly Regex numberingRegex = new(@"^\s*(?\d+(?:\.\d+)*\.?\s*)", RegexOptions.Compiled, TimeSpan.FromMilliseconds(100)); /// @@ -29,19 +29,23 @@ public override IEnumerable Interpret (ParsingContext context) { char level = node.NodeName[1]; - var childElements = base.Interpret(context); - if (!childElements.Any()) // no text = skip this heading + var childElements = base.Interpret(context).ToList(); + if (childElements.Count == 0) // no text = skip this heading return childElements; - var paragraph = childElements.FirstOrDefault() as Paragraph; + var paragraph = childElements[0] as Paragraph; + string baseStyle; paragraph ??= new(childElements); paragraph.ParagraphProperties ??= new(); var runElement = childElements.FirstOrDefault(); - if (runElement != null && context.Converter.SupportsHeadingNumbering && IsNumbering(runElement)) + if (runElement != null && context.Converter.SupportsHeadingNumbering && + TryStripHeadingNumbering(runElement)) { - if (string.Equals(context.DocumentStyle.DefaultStyles.HeadingStyle, context.DocumentStyle.DefaultStyles.NumberedHeadingStyle)) + if (string.Equals( + context.DocumentStyle.DefaultStyles.HeadingStyle, + context.DocumentStyle.DefaultStyles.NumberedHeadingStyle)) { // Only apply the numbering if a custom numbered heading style has not been defined. // If the user defined a custom numbered heading style (with numbering), Word has @@ -66,27 +70,29 @@ public override IEnumerable Interpret (ParsingContext context) } // Apply numbered heading style - paragraph.ParagraphProperties.ParagraphStyleId = - context.DocumentStyle.GetParagraphStyle(context.DocumentStyle.DefaultStyles.NumberedHeadingStyle + level); + baseStyle = context.DocumentStyle.DefaultStyles.NumberedHeadingStyle; } else { // Apply normal heading style - paragraph.ParagraphProperties.ParagraphStyleId = - context.DocumentStyle.GetParagraphStyle(context.DocumentStyle.DefaultStyles.HeadingStyle + level); + baseStyle = context.DocumentStyle.DefaultStyles.HeadingStyle; } + // Apply normal heading style + paragraph.ParagraphProperties.ParagraphStyleId = + context.DocumentStyle.GetParagraphStyle(baseStyle + level); + return [paragraph]; } - private static bool IsNumbering(OpenXmlElement runElement) + internal static bool TryStripHeadingNumbering(OpenXmlElement runElement) { - if (runElement.InnerText is null) + var headingText = runElement.InnerText; + if (string.IsNullOrEmpty(headingText)) return false; // Check if the line starts with a number format (1., 1.1., 1.1.1.) // If it does, make sure we make the heading a numbered item - var headingText = runElement.InnerText; Match regexMatch; try { @@ -97,19 +103,45 @@ private static bool IsNumbering(OpenXmlElement runElement) return false; } - // Make sure we only grab the heading if it starts with a number - if (regexMatch.Success && headingText.Length > regexMatch.Groups["number"].Length) + // Strip the numbering only when it is followed by actual heading text. + // Values such as: "1", "1.1" are not considered numbered headings (issue #189) + if (regexMatch.Success && + headingText.Length > regexMatch.Groups["number"].Length) { - // Strip numbers from text - headingText = headingText.Substring(regexMatch.Groups["number"].Length); - runElement.InnerXml = runElement.InnerXml - .Replace(runElement.InnerText!, headingText); + RemoveLeadingCharacters(runElement, regexMatch.Groups["number"].Length); return true; } return false; } + /// + /// Remove characters from the start of a Run. A Run can contain multiple Text nodes, + /// and Run.InnerText is the concatenation of all of them. + /// The numbering prefix may therefore span several Text nodes. + /// + /// The parent Run. + /// The number of characters to remove. + private static void RemoveLeadingCharacters(OpenXmlElement runElement, int count) + { + foreach (var text in runElement.Descendants()) + { + if (count <= 0) + break; + + if (text.Text.Length <= count) + { + count -= text.Text.Length; + text.Text = string.Empty; + } + else + { + text.Text = text.Text.Substring(count); + break; + } + } + } + /// /// Apply numbering to the heading paragraph. /// diff --git a/src/Html2OpenXml/Expressions/Numbering/ListExpression.cs b/src/Html2OpenXml/Expressions/Numbering/ListExpression.cs index 6cb94878..9a0a17db 100644 --- a/src/Html2OpenXml/Expressions/Numbering/ListExpression.cs +++ b/src/Html2OpenXml/Expressions/Numbering/ListExpression.cs @@ -85,7 +85,7 @@ public override IEnumerable Interpret(ParsingContext context) p.ParagraphProperties!.DivId!.Remove(); } - if (renderAsFramed) + if (mustRenderAsFrame) { return [CreateFrame(liParagraphs)]; } diff --git a/src/Html2OpenXml/Expressions/PhrasingElementExpression.cs b/src/Html2OpenXml/Expressions/PhrasingElementExpression.cs index f54a185c..61513a14 100644 --- a/src/Html2OpenXml/Expressions/PhrasingElementExpression.cs +++ b/src/Html2OpenXml/Expressions/PhrasingElementExpression.cs @@ -27,7 +27,7 @@ class PhrasingElementExpression(IHtmlElement node, OpenXmlLeafElement? styleProp protected readonly RunProperties runProperties = new(); protected readonly HtmlAttributeCollection styleAttributes = node.GetStyles(); - protected IHtmlElement node = node; + protected readonly IHtmlElement node = node; /// @@ -66,10 +66,10 @@ public override void CascadeStyles(OpenXmlElement element) var knownTags = new HashSet(); foreach (var prop in run.RunProperties) { - if (!knownTags.Contains(prop.LocalName)) - knownTags.Add(prop.LocalName); + knownTags.Add(prop.LocalName); } + // inherit only properties that are not already defined foreach (var prop in runProperties) { if (!knownTags.Contains(prop.LocalName)) @@ -94,14 +94,15 @@ protected virtual void ComposeStyles (ParsingContext context) } } - // according to w3c, dir should be used in conjonction with lang. But whatever happens, we'll apply the RTL layout + // according to w3c, dir should be used in conjunction with lang. But whatever happens, we'll apply the RTL layout var dir = node.GetTextDirection(); if (dir == DirectionMode.Rtl) { runProperties.RightToLeftText = new RightToLeftText(); } - // OpenXml limits the border to 4-side of the same color and style. + // Use the top border as the representation border since + // OpenXml supports only a single border definition. var borders = styleAttributes.GetBorders(); if (borders.Top.IsValid) { @@ -131,11 +132,11 @@ protected virtual void ComposeStyles (ParsingContext context) if (decorations.HasFlag(TextDecoration.Underline)) runProperties.Underline = new Underline { Val = UnderlineValues.Single }; - if (decorations.HasFlag(TextDecoration.Dotted)) + else if (decorations.HasFlag(TextDecoration.Dotted)) runProperties.Underline = new Underline { Val = UnderlineValues.Dotted }; - if (decorations.HasFlag(TextDecoration.Dashed)) + else if (decorations.HasFlag(TextDecoration.Dashed)) runProperties.Underline = new Underline { Val = UnderlineValues.Dash }; - if (decorations.HasFlag(TextDecoration.Wave)) + else if (decorations.HasFlag(TextDecoration.Wave)) runProperties.Underline = new Underline { Val = UnderlineValues.Wave }; if (decorations.HasFlag(TextDecoration.Double)) runProperties.DoubleStrike = new DoubleStrike(); diff --git a/src/Html2OpenXml/Expressions/QuoteElementExpression.cs b/src/Html2OpenXml/Expressions/QuoteElementExpression.cs index ab5a14eb..e642311e 100644 --- a/src/Html2OpenXml/Expressions/QuoteElementExpression.cs +++ b/src/Html2OpenXml/Expressions/QuoteElementExpression.cs @@ -24,7 +24,7 @@ sealed class QuoteElementExpression(IHtmlElement node) : PhrasingElementExpressi public override IEnumerable Interpret(ParsingContext context) { // The browsers render the quote tag between a kind of separators. - // We add the Quote style to the nested runs to match more Word. + // We apply the Quote character style to better match Word rendering. Run prefixRun = new( new Text(" " + context.DocumentStyle.QuoteCharacters.Prefix) { Space = SpaceProcessingModeValues.Preserve } @@ -33,8 +33,7 @@ public override IEnumerable Interpret(ParsingContext context) prefixRun.RunProperties.RunStyle = context.DocumentStyle.GetRunStyle(context.DocumentStyle.DefaultStyles.QuoteStyle); yield return prefixRun; - var elements = base.Interpret(context); - foreach (var el in elements) + foreach (var el in base.Interpret(context)) yield return el; Run suffixRun = new( diff --git a/src/Html2OpenXml/Expressions/Table/TableCaptionExpression.cs b/src/Html2OpenXml/Expressions/Table/TableCaptionExpression.cs index 4dd3963e..29e5cfe7 100644 --- a/src/Html2OpenXml/Expressions/Table/TableCaptionExpression.cs +++ b/src/Html2OpenXml/Expressions/Table/TableCaptionExpression.cs @@ -9,8 +9,6 @@ * IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A * PARTICULAR PURPOSE. */ -using System.Collections.Generic; -using System.Linq; using AngleSharp.Html.Dom; using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Wordprocessing; @@ -28,8 +26,8 @@ sealed class TableCaptionExpression(Table table, IHtmlElement node) : PhrasingEl public override IEnumerable Interpret (ParsingContext context) { ComposeStyles(context); - var childElements = Interpret(context.CreateChild(this), node.ChildNodes); - if (!childElements.Any()) + var childElements = Interpret(context.CreateChild(this), node.ChildNodes).ToList(); + if (childElements.Count == 0) return []; var p = new Paragraph ( @@ -46,11 +44,10 @@ public override IEnumerable Interpret (ParsingContext context) } }; - if (childElements.First() is Run run) // any caption? + if (childElements[0] is Run run) // any caption? { Text? t = run.GetFirstChild(); - if (t != null) - t.Text = " " + t.InnerText; + t?.Text = " " + t.InnerText; } p.Append(childElements); @@ -63,13 +60,13 @@ public override IEnumerable Interpret (ParsingContext context) } else { - // If no particular alignement has been specified for the legend, we will align the legend + // If no particular alignment has been specified for the legend, we will align the legend // relative to the owning table TableProperties? props = table.GetFirstChild(); if (props != null) { TableJustification? justif = props.GetFirstChild(); - if (justif?.Val != null) + if (justif?.Val != null) p.ParagraphProperties.Justification = new() { Val = justif.Val.Value.ToJustification() }; } } diff --git a/src/Html2OpenXml/Expressions/Table/TableColExpression.cs b/src/Html2OpenXml/Expressions/Table/TableColExpression.cs index 588bc527..195c748a 100644 --- a/src/Html2OpenXml/Expressions/Table/TableColExpression.cs +++ b/src/Html2OpenXml/Expressions/Table/TableColExpression.cs @@ -9,8 +9,6 @@ * IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A * PARTICULAR PURPOSE. */ -using System; -using System.Collections.Generic; using System.Globalization; using AngleSharp.Html.Dom; using DocumentFormat.OpenXml; @@ -26,7 +24,7 @@ sealed class TableColExpression(IHtmlTableColumnElement node) : TableElementExpr private const int MaxTablePortraitWidth = 9622; private const int MaxTableLandscapeWidth = 12996; private readonly IHtmlTableColumnElement colNode = node; - private double? percentWidth; + private double? columnWidthPercent; /// @@ -47,8 +45,8 @@ public override IEnumerable Interpret(ParsingContext context) else if (width.Metric == UnitMetric.Percent) { var maxWidth = context.IsLandscape ? MaxTableLandscapeWidth : MaxTablePortraitWidth; - percentWidth = Math.Max(0, Math.Min(100, width.Value)); - column.Width = Math.Ceiling(maxWidth / 100d * percentWidth.Value).ToString(CultureInfo.InvariantCulture); + columnWidthPercent = Math.Max(0, Math.Min(100, width.Value)); + column.Width = Math.Ceiling(maxWidth / 100d * columnWidthPercent.Value).ToString(CultureInfo.InvariantCulture); } } @@ -58,7 +56,7 @@ public override IEnumerable Interpret(ParsingContext context) var elements = new OpenXmlElement[Math.Min(colNode.Span, TableExpression.MaxColumns)]; elements[0] = column; - for (int i = 1; i < colNode.Span; i++) + for (int i = 1; i < elements.Length; i++) elements[i] = column.CloneNode(true); return elements; @@ -68,12 +66,13 @@ public override void CascadeStyles(OpenXmlElement element) { base.CascadeStyles(element); - if (percentWidth.HasValue && element is TableCell cell && + if (columnWidthPercent.HasValue && element is TableCell cell && cell.TableCellProperties?.TableCellWidth is null) { cell.TableCellProperties!.TableCellWidth = new() { Type = TableWidthUnitValues.Pct, - Width = ((int) (percentWidth.Value * 50)).ToString(CultureInfo.InvariantCulture) + // OpenXml stores percentage widths in fiftieths of a percent + Width = ((int) (columnWidthPercent.Value * 50)).ToString(CultureInfo.InvariantCulture) }; } } diff --git a/src/Html2OpenXml/Expressions/Table/TableElementExpressionBase.cs b/src/Html2OpenXml/Expressions/Table/TableElementExpressionBase.cs index db87e399..427c01a7 100644 --- a/src/Html2OpenXml/Expressions/Table/TableElementExpressionBase.cs +++ b/src/Html2OpenXml/Expressions/Table/TableElementExpressionBase.cs @@ -36,8 +36,7 @@ public override void CascadeStyles(OpenXmlElement element) var knownTags = new HashSet(); foreach (var prop in p.ParagraphProperties) { - if (!knownTags.Contains(prop.LocalName)) - knownTags.Add(prop.LocalName); + knownTags.Add(prop.LocalName); } foreach (var prop in paraProperties) @@ -55,8 +54,7 @@ public override void CascadeStyles(OpenXmlElement element) var knownTags = new HashSet(); foreach (var prop in cell.TableCellProperties) { - if (!knownTags.Contains(prop.LocalName)) - knownTags.Add(prop.LocalName); + knownTags.Add(prop.LocalName); } foreach (var prop in cellProperties) @@ -74,7 +72,7 @@ protected override void ComposeStyles(ParsingContext context) if (!Converter.TryParseVAlign(styleAttributes["vertical-align"], out var valign) && !Converter.TryParseVAlign(node.GetAttribute("valign").AsSpan(), out valign)) { - // in Html, table cell are vertically centered by default + // HTML table cells defaults to vertical middle alignment valign = TableVerticalAlignmentValues.Center; } diff --git a/src/Html2OpenXml/Expressions/Table/TableExpression.cs b/src/Html2OpenXml/Expressions/Table/TableExpression.cs index 299b506a..d83f103f 100644 --- a/src/Html2OpenXml/Expressions/Table/TableExpression.cs +++ b/src/Html2OpenXml/Expressions/Table/TableExpression.cs @@ -10,6 +10,7 @@ * PARTICULAR PURPOSE. */ using System.Globalization; +using AngleSharp.Dom; using AngleSharp.Html.Dom; using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Wordprocessing; @@ -81,12 +82,12 @@ private List InterpretGridColumns(ParsingContext context, int column var columns = new List(columnCount); var colStyleExpressions = new List(columnCount); - var colgroup = tableNode.Children.FirstOrDefault(n => n.LocalName == "colgroup"); + var colgroup = tableNode.Children.FirstOrDefault(n => n.LocalName == TagNames.Colgroup); // if colgroup tag is not found, maybe the table was misformed and they stand below the root level colgroup ??= tableNode; foreach (var col in colgroup.Children - .Where(n => n.LocalName == "col").Cast()) + .Where(n => n.LocalName == TagNames.Col).Cast()) { var expression = new TableColExpression(col); foreach (var child in expression.Interpret(context).Cast()) @@ -120,6 +121,8 @@ public override void CascadeStyles(OpenXmlElement element) colIndex = 0; } + // cells are processed left-to-right. The current column style is applied + // before advancing the column index if (colIndex < colStyleExpressions.Length) colStyleExpressions![colIndex].CascadeStyles(element); @@ -205,8 +208,7 @@ protected override void ComposeStyles (ParsingContext context) }; } - var spacing = Convert.ToInt16(tableNode.GetAttribute("cellspacing")); - if (spacing > 0) + if (short.TryParse(tableNode.GetAttribute("cellspacing"), out var spacing) && spacing > 0) { tableProperties.TableCellSpacing = new() { Type = TableWidthUnitValues.Dxa, @@ -214,8 +216,7 @@ protected override void ComposeStyles (ParsingContext context) }; } - var padding = Convert.ToInt16(tableNode.GetAttribute("cellpadding")); - if (padding > 0) + if (short.TryParse(tableNode.GetAttribute("cellpadding"), out var padding) && padding > 0) { int paddingDxa = (int) new Unit(UnitMetric.Pixel, padding).ValueInDxa; diff --git a/src/Html2OpenXml/Expressions/Table/TablePartExpression.cs b/src/Html2OpenXml/Expressions/Table/TablePartExpression.cs index fe90819e..327a108a 100644 --- a/src/Html2OpenXml/Expressions/Table/TablePartExpression.cs +++ b/src/Html2OpenXml/Expressions/Table/TablePartExpression.cs @@ -9,7 +9,6 @@ * IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A * PARTICULAR PURPOSE. */ -using System.Collections.Generic; using AngleSharp.Html.Dom; using DocumentFormat.OpenXml; diff --git a/src/Html2OpenXml/Expressions/Table/TableRowExpression.cs b/src/Html2OpenXml/Expressions/Table/TableRowExpression.cs index 8b1223b9..df72bf8a 100644 --- a/src/Html2OpenXml/Expressions/Table/TableRowExpression.cs +++ b/src/Html2OpenXml/Expressions/Table/TableRowExpression.cs @@ -22,15 +22,15 @@ sealed class TableRowExpression : TableElementExpressionBase { private readonly IHtmlTableRowElement rowNode; private readonly TableRowProperties rowProperties = new(); - private readonly int columCount; - private readonly RowSpanCollection carriedRowSpans, rowSpans = []; + private readonly int columnCount; + private readonly RowSpanCollection carriedRowSpans; - public TableRowExpression(IHtmlTableRowElement node, int columCount, RowSpanCollection carriedRowSpans) + public TableRowExpression(IHtmlTableRowElement node, int columnCount, RowSpanCollection carriedRowSpans) : base (node) { rowNode = node; - this.columCount = columCount; + this.columnCount = columnCount; this.carriedRowSpans = carriedRowSpans; } @@ -41,7 +41,7 @@ public override IEnumerable Interpret (ParsingContext context) // RowSpan in html requires to skip the cell declaration on the next row, // whilst in OpenXml, the cell must exists with the VerticalMerge=Continue property - var cells = new List(columCount); + var cells = new List(columnCount); cells.AddRange(rowNode.Cells); foreach (var idx in carriedRowSpans.Columns) { @@ -80,20 +80,22 @@ public override IEnumerable Interpret (ParsingContext context) if (TableCellExpression.IsValidRowSpan(cell.RowSpan)) { - rowSpans.Add(colIndex, cell.RowSpan, cell.ColumnSpan); + RowSpans.Add(colIndex, cell.RowSpan, cell.ColumnSpan); } // The space effectively occupied by this cell. + // AngleSharp normalise the ColSpan (negative or zero become 1) colIndex += cell.ColumnSpan; } // if the row is not complete, create empty cells - if (colIndex < columCount) + while (colIndex < columnCount) { tableRow.AppendChild(TableCellExpression.CreateEmpty()); + colIndex++; } - rowSpans.UnionWith(carriedRowSpans); + RowSpans.CarryForward(carriedRowSpans); return [tableRow]; } @@ -118,8 +120,5 @@ protected override void ComposeStyles(ParsingContext context) /// /// The carried row spans. /// - public RowSpanCollection RowSpans - { - get => rowSpans; - } + public RowSpanCollection RowSpans { get; } = []; } \ No newline at end of file diff --git a/src/Html2OpenXml/Primitives/Size.cs b/src/Html2OpenXml/Primitives/Size.cs index 8dbdb6c3..5312dd67 100644 --- a/src/Html2OpenXml/Primitives/Size.cs +++ b/src/Html2OpenXml/Primitives/Size.cs @@ -55,4 +55,10 @@ public override string ToString() { return string.Format("({0},{1})", Width, Height); } + + /// + /// Ensure both the Width and Height are positive. + /// + public readonly bool HasInvalidDimension + => Width <= 0 || Height <= 0; } diff --git a/src/Html2OpenXml/Primitives/Unit.cs b/src/Html2OpenXml/Primitives/Unit.cs index 3dd7cdb4..c55888d5 100755 --- a/src/Html2OpenXml/Primitives/Unit.cs +++ b/src/Html2OpenXml/Primitives/Unit.cs @@ -19,20 +19,18 @@ namespace HtmlToOpenXml; readonly struct Unit { /// Represents an empty unit (not defined). - public static readonly Unit Empty = new Unit(); + public static readonly Unit Empty = new(); /// Represents an Auto unit. - public static readonly Unit Auto = new Unit(UnitMetric.Auto, 0L); + public static readonly Unit Auto = new(UnitMetric.Auto, 0L); private readonly UnitMetric metric; - private readonly double value; - private readonly long valueInEmus; public Unit(UnitMetric metric, double value) { this.metric = metric; - this.value = value; - this.valueInEmus = ComputeInEmus(metric, value); + this.Value = value; + this.ValueInEmus = ComputeInEmus(metric, value); } public static Unit Parse(ReadOnlySpan span, UnitMetric defaultMetric = UnitMetric.Unitless) @@ -134,33 +132,24 @@ private static long ComputeInEmus(UnitMetric metric, double value) /// /// Gets the type of unit (pixel, percent, point, ...) /// - public UnitMetric Metric - { - get { return metric; } - } + public UnitMetric Metric => metric; /// /// Gets the value of this unit. /// - public double Value - { - get { return value; } - } + public double Value { get; } /// /// Gets the value expressed in English Metrics Unit. /// - public long ValueInEmus - { - get { return valueInEmus; } - } + public long ValueInEmus { get; } /// /// Gets the value expressed in Dxa unit. /// public long ValueInDxa { - get { return (long) ((double) valueInEmus / 914400L * 20 * 72); } + get { return (long) ((double)ValueInEmus / 914400L * 20 * 72); } } /// @@ -168,7 +157,7 @@ public long ValueInDxa /// public int ValueInPx { - get { return (int) (metric == UnitMetric.Pixel ? this.value : (float) valueInEmus / 914400L * 96); } + get { return (int) (metric == UnitMetric.Pixel ? this.Value : (float)ValueInEmus / 914400L * 96); } } /// @@ -176,7 +165,7 @@ public int ValueInPx /// public double ValueInPoint { - get { return metric == UnitMetric.Point ? this.value : (float) valueInEmus / 12700L; } + get { return metric == UnitMetric.Point ? this.Value : (float)ValueInEmus / 12700L; } } /// diff --git a/src/Html2OpenXml/Utilities/AngleSharpExtensions.cs b/src/Html2OpenXml/Utilities/AngleSharpExtensions.cs index 711eb959..cfab8d84 100644 --- a/src/Html2OpenXml/Utilities/AngleSharpExtensions.cs +++ b/src/Html2OpenXml/Utilities/AngleSharpExtensions.cs @@ -44,9 +44,17 @@ public static HtmlAttributeCollection GetStyles(this IElement element) [MethodImpl(MethodImplOptions.AggressiveInlining)] public static bool IsTopAnchor(this IHtmlAnchorElement element) { - if (element.Hash.Length <= 1) return false; - return "#top".Equals(element.Hash, StringComparison.OrdinalIgnoreCase) - || "#_top".Equals(element.Hash, StringComparison.OrdinalIgnoreCase); + if (element.Hash.Length < 4) return false; + return IsTopAnchor(element.Hash.AsSpan(1)); + } + + /// + /// Gets whether the anchor is redirect to the `top` of the document. + /// + [MethodImpl(MethodImplOptions.AggressiveInlining)] + public static bool IsTopAnchor(ReadOnlySpan anchor) + { + return anchor.Is("top") || anchor.Is("_top"); } /// 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/LinkTests.cs b/test/HtmlToOpenXml.Tests/LinkTests.cs index c9d0daa3..ebdfe20b 100644 --- a/test/HtmlToOpenXml.Tests/LinkTests.cs +++ b/test/HtmlToOpenXml.Tests/LinkTests.cs @@ -284,6 +284,13 @@ 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) { diff --git a/test/HtmlToOpenXml.Tests/TableTests.cs b/test/HtmlToOpenXml.Tests/TableTests.cs index 292c8a5c..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()); @@ -776,7 +776,7 @@ public void ColWithPercentWidth_ReturnsRefineTableWidth() Assert.That(cells.Last().TableCellProperties?.TableCellWidth?.Width?.Value, Is.EqualTo("4346")); } } - + [Test] public void CellPadding_ReturnsTableCellMargin() { From ad7c988c148fef41971a36df73f1e33179ee4ce3 Mon Sep 17 00:00:00 2001 From: Olivier Nizet Date: Fri, 13 Nov 2026 22:21:42 +0100 Subject: [PATCH 18/18] Update changelog --- CHANGELOG.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4ac598c4..dfde7de2 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,9 +8,13 @@ Ease of Use Improvements: - 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