diff --git a/CHANGELOG.md b/CHANGELOG.md index dfde7de2..bbb8b20b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,21 @@ # Changelog +## 4.3.0 + +- New `WordDocumentFactory.Create(orientation, paperSize)` helper. +- New `WordDocumentFactory.AddPage(orientation, paperSize)` helper. +- New `WordDocumentFactory.AddPageBreak()` helper. +- Add extensibility capabilities to the converter: `Transformers`, `ParserConfigurators` and `NodeProcessors`. +- New `LoadDocumentAsync(html)` which allow parsing once and converting multiple times. +- Image size expressed in percentage (max-width) consider the current page width (orientation and different paper size than A4). +- Image widths are automatically constrained to prevent overflow of the page. +- Fix SVG appended to the body rather than in the footer/header. + +- **[BREAKING CHANGE]** Remove the non-standard attribute `page-orientation` on the body to change the orientation. Use `AddPage()` instead. +- Stop mutating the `HttpClient` in `DefaultWebRequest`. +- Remove `ILogger` from `DefaultWebRequest` which removes one extra package dependency. +- Prefer `converter.UseCssInliner()` rather than creating a new instance of `CssStyleHtmlConverter`. + ## 4.2.0 Ease of Use Improvements: diff --git a/Directory.Build.props b/Directory.Build.props index 77e8e3a6..72b5f240 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -4,7 +4,7 @@ enable preview enable - 4.2.0 + 4.3.0 diff --git a/Directory.Packages.props b/Directory.Packages.props index 7a158eb4..e1344b32 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -7,23 +7,22 @@ - - + + - - + - + - - + + @@ -33,11 +32,7 @@ - - - - - - + + \ No newline at end of file diff --git a/README.md b/README.md index 22e7f15e..1a8b68a0 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # HtmlToOpenXml [![Latest version](https://img.shields.io/nuget/v/HtmlToOpenXml.svg)](https://www.nuget.org/packages/HtmlToOpenXml/) [![Download Counts](https://img.shields.io/nuget/dt/HtmlToOpenXml.svg)](https://www.nuget.org/packages/HtmlToOpenXml/) [![MIT License](https://img.shields.io/badge/license-MIT-blue.svg)](https://github.com/onizet/html2openxml/blob/dev/LICENSE) -HtmlToOpenXml is a mature, high-fidelity converter that translates complex HTML structures into native OpenXML elements, ensuring your content renders exactly as intended across all Microsoft Word users. +HtmlToOpenXml is a mature library for generating native OpenXML Word documents from HTML. It transforms simple or complete HTML into fully editable Word content while preserving document styles, numbering definitions, templates, and layout. Originally created in 2009 to transform user-generated content into templated Word documents, it has evolved into a mature HTML-to-OpenXML converter supporting styles, numbering, images, bookmarks, page layout, tables, @@ -8,14 +8,31 @@ document template, and custom resource resolution. ![Logo](https://raw.githubusercontent.com/onizet/html2openxml/master/docs/images/html2openxml.png) -Supports **.Net Framework 4.6.2**, **.NET Standard 2.0**, **.NET 8** **.NET 10** which are all LTS. +## Features -Built on top of [DocumentFormat.OpenXml](https://www.nuget.org/packages/DocumentFormat.OpenXml/) and [AngleSharp](https://www.nuget.org/packages/AngleSharp). +- HTML → DOCX conversion +- Word template integration +- Portrait and landscape page sections +- Headers and footers +- Tables with RowSpan and ColSpan support +- Numbered and bulleted lists +- Images (PNG, JPEG, SVG, Data URI) +- Internal hyperlinks and bookmarks +- Right-to-left (RTL) documents +- CSS stylesheet support (optional package) + +Supports **.NET Framework 4.6.2**, **.NET Standard 2.0**, **.NET 8** **.NET 10**. --> [Official Nuget Package](https://www.nuget.org/packages/HtmlToOpenXml) (❗ **Update your bookmark**, suffix `.dll` removed) +Built on top of [DocumentFormat.OpenXml](https://www.nuget.org/packages/DocumentFormat.OpenXml/) and [AngleSharp](https://www.nuget.org/packages/AngleSharp). --> [HtmlToOpenXml.CssInliner](https://www.nuget.org/packages/HtmlToOpenXml.CssInliner/) (companion library for extended CSS support) +| Package | NuGet Stable | Downloads | +| ------- | ------------ | --------- | +| [HtmlToOpenXml](https://www.nuget.org/packages/HtmlToOpenXml/) | [![HtmlToOpenXml](https://img.shields.io/nuget/v/HtmlToOpenXml.svg)](https://www.nuget.org/packages/HtmlToOpenXml/) | [![HtmlToOpenXml](https://img.shields.io/nuget/dt/HtmlToOpenXml.svg)](https://www.nuget.org/packages/HtmlToOpenXml/) | +| [HtmlToOpenXml.CssInliner](https://www.nuget.org/packages/HtmlToOpenXml.CssInliner/) | [![HtmlToOpenXml.CssInliner](https://img.shields.io/nuget/v/HtmlToOpenXml.CssInliner.svg)](https://www.nuget.org/packages/HtmlToOpenXml.CssInliner/) | [![HtmlToOpenXml.CssInliner](https://img.shields.io/nuget/dt/HtmlToOpenXml.CssInliner.svg)](https://www.nuget.org/packages/HtmlToOpenXml.CssInliner/) | +> **Note** +> The package was renamed from `HtmlToOpenXml.dll` to `HtmlToOpenXml`. +> NuGet download statistics were unfortunately not transferred to the new package. ## Quick Start diff --git a/docs/.vuepress/config.js b/docs/.vuepress/config.js index 650dc43f..27c28fa8 100644 --- a/docs/.vuepress/config.js +++ b/docs/.vuepress/config.js @@ -20,7 +20,7 @@ export default defineUserConfig({ navbar: ['/', { text: 'API Reference', link: '/guide/api', prefix: 'guide/', - children: ['api', 'hyperlinks', 'images', 'styling', 'tables', 'numbering', 'pre', 'footnotes', 'pagebreak', 'rtl'] + children: ['api', 'composition', 'hyperlinks', 'images', 'styling', 'tables', 'numbering', 'pre', 'footnotes', 'rtl'] }, { text: 'LLM Docs Friendly', link: '/llmdoc' }, { text: 'NuGet', link: 'https://www.nuget.org/packages/HtmlToOpenXml', ariaLabel: 'NuGet', target: '_blank' } @@ -30,7 +30,7 @@ export default defineUserConfig({ { text: 'API Reference', prefix: 'guide/', - children: ['quickstart', 'api', 'hyperlinks', 'images', 'styling', 'tables', 'numbering', 'pre', 'footnotes', 'pagebreak', 'rtl'], + children: ['quickstart', 'api', 'composition', 'hyperlinks', 'images', 'styling', 'tables', 'numbering', 'pre', 'footnotes', 'rtl', 'extensibility'], }, { text: 'LLM Docs Friendly', link: 'llmdoc' diff --git a/docs/.vuepress/public/nuspec-ai.txt b/docs/.vuepress/public/nuspec-ai.txt index 88ba80a5..a70c0c94 100644 --- a/docs/.vuepress/public/nuspec-ai.txt +++ b/docs/.vuepress/public/nuspec-ai.txt @@ -1,7 +1,7 @@ -#NuSpec.AI/v2 HtmlToOpenXml 4.2.0 +#NuSpec.AI/v2 HtmlToOpenXml 4.3.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.6|0;DocumentFormat.OpenXml|3.5.1|0;Microsoft.Extensions.Logging.Abstractions|6.0.0|0;System.ValueTuple|4.6.2|0 +#dep AngleSharp|1.10.4|0;DocumentFormat.OpenXml|3.5.1|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." @@ -21,29 +21,56 @@ .p ParagraphHeaderStyle:string "Default style for any paragraphs (p) in the header section (DocumentFormat.OpenXml.Packaging.HeaderPart )." .p ParagraphFooterStyle:string "Default style for any paragraphs (p) in the footer section (DocumentFormat.OpenXml.Packaging.FooterPart )." .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." +@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 (RTL) 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. Instances are not thread-safe and should not be used concurrently." .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, CancellationToken cancellationToken = null) "Convert HTML into OpenXml elements and return them to the caller. The returned elements are detached from the document body, but the conversion prcoess may create or udpate related OpenXml parts such as styles, numbering definitions, bookmarks, image parts and relationship 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()." - .m ParseHeader:Task(string html, HeaderFooterValues? headerType = null, CancellationToken cancellationToken = null) "Parse some HTML and append the genereated content to a Word header. Typical uses include company logos, document titles, confidentiality notices, report identifiers, and other recurring content displayed at the top of each page." + .m ParseAsync:Task>(HtmlFragment fragment, CancellationToken cancellationToken = null) "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()." + .m LoadDocumentAsync:Task(string html, CancellationToken cancellationToken = null) "Loads an HTML document and returns its body as a reusable fragment. The document is parsed only once and any registered parser configurators and transformers are supplied before the fragment is returned." + .m ParseHeader:Task(HtmlFragment fragment, HeaderFooterValues? headerType = null, CancellationToken cancellationToken = null) "Parse some HTML and append the generated content to a Word header." + .m ParseHeader:Task(string html, HeaderFooterValues? headerType = null, CancellationToken cancellationToken = null) "Parse some HTML and append the generated content to a Word header. Typical uses include company logos, document titles, confidentiality notices, report identifiers, and other recurring content displayed at the top of each page." + .m ParseFooter:Task(HtmlFragment fragment, HeaderFooterValues? footerType = null, CancellationToken cancellationToken = null) "Parse some HTML and append the generated content into a Word footer." .m ParseFooter:Task(string html, HeaderFooterValues? footerType = null, CancellationToken cancellationToken = null) "Parse some HTML and append the generated content into a Word footer. Typical uses include legal disclaimers, contact information, page numbering, copyright notices, and other recurring content displayed at the bottom of each page." + .m ParseBody:Task(HtmlFragment fragment, CancellationToken cancellationToken = null) "Parses some Html and appends the generated content to the document body." .m ParseBody:Task(string html, CancellationToken cancellationToken = null) "Parses some Html and appends the generated content to the document body. This is the recommended method for most scenarios. Page Break can be inserted using the CSS properties page-break-before and page-break-after with the value "always". Useful for reports, invoices, contracts, and other multi-page business documents. Page Orientation can be changed through the non-standard page-orientation attribute (supported values: portrait and landscape). This is useful for wide tables, reports and other content that benefits from a landscape layout. Currently, the attribute is supported on the body element and applies to the main document." .m RefreshStyles:void() "Reloads the style cache from the current Word document (HtmlToOpenXml.WordDocumentStyle). Call this method if styles are added after the HtmlConverter instance has been created." .p AcronymPosition:AcronymPosition "Defines the location where to add the acronym or abbreviation explanation tag. Defaults to the end of the page (HtmlToOpenXml.AcronymPosition.PageEnd)." - .p SupportsAnchorLinks:bool "Defines whether internal anchor hyperlinks are converted to Word bookmarks. Anchor links target another location within the document, such as #_top or a bookmark reference (#bookmarkReference). Bookmars can be created automatically from HTML anchors or explicitely using the data-bookmark attribute. When data-bookmark is present, the library uses this target name to jump to an existing structural element in the destination DOCX file rather than creating a new anchor.

Introduction

Anchor links are enabled by default. If the target cannot be resolved in the current Word document, the content will be rendered as a simple text." - .p HtmlStyles:WordDocumentStyle "Gets the style manager for the current conversion. HtmlStyles controls how HTML elements are translated into Word styles. Through this object you can customize the default style mappings, add custom styles, and react when a referenced style is missing from the document." + .p SupportsAnchorLinks:bool "Defines whether internal anchor hyperlinks are converted to Word bookmarks. Anchor links target another location within the document, such as #_top or a bookmark reference (#bookmarkReference). Bookmarks can be created automatically from HTML anchors or explicitly using the data-bookmark attribute. When data-bookmark is present, the library uses this target name to jump to an existing structural element in the destination DOCX file rather than creating a new anchor.

Introduction

Anchor links are enabled by default. If the target cannot be resolved in the current Word document, the content will be rendered as a simple text." + .p HtmlStyles:WordDocumentStyle "Gets the style translator used for the current conversion. HtmlStyles acts as the runtime bridge between CSS class attributes and target Word styles. Through this object you can customize the default style mappings, add custom styles, and handle the HtmlToOpenXml.WordDocumentStyle.StyleMissing event when a referenced style is absent from the template. Class name are case insensitive, e.g.,

will be mapped to and rendered using the Word style Important_Paragraph." .p TableCaptionPosition:CaptionPositionValues "Defines where the Legend tag (caption) should be rendered above or below the table. Defaults above the table." .p RenderPreAsTable:bool "Defines whether the preformatted blocks (pre) are rendered as tables. When enabled, pre elements are converted to a single-cell table to preserve whitespace, indentation and line breaks. This is particularly useful for source code, console output, and technical blog posts. When disabled, preformatted content is rendered using regular Word paragraphs. Defaults to false." .p ImageProcessing:ImageProcessingMode "Controls how images are handled during conversion. Images are embedded in the generated document by default. External resources are resolved through HtmlToOpenXml.IO.IWebRequest, which can be customised to provide authentication, support additional formats such as WebP (see the wiki), or resolve relative URLs. Default: HtmlToOpenXml.ImageProcessingMode.Embed." .p ContinueNumbering:bool "Defines whether consecutive ordered lists continue the numbering sequence from previous lists. By default, numbering continues across multiple ol elements. Use the HTML start attribute to restart numbering or begin at a specific value. When disabled, each ordered list starts a new numbering sequence." .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." + .p WebRequester:IWebRequest "Gets the resource retrieval service used by the converter." + .p Transformers:IList "Gets the collection of document transformers executed after the HTML document has been parsed but before OpenXml conversion begins." + .p ParserConfigurators:IList "Gets the collection of parser configurators used to customize the underlying AngleSharp parsing environment." + .p NodeProcessors:IList "Gets the collection of custom HTML node processors used during document conversion. Processors can extend or override the interpretation of HTML nodes." +@c HtmlFragment "Represents an HTML fragment that can be transformed, queried, and converted into OpenXml content. A fragment always represent an HTML element. Non-HTML elements, such as SVG nodes, are not exposed through this abstraction." + .m QuerySelector:HtmlFragment?(string selectors) "Returns the first descendant fragment matching the specified selector." + .m QuerySelectoAll:IReadOnlyCollection(string selectors) "Returns all descendant fragments matching the specified selector." + .m Remove:void() "Removes this fragment from its parent document. This is useful when a fragment is rendered separately (for example as a header, footer or cover page), and should not be included in subsequent body conversion." + .m ReplaceContent:void(string replacementHtml) "Replace the content of this fragment with the specified HTML markup. The supplied HTML is parsed and inserted as the new children of the current fragment. The fragment element itself is preserved This method modifies the loaded HTML document in-place allowing transformers and application code to reshape the document structure before OpenXml conversion begins." + .p InnerHtml:string "Gets or sets the inner HTML (excluding the current element) of the element." + .p OuterHtml:string "Gets or sets the outer HTML (including the current element) of the element." +@i IHtmlNodeContext "Provides access to document-level services and state during the interpretation of an HTML node. This interface intentionally exposes only the information required by custom node processors and shoud not be considered a complete representation of the parser state." + .p MainPart:MainDocumentPart "The mainDocumentPart where converted content will be inserted." + .p DocumentStyle:WordDocumentStyle "Gets the style translator used for the current conversion." + .m CascadeStyles:void(OpenXmlElement element) "Applies all styles currently inherited from the surrounding HTML context to the specified OpenXml element. Custom node processors can use this method to ensure that generated OpenXml elements participate in the same style inheritance rules as elements produced by the built-in HtmlToOpenXml processors." +@i IHtmlNodeProcessor "Provides a custom interpretation for one or more HTML nodes. Implementations can extend or override the default HtmlToOpenXml processing pipeline by translating specific HTML nodes into OpenXml elements. Node processors are evaluated before the built-in tag handlers. If a processor declares that it can handle a node, the default HtmlToOpenXml implementation is bypassed for that node." + .m CanProcess:bool(INode node) "Determines whether this processor should interpret the specified node." + .m Interpret:IEnumerable(IHtmlNodeContext context, INode node) "Converts the specified HTML node into OpenXml elements." +@i IHtmlParserConfigurator "Configures the HTML parsing environment before a document is loaded. Implementations can register additional parser services such as CSS engines, resource loaders, scripting support, or custom AngleSharp integrations." + .m Configure:IConfiguration(IConfiguration configuration) "Configure the HTML parsing environment." +@i IHtmlTransformer "Performs document-wide transformations after HTML parsing and before the OpenXml conversion begins. Transformers operate on an already loaded HtmlToOpenXml.HtmlFragment and can normalize markup, inline CSS declarations, rewrite links, inject corporate branding, create bookmarks, sanitize content, or perform any DOM manipulation required by the application." + .m TransformAsync:Task(AngleSharp.Dom.IDocument document, CancellationToken cancellationToken) "Transforms the specified HTML fragment before conversion." @e ImageProcessingMode "Controls whether images are embedded in the generated document or kept as external references." .ev Embed=0,LinkExternal=1,EmbedDataUriOnly=2 @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." + .ctor () "Initialize a new instance of the HtmlToOpenXml.IO.DefaultWebRequest class." + .ctor (HttpClient httpClient) "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." .m FetchAsync:Task(Uri requestUri, CancellationToken cancellationToken) .m SupportsProtocol:bool(string protocol) .p BaseImageUrl:Uri? "Defines the base URI used to resolve image URLs. Use this property when HTML content contains relative images references such as /images/logo.png or /../assets/banner.jpg. During conversion, relative URLs are combined with this base URI to locate and download the image resource" @@ -57,6 +84,8 @@ .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 +@e PaperSize "Defines the paper size used when creating new document page. Sizes correspond to the standard paper formats supported by Microsoft Word and OpenXML." + .ev A3=0,A4=1,A5=2,A6=3,B3=4,B4=5,B5=6,B6=7,Letter=8,Legal=9 @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 »" @@ -66,8 +95,11 @@ .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." + .m Create:WordprocessingDocument(Stream stream, PageOrientation orientation = Portrait, PaperSize paperSize = A4) "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." + .m AddPage:void(this HtmlConverter converter, PageOrientation orientation, PaperSize paperSize = A4) "Starts a new page in the document using the specified paper size and orientation. The new page is created as a separate Word section, allowing the page size and orientation to differ from the surrounding content." + .m AddPageBreak:void(this HtmlConverter converter) "Inserts a page break immediately after the specified element." @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." - .p QuoteCharacters:QuoteChars "Defines the beginning and ending characters used in the tag. Defaults follow the style: « abc »." \ No newline at end of file + .p QuoteCharacters:QuoteChars "Defines the beginning and ending characters used in the tag. Defaults follow the style: « abc »." + .p Styles:IEnumerable")] + [TestCase("")] + [TestCase("")] + [TestCase("")] + [TestCase("max='100' value='70'>70%")] + [TestCase("")] + [TestCase("")] + [TestCase("350 degrees")] + [TestCase("

")] + public void UnsupportedTag_ShouldBeIgnored(string html) { - [TestCase("")] - [TestCase("")] - [TestCase("")] - [TestCase("")] - [TestCase("")] - [TestCase("")] - [TestCase("max='100' value='70'>70%")] - [TestCase("")] - [TestCase("")] - [TestCase("350 degrees")] - [TestCase("

")] - public void UnsupportedTag_ShouldBeIgnored(string html) - { - // the inner html shouldn't be interpreted - var elements = converter.Parse(html); - Assert.That(elements, Is.Empty); - } + // the inner html shouldn't be interpreted + var elements = converter.Parse(html); + Assert.That(elements, Is.Empty); + } - [Test] - public void Paragraph_WithUnclosedTags_ShouldApplyStyle() - { - var elements = converter.Parse("

some text in italics ,bold and italics

"); - Assert.That(elements, Has.Count.EqualTo(1)); - Assert.That(elements[0].InnerText, Is.EqualTo("some text in italics ,bold and italics")); - - var runProperties = elements[0].ChildElements[0].GetFirstChild(); - Assert.That(runProperties, Is.Null); - - runProperties = elements[0].ChildElements[1].GetFirstChild(); - Assert.That(runProperties, Is.Not.Null); - using (Assert.EnterMultipleScope()) - { - Assert.That(runProperties.HasChild(), Is.True); - Assert.That(runProperties.HasChild(), Is.False); - } - - runProperties = elements[0].ChildElements[2].GetFirstChild(); - Assert.That(runProperties, Is.Not.Null); - using (Assert.EnterMultipleScope()) - { - Assert.That(runProperties.HasChild(), Is.True); - Assert.That(runProperties.HasChild(), Is.True); - } - } + [Test] + public void Paragraph_WithUnclosedTags_ShouldApplyStyle() + { + var elements = converter.Parse("

some text in italics ,bold and italics

"); + Assert.That(elements, Has.Count.EqualTo(1)); + Assert.That(elements[0].InnerText, Is.EqualTo("some text in italics ,bold and italics")); - [Test] - public void ConsecutiveParagraph_WithUnclosedTags_ShouldContinueStyle() - { - var elements = converter.Parse("

First paragraph in semi-italics

Second paragraph still italic but also in bold

"); - Assert.That(elements, Has.Count.EqualTo(2)); - using (Assert.EnterMultipleScope()) - { - Assert.That(elements[0].Elements().Count, Is.EqualTo(2)); - Assert.That(elements[1].Elements().Count, Is.EqualTo(2)); - } - - var runProperties = elements[0].ChildElements[0].GetFirstChild(); - Assert.That(runProperties, Is.Null); - - runProperties = elements[0].GetLastChild()!.GetFirstChild(); - Assert.That(runProperties, Is.Not.Null); - Assert.That(runProperties.HasChild(), Is.True); + var runProperties = elements[0].ChildElements[0].GetFirstChild(); + Assert.That(runProperties, Is.Null); - runProperties = elements[1].FirstChild?.GetFirstChild(); - Assert.That(runProperties, Is.Not.Null); + runProperties = elements[0].ChildElements[1].GetFirstChild(); + Assert.That(runProperties, Is.Not.Null); + using (Assert.EnterMultipleScope()) + { Assert.That(runProperties.HasChild(), Is.True); Assert.That(runProperties.HasChild(), Is.False); + } - runProperties = elements[1].GetLastChild()!.GetFirstChild(); - Assert.That(runProperties, Is.Not.Null); + runProperties = elements[0].ChildElements[2].GetFirstChild(); + Assert.That(runProperties, Is.Not.Null); + using (Assert.EnterMultipleScope()) + { Assert.That(runProperties.HasChild(), Is.True); Assert.That(runProperties.HasChild(), Is.True); } + } - [Test] - public void ConsecutiveParagraph_WithClosedTags_ShouldNotContinueStyle() + [Test] + public void ConsecutiveParagraph_WithUnclosedTags_ShouldContinueStyle() + { + var elements = converter.Parse("

First paragraph in semi-italics

Second paragraph still italic but also in bold

"); + Assert.That(elements, Has.Count.EqualTo(2)); + using (Assert.EnterMultipleScope()) { - // this should generate a new paragraph with its own style - var elements = converter.Parse("

First paragraph in italics

Second paragraph not in italic

"); - Assert.That(elements, Has.Count.EqualTo(2)); Assert.That(elements[0].Elements().Count, Is.EqualTo(2)); - Assert.That(elements[1].Elements().Count, Is.EqualTo(1)); - Assert.That(elements[1].FirstChild, Is.TypeOf(typeof(Run))); - - var runProperties = elements[1].FirstChild!.GetFirstChild(); - Assert.That(runProperties, Is.Null); + Assert.That(elements[1].Elements().Count, Is.EqualTo(2)); } - [TestCase("

Some\ntext

", ExpectedResult = 1)] - [TestCase("

Some bold\ntext

", ExpectedResult = 3)] - [TestCase("\t

Some bold\ntext

", ExpectedResult = 3)] - [TestCase("

Some text

", ExpectedResult = 1)] - public int Newline_ReturnsRunCount (string html) - { - var elements = converter.Parse(html); - return elements[0].Elements().Count(); - } + var runProperties = elements[0].ChildElements[0].GetFirstChild(); + Assert.That(runProperties, Is.Null); - [TestCase(" < b >bold
", ExpectedResult = "< b >bold")] - [TestCase(" <3", ExpectedResult = "<3")] - public string EntityNames_ShouldBeTreatedAsSimpleText (string html) - { - var elements = converter.Parse(html); - Assert.That(elements, Has.Count.EqualTo(1)); - Assert.That(elements[0].ChildElements, Has.Count.EqualTo(1)); - Assert.That(elements[0].FirstChild, Is.TypeOf()); - return elements[0].FirstChild.InnerText; - } + runProperties = elements[0].GetLastChild()!.GetFirstChild(); + Assert.That(runProperties, Is.Not.Null); + Assert.That(runProperties.HasChild(), Is.True); - [Test(Description = "Provided html is only whitespaces")] - public void EmptyText_ShouldBeIgnored() - { - var elements = converter.Parse(" \n"); - Assert.That(elements, Is.Empty); - } + runProperties = elements[1].FirstChild?.GetFirstChild(); + Assert.That(runProperties, Is.Not.Null); + Assert.That(runProperties.HasChild(), Is.True); + Assert.That(runProperties.HasChild(), Is.False); - [Test(Description = "Provided mainPart is null")] - public void ProvidedMainPart_WithNull_ShouldFail() - { - Assert.Throws(() => new HtmlConverter((MainDocumentPart) null!)); - } + runProperties = elements[1].GetLastChild()!.GetFirstChild(); + Assert.That(runProperties, Is.Not.Null); + Assert.That(runProperties.HasChild(), Is.True); + Assert.That(runProperties.HasChild(), Is.True); + } - [Test(Description = "Provided mainPart.Document is empty")] - public void ProvidedMainPartDocument_WithNull_ShouldBeAssigned() - { - using var generatedDocument = new MemoryStream(); - using var package = WordprocessingDocument.Create(generatedDocument, WordprocessingDocumentType.Document); - mainPart = package.MainDocumentPart!; - mainPart = package.AddMainDocumentPart(); + [Test] + public void ConsecutiveParagraph_WithClosedTags_ShouldNotContinueStyle() + { + // this should generate a new paragraph with its own style + var elements = converter.Parse("

First paragraph in italics

Second paragraph not in italic

"); + Assert.That(elements, Has.Count.EqualTo(2)); + Assert.That(elements[0].Elements().Count, Is.EqualTo(2)); + Assert.That(elements[1].Elements().Count, Is.EqualTo(1)); + Assert.That(elements[1].FirstChild, Is.TypeOf(typeof(Run))); + + var runProperties = elements[1].FirstChild!.GetFirstChild(); + Assert.That(runProperties, Is.Null); + } - Assert.That(mainPart.Document, Is.Null); + [TestCase("

Some\ntext

", ExpectedResult = 1)] + [TestCase("

Some bold\ntext

", ExpectedResult = 3)] + [TestCase("\t

Some bold\ntext

", ExpectedResult = 3)] + [TestCase("

Some text

", ExpectedResult = 1)] + public int Newline_ReturnsRunCount (string html) + { + var elements = converter.Parse(html); + return elements[0].Elements().Count(); + } - var elements = new HtmlConverter(mainPart).Parse("Placeholder"); - Assert.That(elements, Is.Not.Empty); - } + [TestCase(" < b >bold
", ExpectedResult = "< b >bold")] + [TestCase(" <3", ExpectedResult = "<3")] + public string EntityNames_ShouldBeTreatedAsSimpleText (string html) + { + var elements = converter.Parse(html); + Assert.That(elements, Has.Count.EqualTo(1)); + Assert.That(elements[0].ChildElements, Has.Count.EqualTo(1)); + Assert.That(elements[0].FirstChild, Is.TypeOf()); + return elements[0].FirstChild.InnerText; + } + + [Test(Description = "Provided html is only whitespaces")] + public void EmptyText_ShouldBeIgnored() + { + var elements = converter.Parse(" \n"); + Assert.That(elements, Is.Empty); + } - [Test(Description = "Provided BaseImageUrl must be an absolute uri")] - public void ProvidedBaseImageUrl_WithRelativeUrl_ShouldFail() + [Test(Description = "Provided mainPart is null")] + public void ProvidedMainPart_WithNull_ShouldFail() + { + Assert.Throws(() => new HtmlConverter((MainDocumentPart) null!)); + } + + [Test(Description = "Provided mainPart.Document is empty")] + public void ProvidedMainPartDocument_WithNull_ShouldBeAssigned() + { + using var generatedDocument = new MemoryStream(); + using var package = WordprocessingDocument.Create(generatedDocument, WordprocessingDocumentType.Document); + mainPart = package.MainDocumentPart!; + mainPart = package.AddMainDocumentPart(); + + Assert.That(mainPart.Document, Is.Null); + + var elements = new HtmlConverter(mainPart).Parse("Placeholder"); + Assert.That(elements, Is.Not.Empty); + } + + [Test(Description = "Provided BaseImageUrl must be an absolute uri")] + public void ProvidedBaseImageUrl_WithRelativeUrl_ShouldFail() + { + Assert.Throws(() => new HtmlConverter(mainPart, new IO.DefaultWebRequest { + BaseImageUrl = new Uri("/path", UriKind.Relative) + })); + } + + [Test] + public async Task LoadHtml_ThenParseFragment_ShouldInsertInCorrectPart() + { + var document = await converter.LoadDocumentAsync(""" +
Header content
+ Body content + """, TestContext.CurrentContext.CancellationToken); + + var header = document.QuerySelector("header"); + Assert.That(header, Is.Not.Null); + Assert.That(header.InnerHtml, Is.EqualTo("Header content")); + + await converter.ParseHeader(header); + header.Remove(); + + Assert.That(document.InnerHtml.Trim(), Is.EqualTo("Body content")); + + await converter.ParseBody(document); + + using (Assert.EnterMultipleScope()) { - Assert.Throws(() => new HtmlConverter(mainPart, new IO.DefaultWebRequest { - BaseImageUrl = new Uri("/path", UriKind.Relative) - })); + Assert.That(mainPart.HeaderParts.First().Header!.InnerText, Is.EqualTo("Header content")); + Assert.That(mainPart.Document!.Body!.InnerText, Is.EqualTo("Body content")); } } + + [Test] + public void OverrideNodeProcessor_ShouldReplaceDefaultInterpreter() + { + var today = DateTime.Today; + + var dateProcessor = new Mock(); + dateProcessor.Setup(p => p.CanProcess(It.IsAny())) + .Returns(false); + dateProcessor.Setup(p => p.CanProcess(It.Is( + n => n.NodeName == "H2O-DATE"))) + .Returns(true); + + dateProcessor.Setup(p => p.Interpret( + It.IsAny(), + It.Is(n => n.NodeName == "H2O-DATE"))) + .Returns([ + new Run(new Text(today.ToShortDateString())) + ]); + + converter.NodeProcessors.Add(dateProcessor.Object); + + var elements = converter.Parse("Italics"); + dateProcessor.Verify(p => p.CanProcess(It.IsAny()), + Times.Exactly(2), "Expected to be called for and "); + + dateProcessor.Verify(p => p.Interpret( + It.IsAny(), + It.Is(n => n.NodeName == "H2O-DATE")), Times.Once()); + + Assert.That(elements, Has.Count.EqualTo(1)); + Assert.That(elements[0].ChildElements, Has.Count.EqualTo(2)); + Assert.That(elements[0].FirstChild?.InnerText, Is.EqualTo(today.ToShortDateString())); + Assert.That(elements[0].LastChild?.InnerText, Is.EqualTo("Italics")); + } } \ No newline at end of file diff --git a/test/HtmlToOpenXml.Tests/TableTests.cs b/test/HtmlToOpenXml.Tests/TableTests.cs deleted file mode 100644 index a265bfef..00000000 --- a/test/HtmlToOpenXml.Tests/TableTests.cs +++ /dev/null @@ -1,879 +0,0 @@ -using NUnit.Framework; -using DocumentFormat.OpenXml.Wordprocessing; - -namespace HtmlToOpenXml.Tests -{ - /// - /// Tests for table or pre. - /// - [TestFixture] - public class TableTests : HtmlConverterTestBase - { - [TestCase("
", Description = "Row with no cells")] - [TestCase("
", Description = "No rows")] - [TestCase("
", Description = "No rows in any parts")] - public void EmptyTable_ShouldBeIgnored(string html) - { - var elements = converter.Parse(html); - Assert.That(elements, Is.Empty); - } - - [Test(Description = "Empty cell should generate an empty Paragraph")] - public void EmptyCell_ReturnsEmpty() - { - var elements = converter.Parse(@"
Next cell is empty
"); - Assert.That(elements, Has.Count.EqualTo(1)); - Assert.That(elements, Has.All.TypeOf()); - - var rows = elements[0].Elements(); - Assert.That(rows.Count(), Is.EqualTo(1)); - var cells = rows.First().Elements(); - Assert.That(cells.Count(), Is.EqualTo(2)); - Assert.That(cells.All(c => c.HasChild()), Is.True); - Assert.That(cells.Last().Count(c => c is not TableCellProperties), Is.EqualTo(1)); - } - - [Test(Description = "Empty tfoot should be ignored")] - public void EmptyTablePart_ShouldBeIgnored() - { - // table parts should be reordered - var elements = converter.Parse(@"
- - -
Cell 1.1
"); - - Assert.That(elements, Has.Count.EqualTo(1)); - Assert.That(elements[0], Is.TypeOf(typeof(Table))); - - var rows = elements[0].Elements(); - Assert.That(rows.Count(), Is.EqualTo(1)); - } - - [Test(Description = "Second row does not contains complete number of cells")] - public void RowWithNoCell_ReturnsCompletelyFilledRow() - { - var elements = converter.Parse(@" - - - -
Cell 1.1Cell 1.2Cell 1.3
Cell 2.1
"); - Assert.That(elements, Has.Count.EqualTo(1)); - 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(3), - "All rows should have the same number of cells"); - } - - [Test(Description = "Respect the order header-body-footer even if provided disordered")] - public void DisorderedTableParts_ReturnsOrderedTable () - { - // table parts should be reordered - var elements = converter.Parse(@"
- - - -
Body
Header
Footer
"); - - Assert.That(elements, Has.Count.EqualTo(1)); - Assert.That(elements[0], Is.TypeOf(typeof(Table))); - - var rows = elements[0].Elements(); - Assert.That(rows.Count(), Is.EqualTo(3)); - using (Assert.EnterMultipleScope()) - { - Assert.That(rows.ElementAt(0).InnerText, Is.EqualTo("Header")); - Assert.That(rows.ElementAt(1).InnerText, Is.EqualTo("Body")); - Assert.That(rows.ElementAt(2).InnerText, Is.EqualTo("Footer")); - } - } - - [TestCase(2u, 2)] - [TestCase(1u, null)] - [TestCase(0u, null)] - public void ColSpan_ReturnsGridSpan(uint colSpan, int? expectedColSpan) - { - var elements = converter.Parse(@$" - - {"".Repeat(Math.Max(1, colSpan))} -
Cell 1.1
Cell
"); - Assert.That(elements, Has.Count.EqualTo(1)); - Assert.That(elements, Has.All.TypeOf()); - var rows = elements[0].Elements(); - Assert.That(rows.Count(), Is.EqualTo(2)); - - using (Assert.EnterMultipleScope()) - { - Assert.That(rows.First().GetFirstChild()? - .TableCellProperties?.GetFirstChild()?.Val?.Value, Is.EqualTo(expectedColSpan), - $"Expected GridSpan={expectedColSpan}"); - Assert.That(rows.First().Elements().Count(), Is.EqualTo(1), - "1st row should contain only 1 cell"); - Assert.That(rows.Last().Elements().Count(), Is.EqualTo(Math.Max(1, colSpan)), - $"2nd row should contains {Math.Max(1, colSpan)} cells"); - } - } - - [Test(Description = "rowSpan=0 should extend on all rows")] - public void RowSpanZero_ReturnsExtendedToAllRows() - { - var elements = converter.Parse(@"
- - - - - - - - -
Cell 1.1Cell 1.2Cell 1.3
Cell 2.2Cell 2.3
Cell 3.2Cell 3.3
Cell 4.1Cell 4.2Cell 4.3
"); - Assert.That(elements, Has.Count.EqualTo(1)); - Assert.That(elements, Has.All.TypeOf()); - var rows = elements[0].Elements().ToArray(); - Assert.That(rows, Has.Length.EqualTo(4)); - using (Assert.EnterMultipleScope()) - { - Assert.That(rows.Select(r => r.Elements().Count()), - Has.All.EqualTo(3), - "All rows should have the same number of cells"); - Assert.That(rows[0].GetFirstChild()?.TableCellProperties? - .VerticalMerge?.Val?.Value, Is.EqualTo(MergedCellValues.Restart)); - Assert.That(rows[1].GetFirstChild()?.TableCellProperties? - .VerticalMerge?.Val?.Value, Is.EqualTo(MergedCellValues.Continue)); - Assert.That(rows[2].GetFirstChild()?.TableCellProperties? - .VerticalMerge?.Val?.Value, Is.EqualTo(MergedCellValues.Continue)); - Assert.That(rows[3].GetFirstChild()?.TableCellProperties? - .VerticalMerge?.Val?.Value, Is.Null, - "Row on tfoot should not continue the span"); - } - } - - [Test] - public void RowSpan_ReturnsVerticalMerge() - { - var elements = converter.Parse(@"
- - - -
Cell 1.1Cell 1.2Cell 1.3
Cell 2.1Cell 2.2Cell 2.3
Cell 3.1Cell 3.3
"); - Assert.That(elements, Has.Count.EqualTo(1)); - Assert.That(elements, Has.All.TypeOf()); - var rows = elements[0].Elements(); - Assert.That(rows.Count(), Is.EqualTo(3)); - Assert.That(rows.Select(r => r.Elements().Count()), - Has.All.EqualTo(3), - "All rows should have the same number of cells"); - - Assert.That(rows.ElementAt(1).Elements().ElementAt(1)?.TableCellProperties?.VerticalMerge?.Val?.Value, Is.EqualTo(MergedCellValues.Restart)); - Assert.That(rows.ElementAt(2).Elements().ElementAt(1)?.TableCellProperties?.VerticalMerge?.Val?.Value, Is.EqualTo(MergedCellValues.Continue)); - } - - [Test] - public void RowAndColumnSpan_ReturnsVerticalMergeAndGridSpan() - { - var elements = converter.Parse(@"
- - - -
Cell 1.1Cell 1.3
Cell 2.3
Cell 3.1Cell 3.2Cell 3.3
"); - Assert.That(elements, Has.Count.EqualTo(1)); - Assert.That(elements, Has.All.TypeOf()); - var rows = elements[0].Elements(); - Assert.That(rows.Count(), Is.EqualTo(3)); - Assert.That(rows.Take(2).Select(r => r.Elements().Count()), - Has.All.EqualTo(2), - "1st and 2nd rows should have 2 cells"); - Assert.That(rows.Last().Elements().Count(), - Is.EqualTo(3), - "3rd row should have 3 cells"); - Assert.That(rows.First().GetFirstChild()?.TableCellProperties?.GridSpan?.Val?.Value, Is.EqualTo(2)); - Assert.That(rows.First().GetFirstChild()?.TableCellProperties?.VerticalMerge?.Val?.Value, Is.EqualTo(MergedCellValues.Restart)); - - Assert.That(rows.ElementAt(1).GetFirstChild()?.TableCellProperties?.GridSpan?.Val?.Value, Is.EqualTo(2)); - Assert.That(rows.ElementAt(1).GetFirstChild()?.TableCellProperties?.VerticalMerge?.Val?.Value, Is.EqualTo(MergedCellValues.Continue)); - } - - [TestCase("tb-lr", ExpectedResult = "btLr")] - [TestCase("vertical-lr", ExpectedResult ="btLr")] - [TestCase("tb-rl", ExpectedResult = "tbRl")] - [TestCase("vertical-rl", ExpectedResult = "tbRl")] - public string? VerticalText_ReturnsTableCellWithTextAlignment(string direction) - { - var elements = converter.Parse(@$"
- -
Cell 1.1
"); - Assert.That(elements, Has.Count.EqualTo(1)); - Assert.That(elements, Has.All.TypeOf()); - var rows = elements[0].Elements(); - Assert.That(rows.Count(), Is.EqualTo(1)); - Assert.That(rows.First().Elements().Count(), Is.EqualTo(1)); - var cell = rows.First().GetFirstChild(); - Assert.That(cell?.TableCellProperties?.TableCellVerticalAlignment?.Val?.Value, Is.EqualTo(TableVerticalAlignmentValues.Center)); - return cell?.TableCellProperties?.TextDirection?.Val?.InnerText; - } - - [Test(Description = "Table padding is not supported in OpenXml, only margin")] - public void CellPadding_ReturnsTableWithCellMargin() - { - var elements = converter.Parse(@$"
- -
Cell 1.1
"); - Assert.That(elements, Has.Count.EqualTo(1)); - Assert.That(elements, Has.All.TypeOf()); - var cellMargin = elements[0].GetFirstChild()?.TableCellMarginDefault; - Assert.That(cellMargin, Is.Not.Null); - - using (Assert.EnterMultipleScope()) - { - Assert.That(cellMargin.TableCellLeftMargin?.Width?.Value, Is.EqualTo(29)); - Assert.That(cellMargin.TableCellRightMargin?.Width?.Value, Is.EqualTo(29)); - Assert.That(cellMargin.TopMargin?.Width?.Value, Is.EqualTo("29")); - Assert.That(cellMargin.BottomMargin?.Width?.Value, Is.EqualTo("29")); - } - } - - [Test] - public void CellSpacing_ReturnsTableCellWithSpacing() - { - var elements = converter.Parse(@$"
- -
Cell 1.1
"); - Assert.That(elements, Has.Count.EqualTo(1)); - Assert.That(elements, Has.All.TypeOf()); - var cellSpacing = elements[0].GetFirstChild()?.TableCellSpacing; - Assert.That(cellSpacing?.Type?.Value, Is.EqualTo(TableWidthUnitValues.Dxa)); - Assert.That(cellSpacing?.Width?.Value, Is.EqualTo("29")); - } - - [TestCaseSource(nameof(BorderWidthCases))] - public void HtmlBorders_ShouldSucceed(string borderAtrribute, IEnumerable? expectedBorderValue, IEnumerable? expectedBorderWidth) - { - // we specify a style which doesn't handle borders - converter.HtmlStyles.AddStyle(new Style { - StyleId = "NoStyle", - Type = StyleValues.Table - }); - var elements = converter.Parse($@"
- -
Cell 1
"); - Assert.That(elements, Has.Count.EqualTo(1)); - Assert.That(elements, Has.All.TypeOf()); - var borders = elements[0].GetFirstChild()?.TableBorders; - if (expectedBorderValue is null) - { - Assert.That(borders, Is.Null); - return; - } - - Assert.That(borders, Is.Not.Null); - Assert.That(borders.HasChild(), Is.True); - Assert.That(new string?[] { borders.TopBorder?.Val?.InnerText, - borders.LeftBorder?.Val?.InnerText, - borders.RightBorder?.Val?.InnerText, - borders.BottomBorder?.Val?.InnerText, - borders.InsideHorizontalBorder?.Val?.InnerText, - borders.InsideVerticalBorder?.Val?.InnerText }, - Is.EquivalentTo(expectedBorderValue)); - - if (expectedBorderWidth is null) - { - Assert.That(borders.Elements().Any(b => b.Size?.HasValue == true), Is.False); - } - else - { - Assert.That(new uint?[] { borders.TopBorder?.Size?.Value, - borders.LeftBorder?.Size?.Value, - borders.RightBorder?.Size?.Value, - borders.BottomBorder?.Size?.Value, - borders.InsideHorizontalBorder?.Size?.Value, - borders.InsideVerticalBorder?.Size?.Value }, - Is.EquivalentTo(expectedBorderWidth)); - } - } - - static readonly object[] BorderWidthCases = - [ - // unset border <> border=0 - new object[] { "", null!, null! }, - // Negative border should be considered as zero - new object[] { "border='-1'", - new string[] { "none", "none", "none", "none", "none", "none" }, null! }, - new object[] { "border='0'", - new string[] { "none", "none", "none", "none", "none", "none" }, null! }, - new object[] { "border='1'", - new string[] { "none", "none", "none", "none", "single", "single" }, - new uint?[] { null, null, null, null, 14, 14 } }, - new object[] { "style='border:1px;border-bottom:3px dashed'", - new string[] { "single", "single", "single", "dashed", null!, null! }, - new uint?[] { 6, 6, 6, 18, null, null } } - ]; - - [TestCase("above", 0, 1)] - [TestCase("below", 1, 0)] - public void TableCaption_ReturnsPositionedParagraph(string position, int captionPos, int tablePos) - { - converter.TableCaptionPosition = new (position); - var elements = converter.Parse(@$"
- - -
Some table caption
Cell 1.1
"); - Assert.That(elements, Has.Count.EqualTo(2)); - Assert.That(elements[captionPos], Is.TypeOf()); - Assert.That(elements[tablePos], Is.TypeOf()); - var p = (Paragraph) elements[captionPos]; - var runs = p.Elements(); - Assert.That(runs.Count(), Is.AtLeast(4)); - - using (Assert.EnterMultipleScope()) - { - Assert.That(p.ParagraphProperties?.ParagraphStyleId?.Val?.Value, Is.EqualTo(converter.HtmlStyles.DefaultStyles.CaptionStyle)); - Assert.That(runs.First().HasChild(), Is.True); - Assert.That(runs.ElementAt(1).HasChild(), Is.True); - Assert.That(runs.ElementAt(2).HasChild(), Is.True); - } - using (Assert.EnterMultipleScope()) - { - Assert.That(runs.First().GetFirstChild()?.FieldCharType?.Value, Is.EqualTo(FieldCharValues.Begin)); - Assert.That(runs.ElementAt(1).GetFirstChild()?.InnerText, Is.EqualTo("SEQ TABLE \\* ARABIC")); - Assert.That(runs.ElementAt(2).GetFirstChild()?.FieldCharType?.Value, Is.EqualTo(FieldCharValues.End)); - Assert.That(runs.Last().InnerText, Is.EqualTo(" Some table caption")); - } - } - - [TestCase("right", ExpectedResult = "right")] - [TestCase("", ExpectedResult = "center")] - public string? TableCaptionAlign_ReturnsPositionedParagraph_AlignedWithTable(string alignment) - { - var elements = converter.Parse(@$"
- - -
Some table caption
Cell 1.1
"); - - Assert.That(elements, Has.Count.EqualTo(2)); - var caption = (Paragraph) elements[1]; - return caption.ParagraphProperties?.Justification?.Val?.ToString(); - } - - [TestCase("align='right'", ExpectedResult = "right")] - [TestCase("style='justify-self:center'", ExpectedResult = "center")] - [TestCase("style='margin-left:auto'", ExpectedResult = "right")] - [TestCase("style='margin-left:auto;margin-right:auto'", ExpectedResult = "center")] - public string? TableAlign_ReturnsTableJustification(string style) - { - var elements = converter.Parse(@$" - -
Cell 1.1
"); - - Assert.That(elements, Has.Count.EqualTo(1)); - return elements[0].GetFirstChild()?.TableJustification?.Val?.ToString(); - } - - [TestCase("", ExpectedResult = "right")] - [TestCase("justify-self:center", ExpectedResult = "center")] - public string? NestedTableAlign_ReturnsTableOrParentJustification(string tableStyle) - { - var elements = converter.Parse(@$"
- - -
Cell 1.1
-
"); - - Assert.That(elements, Has.Count.EqualTo(1)); - return elements[0].GetFirstChild()?.TableJustification?.Val?.ToString(); - } - - [Test] - public void EmptyTableCaption_ShouldBeIgnored() - { - var elements = converter.Parse(@$" - - -
Cell 1.1
"); - Assert.That(elements, Has.Count.EqualTo(1)); - Assert.That(elements[0], Is.TypeOf()); - } - - [Test] - public void PreAsTable_ReturnsTableWithPreservedWhitespaces() - { - const string preformattedText = @" - ^__^ - (oo)\_______ - (__)\ )\/\ - ||----w | - || ||"; - - converter.RenderPreAsTable = true; - var elements = converter.Parse(@$" -
-{preformattedText}
"); - Assert.That(elements, Has.Count.EqualTo(1)); - Assert.That(elements, Has.All.TypeOf
()); - var tableProps = elements[0].GetFirstChild(); - Assert.That(tableProps, Is.Not.Null); - using (Assert.EnterMultipleScope()) - { - Assert.That(tableProps.GetFirstChild()?.Val?.Value, Is.EqualTo(converter.HtmlStyles.DefaultStyles.PreTableStyle)); - Assert.That(tableProps.GetFirstChild()?.Type?.Value, Is.EqualTo(TableWidthUnitValues.Auto)); - Assert.That(tableProps.GetFirstChild()?.Width?.Value, Is.EqualTo("0")); - } - - var rows = elements[0].Elements(); - Assert.That(rows.Count(), Is.EqualTo(1)); - var cells = rows.First().Elements(); - Assert.That(cells.Count(), Is.EqualTo(1)); - var cell = cells.First(); - using (Assert.EnterMultipleScope()) - { - Assert.That(cell.TableCellProperties?.TableCellBorders?.ChildElements.Count(), Is.EqualTo(4)); - Assert.That(cell.TableCellProperties?.TableCellBorders?.ChildElements, Has.All.InstanceOf()); - Assert.That(cell.TableCellProperties?.TableCellBorders?.Elements().All(b => b.Val?.Value == BorderValues.Single), Is.True); - } - - var run = cell.GetFirstChild()?.GetFirstChild(); - Assert.That(run, Is.Not.Null); - using (Assert.EnterMultipleScope()) - { - var odds = run.ChildElements.Where((item, index) => index % 2 != 0); - Assert.That(odds, Has.All.TypeOf()); - Assert.That(run.ChildElements.ElementAt(0).InnerText, Is.EqualTo(" ^__^")); - Assert.That(run.ChildElements.ElementAt(2).InnerText, Is.EqualTo(" (oo)\\_______")); - Assert.That(run.ChildElements.ElementAt(4).InnerText, Is.EqualTo(" (__)\\ )\\/\\")); - Assert.That(run.ChildElements.ElementAt(6).InnerText, Is.EqualTo(" ||----w |")); - Assert.That(run.ChildElements.ElementAt(8).InnerText, Is.EqualTo(" || ||")); - } - } - - [Test] - public void RowStyle_ReturnsRunCellsWithCascadedStyle() - { - var elements = converter.Parse(@$"
- -
Cell
"); - Assert.That(elements, Has.Count.EqualTo(1)); - Assert.That(elements, Has.All.TypeOf()); - - var row = elements[0].GetFirstChild(); - Assert.That(row, Is.Not.Null); - Assert.That(row.TableRowProperties?.GetFirstChild()?.Val?.Value, Is.EqualTo(1800)); - - var cell = row.GetFirstChild(); - Assert.That(cell, Is.Not.Null); - Assert.That(cell.TableCellProperties, Is.Not.Null); - Assert.That(cell.TableCellProperties.Shading?.Fill?.Value, Is.EqualTo("C0C0C0")); - - var runProperties = cell.GetFirstChild()?.GetFirstChild()?.RunProperties; - Assert.That(runProperties?.Shading, Is.Null); - } - - [Test(Description = "Ancestor block background-color must not paint table cell runs")] - public void ParentDivBackground_ShouldNotCascadeIntoCell() - { - var elements = converter.Parse(@"
-
Cell
- "); - Assert.That(elements, Has.Count.EqualTo(1)); - Assert.That(elements, Is.All.TypeOf()); - - var cell = elements[0].GetFirstChild()?.GetFirstChild(); - Assert.That(cell, Is.Not.Null); - var runProperties = cell.GetFirstChild()?.GetFirstChild()?.RunProperties; - Assert.That(runProperties, Is.Null); - } - - [Test(Description = "Explicit span background inside a cell is kept even when a parent div has a fill")] - public void ParentDivBackground_SpanInCell_KeepsOwnShading() - { - var elements = converter.Parse(@"
-
Cell
- "); - - var cell = elements[0].GetFirstChild()?.GetFirstChild(); - var runProperties = cell?.GetFirstChild()?.GetFirstChild()?.RunProperties; - Assert.That(runProperties?.Shading?.Fill?.Value, Is.EqualTo("FFFF00")); - } - - [Test(Description = "Background on a div inside a cell still applies to the run")] - public void InnerDivBackground_InsideCell_StillCascadesToRun() - { - var elements = converter.Parse(@"
-
Cell
-
"); - - var cell = elements[0].GetFirstChild()?.GetFirstChild(); - var runProperties = cell?.GetFirstChild()?.GetFirstChild()?.RunProperties; - Assert.That(runProperties?.Shading?.Fill?.Value, Is.EqualTo("00FF00")); - } - - [Test] - public void CellStyle_ReturnsRunWithCascadeStyle() - { - var elements = converter.Parse(@$" - -
Cell
"); - Assert.That(elements, Has.Count.EqualTo(1)); - Assert.That(elements, Has.All.TypeOf()); - var cell = elements[0].GetFirstChild()?.GetFirstChild(); - Assert.That(cell, Is.Not.Null); - var runProperties = cell.GetFirstChild()?.GetFirstChild()?.RunProperties; - Assert.That(runProperties, Is.Not.Null); - using (Assert.EnterMultipleScope()) - { - Assert.That(runProperties.Bold, Is.Not.Null); - Assert.That(runProperties.Italic, Is.Not.Null); - } - using (Assert.EnterMultipleScope()) - { - // normally, Val should be null - if (runProperties.Bold.Val is not null) - Assert.That(runProperties.Bold.Val, Is.True); - if (runProperties.Italic.Val is not null) - Assert.That(runProperties.Italic.Val, Is.True); - } - } - - [Test] - public void NestedTable_ReturnsTableInsideTable() - { - var elements = converter.Parse(@$"
- -
-
Cell
-
"); - Assert.That(elements, Has.Count.EqualTo(1)); - Assert.That(elements, Has.All.TypeOf()); - Assert.That(elements[0].GetFirstChild()?.Elements().Count(), Is.EqualTo(1)); - var cell = elements[0].GetFirstChild()?.GetFirstChild(); - Assert.That(cell, Is.Not.Null); - using (Assert.EnterMultipleScope()) - { - Assert.That(cell.HasChild
(), Is.True); - Assert.That(cell.HasChild(), Is.True, "Word requires at least a paragraph"); - Assert.That(cell.LastChild, Is.TypeOf(), "Word disallow to ends a cell with a Table"); - } - } - - [Test] - public void Colstyle_ReturnsStyleAppliedOnCell() - { - var elements = converter.Parse(@$"
- - - - - -
Cell 1.1Cell 1.2
"); - - Assert.That(elements, Has.Count.EqualTo(1)); - Assert.That(elements, Has.All.TypeOf()); - var columns = elements[0].GetFirstChild()?.Elements(); - Assert.That(columns, Is.Not.Null); - using (Assert.EnterMultipleScope()) - { - Assert.That(columns.Count(), Is.EqualTo(2)); - Assert.That(columns.First().Width?.Value, Is.EqualTo("1500")); - Assert.That(columns.Last().Width?.Value, Is.EqualTo("750")); - } - - var cells = elements[0].GetFirstChild()?.Elements(); - Assert.That(cells, Is.Not.Null); - using (Assert.EnterMultipleScope()) - { - Assert.That(cells.Count(), Is.EqualTo(2)); - Assert.That(cells.First().TableCellProperties?.TableCellBorders, Is.Null); - Assert.That(cells.Last().TableCellProperties?.TableCellBorders, Is.Not.Null); - } - } - - [Test] - public void ColWithSpan_ReturnsStyleAppliedOnMultipleCells() - { - var elements = converter.Parse(@$"
- - - - - -
Cell 1.1Cell 1.2Cell 1.3
"); - - Assert.That(elements, Has.Count.EqualTo(1)); - Assert.That(elements, Has.All.TypeOf()); - var columns = elements[0].GetFirstChild()?.Elements(); - Assert.That(columns, Is.Not.Null); - using (Assert.EnterMultipleScope()) - { - Assert.That(columns.Count(), Is.EqualTo(3)); - //Assert.That(columns.First().Width?.Value, Is.EqualTo("1500")); - //Assert.That(columns.ElementAt(1).Width?.Value, Is.EqualTo("1500")); - //Assert.That(columns.Last().Width?.Value, Is.EqualTo("750")); - } - - var cells = elements[0].GetFirstChild()?.Elements(); - Assert.That(cells, Is.Not.Null); - using (Assert.EnterMultipleScope()) - { - Assert.That(cells.Count(), Is.EqualTo(3)); - Assert.That(cells.First().GetFirstChild()?.ParagraphProperties?.Justification?.Val?.Value, Is.EqualTo(JustificationValues.Right)); - Assert.That(cells.ElementAt(1).GetFirstChild()?.ParagraphProperties?.Justification?.Val?.Value, Is.EqualTo(JustificationValues.Right)); - Assert.That(cells.Last().GetFirstChild()?.ParagraphProperties?.Justification?.Val, Is.Null); - } - } - - [Test(Description = "Table row contains more cell than specified col")] - public void IncompleteColStyle_ShouldNotThrow() - { - Assert.DoesNotThrow(() => converter.Parse(@$"
- - - - -
Cell 1.1Cell 1.2
")); - } - - [Test(Description = "Cell with multiple runs")] - public void CellWithMultipleDivs_ReturnsOneCellWithMultipleParagraphs() - { - var elements = converter.Parse(@$" - -
Cell
1.1
"); - - Assert.That(elements, Has.Count.EqualTo(1)); - Assert.That(elements, Has.All.TypeOf()); - var cells = elements[0].GetFirstChild()?.Elements(); - Assert.That(cells?.Count(), Is.EqualTo(1)); - Assert.That(cells.First().Elements().Count(), Is.EqualTo(2)); - } - - [Test(Description = "Prevent Word to merge two consecutive tables")] - public void ConsecutiveTables_ReturnsTablesWithPlaceholderParagraphInBetween() - { - var elements = converter.Parse(@" -
Table 1
-
Table 2
"); - Assert.That(elements, Has.Count.EqualTo(3)); - using (Assert.EnterMultipleScope()) - { - Assert.That(elements[0], Is.TypeOf()); - Assert.That(elements[1], Is.TypeOf()); - Assert.That(elements[2], Is.TypeOf
()); - } - } - - [Test(Description = "Insert the empty paragraph on right location, based on combinated rowSpan and colSpan #59")] - public void DoubleRowSpanSameLine_ShouldSucceed() - { - var elements = converter.Parse(@"
- - - - - - - - -
Cell 1.1Cell 1.2Cell 1.3
Cell 2.2
"); - - Assert.That(elements, Has.Count.EqualTo(1)); - Assert.That(elements, Has.All.TypeOf()); - Assert.That(elements[0].GetFirstChild()?.Elements().Count(), Is.EqualTo(4)); - - var rows = elements[0].Elements(); - Assert.That(rows.Count(), Is.EqualTo(2)); - Assert.That(rows.Select(r => r.Elements().Count()), - Has.All.EqualTo(3), - "All should have 3 cells"); - Assert.That(rows.First().GetFirstChild()?.TableCellProperties?.GridSpan?.Val?.Value, Is.EqualTo(2)); - Assert.That(rows.First().GetFirstChild()?.TableCellProperties?.VerticalMerge?.Val?.Value, Is.EqualTo(MergedCellValues.Restart)); - Assert.That(rows.First().GetLastChild()?.TableCellProperties?.VerticalMerge?.Val?.Value, Is.EqualTo(MergedCellValues.Restart)); - - Assert.That(rows.ElementAt(1).GetFirstChild()?.TableCellProperties?.GridSpan?.Val?.Value, Is.EqualTo(2)); - Assert.That(rows.ElementAt(1).GetFirstChild()?.TableCellProperties?.VerticalMerge?.Val?.Value, Is.EqualTo(MergedCellValues.Continue)); - Assert.That(rows.ElementAt(1).GetLastChild()?.TableCellProperties?.VerticalMerge?.Val?.Value, Is.EqualTo(MergedCellValues.Continue)); - } - - [Test(Description = "Cell borders should not be applied on inner runs #156")] - public void CellBorders_ShouldNotPropagate_OnRuns() - { - var elements = converter.Parse(@"
- - - -
Placeholder
"); - - Assert.That(elements, Has.Count.EqualTo(1)); - Assert.That(elements, Has.All.TypeOf()); - var cells = elements[0].GetFirstChild()?.Elements(); - Assert.That(cells?.Count(), Is.EqualTo(1)); - Assert.That(cells.First().TableCellProperties?.TableCellBorders, Is.Not.Null); - var paragraphs = cells.First().Elements(); - Assert.That(paragraphs.Count(), Is.EqualTo(1)); - var runs = paragraphs.First().Elements(); - Assert.That(runs.Count(), Is.EqualTo(1)); - Assert.That(runs.First().RunProperties?.Border, Is.Null); - } - - [TestCase("100%", "pct", Expressions.BlockElementExpression.FullPageWidthPct)] - [TestCase("auto", "auto", "0")] - [TestCase("120px", "dxa", "1800")] - [TestCase("", "pct", Expressions.BlockElementExpression.FullPageWidthPct, Description = "Defaults to 100%")] - public void Width_ReturnsRefineTableWidth(string width, string expectedUnit, string expectedValue) - { - var elements = converter.Parse(@$"
- -
Placeholder
"); - - Assert.That(elements, Has.Count.EqualTo(1)); - Assert.That(elements, Has.All.TypeOf()); - var tableWidth = elements[0].GetFirstChild()?.TableWidth; - Assert.That(tableWidth, Is.Not.Null); - using (Assert.EnterMultipleScope()) - { - Assert.That(tableWidth?.Type?.Value, Is.EqualTo(new TableWidthUnitValues(expectedUnit))); - Assert.That(tableWidth?.Width?.Value, Is.EqualTo(expectedValue)); - } - } - - [Test] - public void ColWithPercentWidth_ReturnsRefineTableWidth() - { - var elements = converter.Parse(@"
- - - - - - - -
Cell 1Cell 2
"); - - Assert.That(elements, Has.Count.EqualTo(1)); - Assert.That(elements, Has.All.TypeOf()); - var tableWidth = elements[0].GetFirstChild()?.TableWidth; - Assert.That(tableWidth, Is.Not.Null); - using (Assert.EnterMultipleScope()) - { - Assert.That(tableWidth?.Type?.Value, Is.EqualTo(TableWidthUnitValues.Pct)); - Assert.That(tableWidth?.Width?.Value, Is.EqualTo("3750")); - } - - var columns = elements[0].GetFirstChild()?.Elements(); - Assert.That(columns, Is.Not.Null); - using (Assert.EnterMultipleScope()) - { - Assert.That(columns.Count(), Is.EqualTo(2)); - Assert.That(columns.First().Width?.Value, Is.EqualTo("1269")); - Assert.That(columns.Last().Width?.Value, Is.EqualTo("8365")); - } - - var cells = elements[0].GetFirstChild()?.Elements(); - Assert.That(cells, Is.Not.Null); - using (Assert.EnterMultipleScope()) - { - Assert.That(cells.Count(), Is.EqualTo(2)); - // width on cell are on 5000 basis - Assert.That(cells.First().TableCellProperties?.TableCellWidth?.Width?.Value, Is.EqualTo("659")); - Assert.That(cells.Last().TableCellProperties?.TableCellWidth?.Width?.Value, Is.EqualTo("4346")); - } - } - - [Test] - public void CellPadding_ReturnsTableCellMargin() - { - var elements = converter.Parse(@"
- - - - -
Cell 1Cell 2
"); - - Assert.That(elements, Has.Count.EqualTo(1)); - Assert.That(elements, Has.All.TypeOf()); - - var cells = elements[0].GetFirstChild()?.Elements(); - Assert.That(cells, Is.Not.Null); - using (Assert.EnterMultipleScope()) - { - Assert.That(cells.Count(), Is.EqualTo(2)); - Assert.That(cells.First().TableCellProperties?.TableCellMargin, Is.Not.Null); - Assert.That(cells.Last().TableCellProperties?.TableCellMargin, Is.Null, - "Only fixed unit are supported"); - } - - var cellMargin = cells.First().TableCellProperties?.TableCellMargin; - using (Assert.EnterMultipleScope()) - { - Assert.That(cellMargin.LeftMargin?.Width?.Value, Is.EqualTo("75")); - Assert.That(cellMargin.RightMargin?.Width?.Value, Is.EqualTo("75")); - Assert.That(cellMargin.TopMargin?.Width?.Value, Is.EqualTo("300")); - Assert.That(cellMargin.BottomMargin?.Width?.Value, Is.EqualTo("300")); - } - } - - [Test] - public void CellWidth_UsesLegacyWidthAttributeWithoutUnit() - { - var elements = converter.Parse(@"
- - - - -
Cell 1Cell 2
"); - - Assert.That(elements, Has.Count.EqualTo(1)); - Assert.That(elements, Has.All.TypeOf()); - - var cells = elements[0].GetFirstChild()?.Elements(); - Assert.That(cells, Is.Not.Null); - - using (Assert.EnterMultipleScope()) - { - Assert.That(cells.Count(), Is.EqualTo(2)); - Assert.That(cells.First().TableCellProperties?.TableCellWidth, Is.Not.Null); - Assert.That(cells.Last().TableCellProperties?.TableCellWidth, Is.Not.Null); - } - - var firstWidth = cells.First().TableCellProperties?.TableCellWidth; - var lastWidth = cells.Last().TableCellProperties?.TableCellWidth; - - using (Assert.EnterMultipleScope()) - { - Assert.That(firstWidth?.Width?.Value, Is.EqualTo("150")); - Assert.That(lastWidth?.Width?.Value, Is.EqualTo("1350")); - } - } - - [Test] - public void CellWidth_UsesLegacyWidthAttributeWithPercentage() - { - var elements = converter.Parse(@"
- - - - -
Cell 1Cell 2
"); - - Assert.That(elements, Has.Count.EqualTo(1)); - Assert.That(elements, Has.All.TypeOf()); - - var cells = elements[0].GetFirstChild()?.Elements(); - Assert.That(cells, Is.Not.Null); - - using (Assert.EnterMultipleScope()) - { - Assert.That(cells.Count(), Is.EqualTo(2)); - Assert.That(cells.First().TableCellProperties?.TableCellWidth, Is.Not.Null); - Assert.That(cells.Last().TableCellProperties?.TableCellWidth, Is.Not.Null); - } - - var firstWidth = cells.First().TableCellProperties?.TableCellWidth; - var lastWidth = cells.Last().TableCellProperties?.TableCellWidth; - - using (Assert.EnterMultipleScope()) - { - Assert.That(firstWidth?.Width?.Value, Is.EqualTo("500")); - Assert.That(lastWidth?.Width?.Value, Is.EqualTo("4500")); - } - } - } -} diff --git a/test/HtmlToOpenXml.Tests/Utilities/MockHttpMessageHandler.cs b/test/HtmlToOpenXml.Tests/Utilities/MockHttpMessageHandler.cs index f964b44c..d2bb98b5 100644 --- a/test/HtmlToOpenXml.Tests/Utilities/MockHttpMessageHandler.cs +++ b/test/HtmlToOpenXml.Tests/Utilities/MockHttpMessageHandler.cs @@ -1,35 +1,35 @@ -/* - * Copyright (c) 2017 Deal Stream sàrl. All rights reserved +/* Copyright (C) Olivier Nizet https://github.com/onizet/html2openxml + * Licensed under the MIT License. + * Please see the LICENSE file in the project root fo full license information */ using Moq; using Moq.Protected; using System.Net.Http; -namespace HtmlToOpenXml.Tests +namespace HtmlToOpenXml.Tests; + +public class MockHttpMessageHandler { - public class MockHttpMessageHandler - { - private readonly Mock mockMessageHandler; + private readonly Mock mockMessageHandler; - public MockHttpMessageHandler() - { - mockMessageHandler = new Mock(); - mockMessageHandler.Protected() - .Setup>("SendAsync", ItExpr.IsAny(), ItExpr.IsAny()) - .ReturnsAsync(new HttpResponseMessage()); - } + public MockHttpMessageHandler() + { + mockMessageHandler = new Mock(); + mockMessageHandler.Protected() + .Setup>("SendAsync", ItExpr.IsAny(), ItExpr.IsAny()) + .ReturnsAsync(new HttpResponseMessage()); + } - public IO.IWebRequest GetWebRequest() - { - return new IO.DefaultWebRequest(new HttpClient(mockMessageHandler.Object)); - } + public IO.IWebRequest GetWebRequest() + { + return new IO.DefaultWebRequest(new HttpClient(mockMessageHandler.Object)); + } - public void AssertNeverCalled() - { - mockMessageHandler.Protected() - .Verify("SendAsync", Times.Never(), - ItExpr.IsAny(), ItExpr.IsAny()); - } + public void AssertNeverCalled() + { + mockMessageHandler.Protected() + .Verify("SendAsync", Times.Never(), + ItExpr.IsAny(), ItExpr.IsAny()); } -} \ No newline at end of file +} diff --git a/test/HtmlToOpenXml.Tests/Utilities/OpenXmlExtensions.cs b/test/HtmlToOpenXml.Tests/Utilities/OpenXmlExtensions.cs index 3167cfd2..5337caaa 100755 --- a/test/HtmlToOpenXml.Tests/Utilities/OpenXmlExtensions.cs +++ b/test/HtmlToOpenXml.Tests/Utilities/OpenXmlExtensions.cs @@ -1,13 +1,6 @@ -/* 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. +/* Copyright (C) Olivier Nizet https://github.com/onizet/html2openxml + * Licensed under the MIT License. + * Please see the LICENSE file in the project root fo full license information */ using DocumentFormat.OpenXml; diff --git a/test/HtmlToOpenXml.Tests/Utilities/ProxyHttpMessageHandler.cs b/test/HtmlToOpenXml.Tests/Utilities/ProxyHttpMessageHandler.cs index fdd08bf6..3c70b9ed 100644 --- a/test/HtmlToOpenXml.Tests/Utilities/ProxyHttpMessageHandler.cs +++ b/test/HtmlToOpenXml.Tests/Utilities/ProxyHttpMessageHandler.cs @@ -1,22 +1,22 @@ -/* - * Copyright (c) 2017 Deal Stream sàrl. All rights reserved +/* Copyright (C) Olivier Nizet https://github.com/onizet/html2openxml + * Licensed under the MIT License. + * Please see the LICENSE file in the project root fo full license information */ using System.Net.Http; -namespace HtmlToOpenXml.Tests +namespace HtmlToOpenXml.Tests; + +public class ProxyHttpMessageHandler : HttpMessageHandler { - public class ProxyHttpMessageHandler : HttpMessageHandler - { - private readonly Func> _getResponseFunc; + private readonly Func> _getResponseFunc; - public ProxyHttpMessageHandler(Func> getResponseFunc) - { - _getResponseFunc = getResponseFunc; - } + public ProxyHttpMessageHandler(Func> getResponseFunc) + { + _getResponseFunc = getResponseFunc; + } - protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) - { - return await _getResponseFunc(request.RequestUri!); - } + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + return await _getResponseFunc(request.RequestUri!); } -} \ No newline at end of file +} diff --git a/test/HtmlToOpenXml.Tests/Utilities/ResourceHelper.cs b/test/HtmlToOpenXml.Tests/Utilities/ResourceHelper.cs index d1f8ed93..9d484570 100644 --- a/test/HtmlToOpenXml.Tests/Utilities/ResourceHelper.cs +++ b/test/HtmlToOpenXml.Tests/Utilities/ResourceHelper.cs @@ -1,41 +1,41 @@ -/* - * Copyright (c) 2017 Deal Stream sàrl. All rights reserved +/* Copyright (C) Olivier Nizet https://github.com/onizet/html2openxml + * Licensed under the MIT License. + * Please see the LICENSE file in the project root fo full license information */ using System.Reflection; using System.Resources; -namespace HtmlToOpenXml.Tests +namespace HtmlToOpenXml.Tests; + +/// +/// Helper class to get an embedded resources. +/// +public static class ResourceHelper { - /// - /// Helper class to get an embedded resources. - /// - public static class ResourceHelper + public static string GetString(string resourceName) { - public static string GetString(string resourceName) - { - return GetString(typeof(ResourceHelper).GetTypeInfo().Assembly, resourceName); - } + return GetString(typeof(ResourceHelper).GetTypeInfo().Assembly, resourceName); + } - public static string GetString(Assembly assembly, string resourceName) + public static string GetString(Assembly assembly, string resourceName) + { + using (var stream = GetStream(assembly, resourceName)) { - using (var stream = GetStream(assembly, resourceName)) - { - using (var reader = new StreamReader(stream)) - return reader.ReadToEnd(); - } + using (var reader = new StreamReader(stream)) + return reader.ReadToEnd(); } + } - public static Stream GetStream(string resourceName) - { - return GetStream(typeof(ResourceHelper).GetTypeInfo().Assembly, resourceName); - } + public static Stream GetStream(string resourceName) + { + return GetStream(typeof(ResourceHelper).GetTypeInfo().Assembly, resourceName); + } - public static Stream GetStream(Assembly assembly, string resourceName) - { - var stream = assembly.GetManifestResourceStream(assembly.GetName().Name + "." + resourceName) - ?? throw new MissingManifestResourceException($"Requested resource `{resourceName}` was not found in the assembly `{assembly}`."); + public static Stream GetStream(Assembly assembly, string resourceName) + { + var stream = assembly.GetManifestResourceStream(assembly.GetName().Name + "." + resourceName) + ?? throw new MissingManifestResourceException($"Requested resource `{resourceName}` was not found in the assembly `{assembly}`."); - return stream; - } + return stream; } -} \ No newline at end of file +} diff --git a/test/HtmlToOpenXml.Tests/Utilities/StringExtensions.cs b/test/HtmlToOpenXml.Tests/Utilities/StringExtensions.cs index 2b8a4fb9..11cea578 100644 --- a/test/HtmlToOpenXml.Tests/Utilities/StringExtensions.cs +++ b/test/HtmlToOpenXml.Tests/Utilities/StringExtensions.cs @@ -1,33 +1,24 @@ -/* 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. +/* Copyright (C) Olivier Nizet https://github.com/onizet/html2openxml + * Licensed under the MIT License. + * Please see the LICENSE file in the project root fo full license information */ +namespace HtmlToOpenXml.Tests; -namespace HtmlToOpenXml.Tests +/// +/// Helper class that provide some extension methods to String. +/// +[System.Diagnostics.DebuggerStepThrough] +static class StringExtensions { - /// - /// Helper class that provide some extension methods to String. - /// - [System.Diagnostics.DebuggerStepThrough] - static class StringExtensions + public static string Repeat(this string text, uint n) { - public static string Repeat(this string text, uint n) + var textAsSpan = text.AsSpan(); + var span = new Span(new char[textAsSpan.Length * (int)n]); + for (var i = 0; i < n; i++) { - var textAsSpan = text.AsSpan(); - var span = new Span(new char[textAsSpan.Length * (int)n]); - for (var i = 0; i < n; i++) - { - textAsSpan.CopyTo(span.Slice(i * textAsSpan.Length, textAsSpan.Length)); - } - - return span.ToString(); + textAsSpan.CopyTo(span.Slice(i * textAsSpan.Length, textAsSpan.Length)); } + + return span.ToString(); } }