diff --git a/CHANGELOG.md b/CHANGELOG.md index dfde7de2..9a73d07a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,12 @@ # Changelog +## 4.3.0 + +- New `SetTableOfContent()` helper. +- New `SetCoverPage()` helper. +- New `AddPage(orientation, paperSize)` helper. +- New `AddPageBreakBefore` and `AddPageBreakAfter` helper. + ## 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/README.md b/README.md index d3691712..d85cc452 100644 --- a/README.md +++ b/README.md @@ -8,11 +8,35 @@ 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 + +- HTML → DOCX conversion +- Word template integration +- Cover pages +- Native Word table of contents generation +- 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 +- Markdown support (optional package) +- CSS stylesheet support (optional package) + +Supports **.NET Framework 4.6.2**, **.NET Standard 2.0**, **.NET 8** and **.NET 10**. Built on top of [DocumentFormat.OpenXml](https://www.nuget.org/packages/DocumentFormat.OpenXml/) and [AngleSharp](https://www.nuget.org/packages/AngleSharp). --> [Official Nuget Package](https://www.nuget.org/packages/HtmlToOpenXml) (❗ **Update your bookmark**, suffix `.dll` removed) +| 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/) | +| [HtmlToOpenXml.Markdown](https://www.nuget.org/packages/HtmlToOpenXml.Markdown/) | [![HtmlToOpenXml.Markdown](https://img.shields.io/nuget/v/HtmlToOpenXml.Markdown.svg)](https://www.nuget.org/packages/HtmlToOpenXml.Markdown/) | [![HtmlToOpenXml.Markdown](https://img.shields.io/nuget/dt/HtmlToOpenXml.Markdown.svg)](https://www.nuget.org/packages/HtmlToOpenXml.Markdown/) | + +> **Note** +> The package was renamed from `HtmlToOpenXml.dll` to `HtmlToOpenXml`. +> NuGet download statistics were unfortunately not transferred to the new package. ## Quick Start @@ -20,13 +44,13 @@ When creating a blank document: ```csharp await using var generatedDocument = new MemoryStream(); -using var package = WordprocessingDocument.Create(generatedDocument, WordprocessingDocumentType.Document); +using var package = WordDocumentFactory.Create(generatedDocument); HtmlConverter converter = new(package); await converter.ParseBody(html); ``` -When inserting inside an existing document: +Using an existing template: ```csharp await using var generatedDocument = new MemoryStream(); @@ -37,46 +61,67 @@ HtmlConverter converter = new(package); await converter.ParseBody(html); ``` +Advanced document features: + +```csharp +await converter.SetCoverPage("

Annual Report 2026

"); + +converter.AddPage(PageOrientation.Landscape); +await converter.ParseBody(wideTableHtml); + +// generate the TOC after all document headings have been created +var toc = converter.SetTableOfContents(); +converter.AddPageBreakAfter(toc); +``` + ## Documentation [**Documentation**](https://onizet.github.io/html2openxml/) covers from the minimal code to advanced scenarios. ### Guides & Tutorials -* [Getting Started Guide](https://onizet.github.io/html2openxml/guide/quickstart.md) -* [LLM Guidance](https://onizet.github.io/html2openxml/llmdoc.md) +- [Getting Started Guide](https://onizet.github.io/html2openxml/guide/quickstart.md) +- [LLM Guidance](https://onizet.github.io/html2openxml/llmdoc.md) ### API Reference -* [API Contract](https://onizet.github.io/html2openxml/guide/api.md) +- [API Contract](https://onizet.github.io/html2openxml/guide/api.md) + +### Document Structure + +- [Cover Pages and Table of Contents](https://onizet.github.io/html2openxml/guide/document-layout.md) ### Technical Deep Dive -* [Numbering List](https://onizet.github.io/html2openxml/guide/numbering.md) -* [Advanced Table Structures (Row/ColSpan, ColGroup)](https://onizet.github.io/html2openxml/guide/tables.md) -* [Image Processing](https://onizet.github.io/html2openxml/guide/images.md) -* [CSS Stylesheet support](https://onizet.github.io/html2openxml/guide/styling.html#note-on-external-css) -* [Performance notes and memory allocations](https://onizet.github.io/html2openxml/appendix/performance.md) +- [List Numbering](https://onizet.github.io/html2openxml/guide/numbering.md) +- [Advanced Tables (RowSpan, ColSpan, ColGroup)](https://onizet.github.io/html2openxml/guide/tables.md) +- [Image Processing](https://onizet.github.io/html2openxml/guide/images.md) +- [CSS Stylesheet support](https://onizet.github.io/html2openxml/guide/styling.html#note-on-external-css) +- [Performance notes and memory allocations](https://onizet.github.io/html2openxml/appendix/performance.md) ## How to implement or debug features -My reference bibles cover both OpenXml and HTML: +Useful references for both OpenXML and HTML: -* [MDN](https://developer.mozilla.org/en-US/docs/Web/HTML) -* [W3Schools](https://www.w3schools.com/html/default.asp) -* [OpenXml MSDN](https://learn.microsoft.com/en-us/dotnet/api/documentformat.openxml.wordprocessing?view=openxml-3.0.1) +- [MDN](https://developer.mozilla.org/en-US/docs/Web/HTML) +- [W3Schools](https://www.w3schools.com/html/default.asp) +- [OpenXml MSDN](https://learn.microsoft.com/en-us/dotnet/api/documentformat.openxml.wordprocessing?view=openxml-3.0.1) -Open MS Word or Apple Pages and design your expected output. Save as a DOCX file, then rename as a ZIP. Extract the content and inspect those files: +Open Microsoft Word and design your expected output. Save as a DOCX file, then rename as a ZIP. Extract the content and inspect those files: `document.xml`, `numbering.xml` (for list) and `styles.xml`. ## Acknowledgements -Thank you to all contributors that share their bug fixes (in no particular order): scwebgroup, ddforge, daviderapicavoli, worstenbrood, jodybullen, BenBurns, OleK, scarhand, imagremlin, antgraf, mdeclercq, pauldbentley, xjpmauricio, jairoXXX, giorand, bostjanKlemenc, AaronLS, taishmanov, AyUsH18102001. +Thank you to all contributors that share their bug fixes (in no particular order): scwebgroup, ddforge, daviderapicavoli, worstenbrood, jodybullen, BenBurns, OleK, scarhand, imagremlin, antgraf, mdeclercq, pauldbentley, xjpmauricio, jairoXXX, giorand, bostjanKlemenc, AaronLS, taishmanov, AlexAbd1990, AyUsH18102001, cyril265. And thanks to David Podhola for the Nuget package. Logo provided with the permission of [Enhanced Labs Design Studio](http://www.enhancedlabs.com). ## Support -This project is open source and I do my best to support it in my spare time. I'm always happy to receive Pull Request and grateful for the time you have taken. Please target branch `dev` only. -If you have questions, don't hesitate to get in touch with me! +This project is open source and I maintain it in my spare time. + +Bug reports, feature requests, and pull requests are always welcome. +Please target the `dev` branch when submitting pull requests. + +If you have questions, don't hesitate to get in touch. diff --git a/docs/.vuepress/config.js b/docs/.vuepress/config.js index c9ec07a8..36f507d0 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', 'hyperlinks', 'images', 'styling', 'tables', 'numbering', 'document-layout', 'pre', 'footnotes', 'pagebreak', 'rtl'] }, { text: 'LLM Docs Friendly', link: '/llmdoc' }, { text: 'NuGet', link: 'https://www.nuget.org/packages/HtmlToOpenXml', ariaLabel: 'NuGet', target: '_blank' } @@ -29,8 +29,9 @@ export default defineUserConfig({ sidebar: [ { text: 'API Reference', + collapsible: true, prefix: 'guide/', - children: ['quickstart', 'api', 'hyperlinks', 'images', 'styling', 'tables', 'numbering', 'pre', 'footnotes', 'pagebreak', 'rtl'], + children: ['quickstart', 'api', 'hyperlinks', 'images', 'styling', 'tables', 'numbering', 'document-layout', 'pre', 'footnotes', 'pagebreak', 'rtl'], }, { text: 'LLM Docs Friendly', link: 'llmdoc' diff --git a/docs/.vuepress/public/nuspec-ai.txt b/docs/.vuepress/public/nuspec-ai.txt index 13e8cee8..b3c646cb 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;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." @@ -21,14 +21,22 @@ .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." + .p TOCHeading:string "Default style for the Table Of Contents heading (the caption "Table Of Contents")." +@e DocumentPosition "Defines a logical insertion point within the document." + .ev DocumentStart=0,AfterCover=1,DocumentEnd=2 @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. 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 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)." @@ -39,6 +47,20 @@ .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." +@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 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." @@ -57,6 +79,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,7 +90,15 @@ .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 AddPageBreakBefore:void(this HtmlConverter converter, OpenXmlElement? element) "Inserts a page break immediately before the specified element. When element is null, the page break is inserted at the beginning of the document." + .m AddPageBreakAfter:void(this HtmlConverter converter, OpenXmlElement? element) "Inserts a page break immediately after the specified element. When element is null, the page break is inserted at the end of the document." + .m GetCoverPage:SdtBlock?(this HtmlConverter converter) "Returns the document cover page, if one exists. The cover page is represented using a Word content control associated with the built-in Cover Page gallery." + .m SetCoverPage:Task(this HtmlConverter converter, string html, CancellationToken cancellationToken = null) "Creates or replaces the document cover page. The supplied HTML is converted using the current HtmlToOpenXml.HtmlConverter configuration and stored inside a Word cover page content control. If a cover page already exists, its content is replaced while the existing content control is preserved." + .m SetCoverPage:Task(this HtmlConverter converter, HtmlFragment fragment, CancellationToken cancellationToken = null) "Creates or replaces the document cover page. The supplied HTML is converted using the current HtmlToOpenXml.HtmlConverter configuration and stored inside a Word cover page content control. If a cover page already exists, its content is replaced while the existing content control is preserved." + .m GetTableOfContents:SdtBlock?(this HtmlConverter converter) "Returns the table of contents, if one exists. The TOC is represented using a Word content control associated with the built-in TOC gallery." + .m SetTableOfContents:SdtBlock(this HtmlConverter converter, int maxLevel = 3, string caption = "Table Of Contents", DocumentPosition position = AfterCover) "Create or updates the document table of contents. The table of contents is generated from paragraphs using Word heading styles (Heading 1 through Heading 9, see also HtmlToOpenXml.HtmlConverter.HtmlStyles) and represented as a Word content control associated with the built-in TOC gallery. If a table of contents already exists, its content is replaced." @c WordDocumentStyle "Provides style-related services used during HTML conversion. HTML class names may be mapped directly to Word styles with the same name (case insensitive). When a referenced style cannot be found, the HtmlToOpenXml.WordDocumentStyle.StyleMissing event allows it to be provisioned dynamically." .m AddStyle:void(Style style) "Adds a new style to the Word document and refreshes the converter's internal style cache. Use this method in conjunction with the HtmlToOpenXml.WordDocumentStyle.StyleMissing event to inject styles required by a template that are absent from the source document." .p DefaultStyles:DefaultStyles "Contains the default styles for new OpenXml elements, created during the conversion process." diff --git a/docs/guide/document-layout.md b/docs/guide/document-layout.md new file mode 100644 index 00000000..153ab9d6 --- /dev/null +++ b/docs/guide/document-layout.md @@ -0,0 +1,300 @@ +--- +lang: en-US +title: Document Layout +description: Generate cover pages, tables of contents, page breaks, and custom page layouts. +--- + +`HtmlToOpenXml` provides helpers for assembling professional Word documents with cover pages, tables of contents, page breaks, and mixed page orientations. + +These features integrate with Word's native document structure and can be combined with HTML conversion, templates, bookmarks, and heading styles. + +## Cover Page + +A cover page is stored as a Word content control and always appears at the beginning of the document. + +### Create or Update a Cover Page + +```csharp +HtmlConverter converter = new(mainPart); + +await converter.SetCoverPage(""" +

Annual Report 2026

+

Confidential

+"""); +``` + +If a cover page already exists, its content is replaced. + +### Retrieve the Existing Cover Page + +```csharp +var coverPage = converter.GetCoverPage(); +``` + +Returns `null` when no cover page is present. + +--- + +## Table of Contents + +`HtmlToOpenXml` can generate a native Microsoft Word table of contents from document headings. + +### Create or Update a Table of Contents + +```csharp +converter.SetTableOfContents(); +``` + +By default, the table of contents is inserted immediately after the cover page. + +### Limit the Heading Depth + +```csharp +converter.SetTableOfContents(maxLevel: 3); +``` + +This includes: + +- Heading 1 +- Heading 2 +- Heading 3 + +Headings below the specified level are ignored. + +--- + +## Positioning + +The insertion location can be controlled using the `DocumentPosition` enumeration. + +```csharp +converter.SetTableOfContents( + maxLevel: 3, + position: DocumentPosition.AfterCover); +``` + +### Available Positions + +```csharp +DocumentPosition.DocumentStart +DocumentPosition.AfterCover +DocumentPosition.DocumentEnd +``` + +| Position | Description | +|-----------|-------------| +| `DocumentStart` | Inserts the table of contents at the beginning of the document. | +| `AfterCover` | Inserts the table of contents immediately after the cover page. If no cover page exists, the TOC is inserted at the beginning of the document. | +| `DocumentEnd` | Inserts the table of contents at the end of the document. | + +--- + +## Page Breaks + +Page breaks can be inserted before or after any OpenXml element. + +### Insert a Page Break Before an Element + +```csharp +var toc = converter.SetTableOfContents(); + +converter.AddPageBreakBefore(toc); +``` + +### Insert a Page Break After an Element + +```csharp +var toc = converter.SetTableOfContents(); + +converter.AddPageBreakAfter(toc); +``` + +A common scenario is to start the report content on a new page immediately after the table of contents: + +```csharp +var toc = converter.SetTableOfContents(); + +converter.AddPageBreakAfter(toc); +``` + +--- + +## Page Orientation and Paper Size + +Documents often require a mixture of portrait and landscape pages. This is particularly useful for: + +- Wide tables +- Financial statements +- Large diagrams +- Charts +- Technical appendices + +### Add a Landscape Page + +```csharp +converter.AddPage(PageOrientation.Landscape); +``` + +### Add a Portrait Page + +```csharp +converter.AddPage(PageOrientation.Portrait); +``` + +A new page is always created, even when the requested orientation already matches the current page orientation. + +--- + +## Paper Size + +When creating a new section, a paper size can also be specified. + +```csharp +converter.AddPage( + PageOrientation.Landscape, + PaperSize.A3); +``` + +### Supported Paper Sizes + +```csharp +PaperSize.A3 +PaperSize.A4 +PaperSize.A5 +PaperSize.A6 + +PaperSize.B3 +PaperSize.B4 +PaperSize.B5 +PaperSize.B6 + +PaperSize.Letter +PaperSize.Legal +``` + +--- + +## Creating a New Document + +`WordDocumentFactory.Create()` can initialize a document using a specific paper size and orientation. + +### A4 Portrait + +```csharp +using var package = WordDocumentFactory.Create( + stream, + PageOrientation.Portrait, + PaperSize.A4); +``` + +### Letter Landscape + +```csharp +using var package = WordDocumentFactory.Create( + stream, + PageOrientation.Landscape, + PaperSize.Letter); +``` + +--- + +## Typical Annual Report Layout + +```csharp +await converter.SetCoverPage(""" +

Annual Report 2026

+"""); + +await converter.ParseBody(""" +

Executive Summary

+ +

Company Overview

+

Mission

+

Key Figures

+ +

Financial Performance

+

Revenue

+

Expenses

+

Profitability

+ +

Future Outlook

+ +

Appendices

+"""); + +// Generate the TOC after all headings have been created +var toc = converter.SetTableOfContents(); + +// Start the report body on a new page +converter.AddPageBreakAfter(toc); +``` + +Result: + +```text +Cover Page +Table of Contents +Document Content +``` + +--- + +## How Headings Are Detected + +The table of contents is generated from Word heading styles. + +The converter automatically maps: + +```html +

Introduction

+

Overview

+

Details

+``` + +to: + +```text +Heading 1 +Heading 2 +Heading 3 +``` + +Only headings whose level is less than or equal to `maxLevel` are included in the generated table of contents. + +--- + +## Hyperlinks + +Each TOC entry is generated as an internal hyperlink. + +Clicking an entry in Word navigates directly to the corresponding heading. + +Any required bookmarks are generated automatically during TOC creation. + +--- + +## Page Numbers + +`HtmlToOpenXml` intentionally does **not** generate page numbers inside table of contents entries. + +Page numbering depends on Word's layout engine and is influenced by factors such as: installed fonts, page orientation, margins, printer configuration, ... + +Because these values are not available during OpenXML generation, reliable page numbers cannot be computed in advance. + +The generated TOC therefore focuses on document navigation and heading structure. + +### Generate Page Numbers + +If page numbers are required, refresh the table of contents from Microsoft Word: + +```text +References → Update Table +``` + +or + +```text +Right-click → Update Field +``` + +Word will calculate the final page numbers and regenerate the table contents. diff --git a/src/Html2OpenXml/Collections/HtmlAttributeCollection.cs b/src/Html2OpenXml/Collections/HtmlAttributeCollection.cs index d114fded..27c92fa7 100755 --- a/src/Html2OpenXml/Collections/HtmlAttributeCollection.cs +++ b/src/Html2OpenXml/Collections/HtmlAttributeCollection.cs @@ -134,18 +134,6 @@ public bool TryGetValue(string name, out ReadOnlySpan value) return false; } - /// - /// Efficient way to determine if a style is equals to a value. - /// - public bool HasStyleEqualsTo(string name, ReadOnlySpan value) - { - if (TryGetValue(name, out var span)) - { - return span.Equals(value, StringComparison.OrdinalIgnoreCase); - } - return false; - } - /// /// Gets an attribute representing a color (named color, hexadecimal or hexadecimal /// without the preceding # character). diff --git a/src/Html2OpenXml/Configuration enum.cs b/src/Html2OpenXml/Configuration enum.cs index 27d17afa..735b58bf 100755 --- a/src/Html2OpenXml/Configuration enum.cs +++ b/src/Html2OpenXml/Configuration enum.cs @@ -14,7 +14,7 @@ namespace HtmlToOpenXml; /// /// 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. /// @@ -100,4 +100,91 @@ public enum PageOrientation /// /// Landscape -} \ No newline at end of file +} + +/// +/// Defines a logical insertion point within the document. +/// +public enum DocumentPosition +{ + /// + /// Inserts the content at the beginning of the document. + /// + DocumentStart, + /// + /// Insert the content immediately after the cover page. + /// If no cover page exists, the content is inserted at the beginning of the document. + /// + AfterCover, + /// + /// Appends the content at the end of the document. + /// + DocumentEnd +} + +/// +/// Defines the paper size used when creating new document page. +/// Sizes correspond to the standard paper formats supported by Microsoft Word and OpenXML. +/// +public enum PaperSize +{ + /// + /// ISO 216 A3 paper size (297 × 420 mm). + /// Commonly used for large diagrams, drawings, and wide reports. + /// + A3, + + /// + /// ISO 216 A4 paper size (210 × 297 mm). + /// The default paper size for most business documents. + /// + A4, + + /// + /// ISO 216 A5 paper size (148 × 210 mm). + /// Often used for booklets, manuals, and brochures. + /// + A5, + + /// + /// ISO 216 A6 paper size (105 × 148 mm). + /// Commonly used for postcards, invitations, and small leaflets. + /// + A6, + + /// + /// ISO 216 B3 paper size (353 × 500 mm). + /// Larger than A3 and typically used for posters and technical drawings. + /// + B3, + + /// + /// ISO 216 B4 paper size (250 × 353 mm). + /// Commonly used for magazines and larger printed documents. + /// + B4, + + /// + /// ISO 216 B5 paper size (176 × 250 mm). + /// Frequently used for books and notebooks. + /// + B5, + + /// + /// ISO 216 B6 paper size (125 × 176 mm). + /// Commonly used for pocket-sized books and booklets. + /// + B6, + + /// + /// US Letter paper size (8.5 × 11 in / 216 × 279 mm). + /// The standard paper size used in North America. + /// + Letter, + + /// + /// US Legal paper size (8.5 × 14 in / 216 × 356 mm). + /// Often used for legal and contractual documents. + /// + Legal, +} diff --git a/src/Html2OpenXml/Expressions/BlockElementExpression.cs b/src/Html2OpenXml/Expressions/BlockElementExpression.cs index b8364feb..096026b2 100644 --- a/src/Html2OpenXml/Expressions/BlockElementExpression.cs +++ b/src/Html2OpenXml/Expressions/BlockElementExpression.cs @@ -51,7 +51,7 @@ public override IEnumerable Interpret (ParsingContext context) var bookmarkTarget = node.GetAttribute("data-bookmark"); if (bookmarkTarget is not null) { - var bookmarkId = IncrementBookmarkId(context).ToString(CultureInfo.InvariantCulture); + var bookmarkId = context.IncrementBookmarkId().ToString(CultureInfo.InvariantCulture); var p = childElements.First(); // need to be inserted after pPr to avoid schema warning p.InsertAfter(new BookmarkStart() { Id = bookmarkId, Name = bookmarkTarget }, p.GetFirstChild()); @@ -240,8 +240,8 @@ protected override void ComposeStyles (ParsingContext context) } var lineHeight = styleAttributes.GetUnit("line-height"); - if (!lineHeight.IsValid - && styleAttributes.HasStyleEqualsTo("line-height", "normal")) + if (!lineHeight.IsValid + && styleAttributes["line-height"].Is("normal")) { // if `normal` is specified, reset any values lineHeight = new Unit(UnitMetric.Unitless, 1); @@ -409,29 +409,6 @@ protected Table CreateFrame(IEnumerable childElements) return framedTable; } - /// - /// Resolve the next available (they must be unique). - /// - protected static int IncrementBookmarkId(ParsingContext context) - { - var bookmarkRef = context.Properties("bookmarkRef"); - - if (!bookmarkRef.HasValue) - { - bookmarkRef = 0; - foreach (var b in context.MainPart.Document!.Body!.Descendants()) - { - // OpenXml SDK expose the ID as a string value but this is really an integer - if (b.Id != null && int.TryParse(b.Id.Value, out int id) && id > bookmarkRef) - bookmarkRef = id; - } - } - - bookmarkRef++; - context.Properties("bookmarkRef", bookmarkRef); - return bookmarkRef.Value; - } - private IEnumerable CreatePageBreakBeforeRuns() { if (!styleAttributes.RequiresPageBreakBefore()) @@ -450,6 +427,6 @@ private IEnumerable CreatePageBreakAfterRuns() yield break; yield return new Run( - new Break() { Type = BreakValues.Page }); + new Break() { Type = BreakValues.Page }); } } diff --git a/src/Html2OpenXml/Expressions/BodyExpression.cs b/src/Html2OpenXml/Expressions/BodyExpression.cs index e40a31c6..59180400 100644 --- a/src/Html2OpenXml/Expressions/BodyExpression.cs +++ b/src/Html2OpenXml/Expressions/BodyExpression.cs @@ -35,7 +35,7 @@ public override IEnumerable Interpret(ParsingContext context) var sectionProperties = body.Descendants().LastOrDefault(); if (sectionProperties != null) { - context.IsLandscape = WordDocumentFactory.IsLandscape(sectionProperties.GetFirstChild()); + context.IsLandscape = sectionProperties.GetFirstChild()?.IsLandscape() == true; } var elements = base.Interpret(context).ToList(); @@ -48,7 +48,7 @@ public override IEnumerable Interpret(ParsingContext context) return elements; } - var bookmarkId = IncrementBookmarkId(context).ToString(CultureInfo.InvariantCulture); + var bookmarkId = context.IncrementBookmarkId().ToString(CultureInfo.InvariantCulture); // this is expected to stand in the 1st paragraph Paragraph? p = body.GetFirstChild(); p ??= body.PrependChild(new Paragraph()); @@ -72,30 +72,13 @@ protected override void ComposeStyles(ParsingContext context) PageOrientation orientation = attrValue.Is("landscape")? PageOrientation.Landscape : PageOrientation.Portrait; - var sectionProperties = mainPart.Document!.Body!.GetFirstChild(); - var pageSize = sectionProperties?.GetFirstChild(); - if (pageSize == null) - { - context.IsLandscape = orientation == PageOrientation.Landscape; - mainPart.Document.Body.Append(WordDocumentFactory.CreateSectionProperties(orientation)); - } - else if (WordDocumentFactory.IsLandscape(pageSize) != (orientation == PageOrientation.Landscape)) - { - PageSize newPageSize = WordDocumentFactory.CreateSectionProperties(orientation) - .GetFirstChild()!; - - pageSize.Width = newPageSize.Width; - pageSize.Height = newPageSize.Height; - } + context.Converter.AddPage(orientation); } if (paraProperties.BiDi is not null) { - var sectionProperties = mainPart.Document!.Body!.GetFirstChild(); - if (sectionProperties == null || sectionProperties.GetFirstChild() == null) - { - mainPart.Document.Body.Append(sectionProperties = new()); - } + var sectionProperties = mainPart.Document!.Body!.GetFirstChild() + ?? mainPart.Document.Body.AppendChild(new SectionProperties()); if (!sectionProperties.HasChild()) { diff --git a/src/Html2OpenXml/Expressions/Numbering/NumberingExpressionBase.cs b/src/Html2OpenXml/Expressions/Numbering/NumberingExpressionBase.cs index ea5912fe..41640609 100644 --- a/src/Html2OpenXml/Expressions/Numbering/NumberingExpressionBase.cs +++ b/src/Html2OpenXml/Expressions/Numbering/NumberingExpressionBase.cs @@ -52,7 +52,7 @@ 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 abstractNum = predefinedNumberingLists.TryGetValue(listName, out var predefined)? // If it's a predefined style, we clone it as usual @@ -60,7 +60,7 @@ protected int GetOrCreateListTemplate(ParsingContext context, string listName) // If not found in predefined lists, listName contains a custom bullet character (e.g., "-") CreateCustomBulletAbstractNum(listName); - abstractNum.AbstractNumberId = IncrementAbstractNumId(context, numberingPart); + abstractNum.AbstractNumberId = context.IncrementAbstractNumId(); var level1 = abstractNum.GetFirstChild()!; // this is not documented but MS Word needs that all the AbstractNum are stored consecutively. @@ -116,33 +116,6 @@ protected int GetOrCreateListTemplate(ParsingContext context, string listName) return null; } - /// - /// Resolve the next available (they must be unique and ordered). - /// - private static int IncrementAbstractNumId(ParsingContext context, Numbering numbering) - { - var absNumIdRef = context.Properties("absNumIdRef"); - if (!absNumIdRef.HasValue) - { - absNumIdRef = 0; - // The absNumIdRef Id is a required field and should be unique. We will loop through the existing Numbering definition - // to retrieve the highest Id and reconstruct our own list definition template. - foreach (var abs in numbering.Elements()) - { - if (abs.AbstractNumberId != null && abs.AbstractNumberId > absNumIdRef) - absNumIdRef = abs.AbstractNumberId; - } - } - - // compute the next list instance ID seed. We start at 1 because 0 has a special meaning: - // The w:numId can contain a value of 0, which is a special value that indicates that numbering was removed - // at this level of the style hierarchy. While processing this markup, if the w:val='0', - // the paragraph does not have a list item (http://msdn.microsoft.com/en-us/library/ee922775(office.14).aspx) - absNumIdRef++; - context.Properties("absNumIdRef", absNumIdRef); - return absNumIdRef.Value; - } - /// /// Resolve the next available (they must be unique and ordered). /// diff --git a/src/Html2OpenXml/HtmlConverter.cs b/src/Html2OpenXml/HtmlConverter.cs index 6b3c223a..e9d5410d 100755 --- a/src/Html2OpenXml/HtmlConverter.cs +++ b/src/Html2OpenXml/HtmlConverter.cs @@ -368,11 +368,8 @@ public async Task ParseBody(HtmlFragment fragment, CancellationToken cancellatio HtmlStyles.GetParagraphStyle(HtmlStyles.DefaultStyles.ParagraphBodyStyle)) .ConfigureAwait(false); - if (!paragraphs.Any()) - return; - SectionProperties? sectionProperties = body.GetLastChild() - ?? WordDocumentFactory.CreateSectionProperties(PageOrientation.Portrait); + ?? WordDocumentFactory.CreateSectionProperties(PageOrientation.Portrait, PaperSize.A4); foreach (var para in paragraphs) body.Append(para); @@ -382,7 +379,7 @@ public async Task ParseBody(HtmlFragment fragment, CancellationToken cancellatio if (sectionProperties?.Parent != null) { sectionProperties.Remove(); - body.AddChild(sectionProperties); + body.AppendChild(sectionProperties); } // we automatically create the _top bookmark if missing. To avoid having an empty paragrah, diff --git a/src/Html2OpenXml/ParsingContext.cs b/src/Html2OpenXml/ParsingContext.cs index 1295d40c..03480f8b 100644 --- a/src/Html2OpenXml/ParsingContext.cs +++ b/src/Html2OpenXml/ParsingContext.cs @@ -11,6 +11,7 @@ */ using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Packaging; +using DocumentFormat.OpenXml.Wordprocessing; using HtmlToOpenXml.Expressions; namespace HtmlToOpenXml; @@ -62,7 +63,7 @@ public void CascadeStyles(OpenXmlElement element) /// public ParsingContext CreateChild(HtmlElementExpression expression, bool isStyleScoped = false) { - var childContext = new ParsingContext(Converter, HostingPart, ImageLoader) { + return new ParsingContext(Converter, HostingPart, ImageLoader) { propertyBag = propertyBag, parentExpression = expression, parentContext = isStyleScoped ? null :this, @@ -70,13 +71,63 @@ public ParsingContext CreateChild(HtmlElementExpression expression, bool isStyle PreserveLinebreaks = PreserveLinebreaks, CollapseWhitespaces = CollapseWhitespaces }; - return childContext; } - /// Retrieves a variable tied to the context of the parsing. + /// Retrieves a variable tied to the global context of the parsing. public T? Properties(string name) => propertyBag.TryGetValue(name, out var value)? (T?) value : default; /// Store a variable in the global context of the parsing. public void Properties(string name, object? value) => propertyBag[name] = value; + + /// + /// Resolve the next available (they must be unique). + /// + public int IncrementBookmarkId() + { + var bookmarkRef = Properties("bookmarkRef"); + + if (!bookmarkRef.HasValue) + { + bookmarkRef = 0; + foreach (var b in MainPart.Document!.Body!.Descendants()) + { + // OpenXml SDK expose the ID as a string value but this is really an integer + if (b.Id != null && int.TryParse(b.Id.Value, out int id) && id > bookmarkRef) + bookmarkRef = id; + } + } + + bookmarkRef++; + Properties("bookmarkRef", bookmarkRef); + return bookmarkRef.Value; + } + + /// + /// Resolve the next available (they must be unique and ordered). + /// + public int IncrementAbstractNumId() + { + var absNumIdRef = Properties("absNumIdRef"); + if (!absNumIdRef.HasValue) + { + absNumIdRef = 0; + // The absNumIdRef Id is a required field and should be unique. We will loop through the existing Numbering definition + // to retrieve the highest Id and reconstruct our own list definition template. + var numberingPart = MainPart.NumberingDefinitionsPart!.Numbering!; + foreach (var abs in numberingPart.Elements()) + { + if (abs.AbstractNumberId != null && abs.AbstractNumberId > absNumIdRef) + absNumIdRef = abs.AbstractNumberId; + } + } + + // compute the next list instance ID seed. We start at 1 because 0 has a special meaning: + // The w:numId can contain a value of 0, which is a special value that indicates that numbering was removed + // at this level of the style hierarchy. While processing this markup, if the w:val='0', + // the paragraph does not have a list item (http://msdn.microsoft.com/en-us/library/ee922775(office.14).aspx) + absNumIdRef++; + Properties("absNumIdRef", absNumIdRef); + return absNumIdRef.Value; + } } diff --git a/src/Html2OpenXml/PredefinedStyles.cs b/src/Html2OpenXml/PredefinedStyles.cs index d94372f3..5a6e7749 100755 --- a/src/Html2OpenXml/PredefinedStyles.cs +++ b/src/Html2OpenXml/PredefinedStyles.cs @@ -25,6 +25,8 @@ static class PredefinedStyles public const string Header = "Header"; public const string Footer = "Footer"; public const string Paragraph = "Normal"; + public const string TOCHeading = "TOCHeading"; + public const string TOC = "TOC"; diff --git a/src/Html2OpenXml/PredefinedStyles.resx b/src/Html2OpenXml/PredefinedStyles.resx index f917f681..e7323ec0 100755 --- a/src/Html2OpenXml/PredefinedStyles.resx +++ b/src/Html2OpenXml/PredefinedStyles.resx @@ -302,7 +302,8 @@ ]]> - + @@ -321,6 +322,71 @@ +]]> + + + + + + + + + + + + + + + + + + + +]]> + + + + + + + + + + + + + + + + + + + + + +]]> + + + + + + + + + + + + + + + + + + + ]]> @@ -424,6 +490,148 @@ +]]> + + + + + + + + + + + + + + + + + + + ]]> + + + + + + + + + + + ]]> + + + + + + + + + + + + ]]> + + + + + + + + + + + + ]]> + + + + + + + + + + + + +]]> + + + + + + + + + + + + +]]> + + + + + + + + + + + + +]]> + + + + + + + + + + + + +]]> + + + + + + + + + + + + +]]> + + + + + + + + + + + + ]]> \ No newline at end of file diff --git a/src/Html2OpenXml/Primitives/DefaultStyles.cs b/src/Html2OpenXml/Primitives/DefaultStyles.cs index af2208c2..433a8990 100644 --- a/src/Html2OpenXml/Primitives/DefaultStyles.cs +++ b/src/Html2OpenXml/Primitives/DefaultStyles.cs @@ -130,4 +130,10 @@ public class DefaultStyles /// /// Normal public string ParagraphBodyStyle { get; set; } = PredefinedStyles.Paragraph; + + /// + /// Default style for the Table Of Contents heading (the caption "Table Of Contents"). + /// + /// TOC Heading + public string TOCHeading { get; set; } = PredefinedStyles.TOCHeading; } \ No newline at end of file diff --git a/src/Html2OpenXml/Utilities/AngleSharpExtensions.cs b/src/Html2OpenXml/Utilities/AngleSharpExtensions.cs index cfab8d84..f4c81143 100644 --- a/src/Html2OpenXml/Utilities/AngleSharpExtensions.cs +++ b/src/Html2OpenXml/Utilities/AngleSharpExtensions.cs @@ -172,17 +172,13 @@ public static bool IsInlineLayout(ReadOnlySpan displayMode, string default public static bool RequiresPageBreakBefore(this HtmlAttributeCollection styleAttributes) { - if (styleAttributes.HasStyleEqualsTo("break-before", "page") || - styleAttributes.HasStyleEqualsTo("page-break-before", "always")) - return true; - return false; + return styleAttributes["break-before"].Is("page") || + styleAttributes["page-break-before"].Is("always"); } public static bool RequiresPageBreakAfter(this HtmlAttributeCollection styleAttributes) { - if (styleAttributes.HasStyleEqualsTo("break-after", "page") || - styleAttributes.HasStyleEqualsTo("page-break-after", "always")) - return true; - return false; + return styleAttributes["break-after"].Is("page") || + styleAttributes["page-break-after"].Is("always"); } } \ No newline at end of file diff --git a/src/Html2OpenXml/Utilities/OpenXmlExtensions.cs b/src/Html2OpenXml/Utilities/OpenXmlExtensions.cs index bcd2ec26..62dfde01 100755 --- a/src/Html2OpenXml/Utilities/OpenXmlExtensions.cs +++ b/src/Html2OpenXml/Utilities/OpenXmlExtensions.cs @@ -40,6 +40,67 @@ public static bool HasChild(this OpenXmlElement element) where T : OpenXmlEle return null; } + public static SdtBlock? FindNamedSdtBlock(this Body body, string name) + { + foreach (var stdBlock in body.Descendants()) + { + if (stdBlock.SdtProperties? + .GetFirstChild()? + .DocPartGallery?.Val?.Value == name) + { + return stdBlock; + } + } + + return null; + } + + public static void InsertOrMove(this Body body, + T element, DocumentPosition position) where T: OpenXmlElement + { + if (element.Parent != null) + element.Remove(); + + if (position == DocumentPosition.AfterCover) + { + var coverPage = body.GetCoverPage(); + if (coverPage != null) + { + body.InsertAfter(element, coverPage); + return; + } + + position = DocumentPosition.DocumentStart; + } + + if (position == DocumentPosition.DocumentStart) + { + body.InsertAt(element, 0); + } + else if (position == DocumentPosition.DocumentEnd) + { + var sectionProperties = body.GetLastChild(); + body.InsertBefore(element, sectionProperties); + } + } + + /// + /// Determines whether the specified page size represents a landscape orientation. + /// + public static bool IsLandscape(this PageSize pageSize) + { + return pageSize.Width?.Value >= pageSize.Height?.Value; + } + + /// + /// Swap the orientation of a page. + /// + public static void FlipPage(this PageSize pageSize) + { + (pageSize.Height, pageSize.Width) = (pageSize.Width, pageSize.Height); + pageSize.Orient = pageSize.IsLandscape() ? PageOrientationValues.Landscape : PageOrientationValues.Portrait; + } + public static bool Compare(this PageSize pageSize, PageOrientationValues orientation) { PageOrientationValues pageOrientation; diff --git a/src/Html2OpenXml/WordDocumentFactory.cs b/src/Html2OpenXml/WordDocumentFactory.cs index 1cf0f513..315c901f 100644 --- a/src/Html2OpenXml/WordDocumentFactory.cs +++ b/src/Html2OpenXml/WordDocumentFactory.cs @@ -9,6 +9,7 @@ * IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A * PARTICULAR PURPOSE. */ +using System.Globalization; using DocumentFormat.OpenXml; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Wordprocessing; @@ -19,15 +20,15 @@ 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 +/// 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); @@ -37,12 +38,12 @@ namespace HtmlToOpenXml; /// public static class WordDocumentFactory { - private const uint A4PortraitWidth = 11906U; - private const uint A4PortraitHeight = 16838U; + const string BuiltInGalleryCoverPageName = "Cover Pages"; + const string BuiltInGalleryTOCName = "Table of Contents"; /// /// 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 @@ -52,19 +53,375 @@ public static class WordDocumentFactory /// The destination stream that will receive the generated DOCX package /// The stream must be writable. /// The page orientation to apply to the document. + /// The paper size of the first page. /// 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) + PageOrientation orientation = PageOrientation.Portrait, + PaperSize paperSize = PaperSize.A4) { var package = WordprocessingDocument.Create(stream, WordprocessingDocumentType.Document); var mainPart = GetOrCreateMainDocumentPart(package); - var sectionProperties = CreateSectionProperties(orientation); + var sectionProperties = CreateSectionProperties(orientation, paperSize); mainPart.Document!.Body!.AddChild(sectionProperties); return package; } + /// + /// 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. + /// + /// + /// The converter owning the target document. + /// The orientation of the new page. + /// The paper size of the new page. + public static void AddPage(this HtmlConverter converter, PageOrientation orientation, PaperSize paperSize = PaperSize.A4) + { + var body = GetOrCreateDocumentBody(converter.mainPart); + var sectionProperties = body.GetLastChild(); + var pageSize = sectionProperties?.GetFirstChild(); + + if (pageSize is null) + { + converter.AddPageBreakAfter(null); + body.AppendChild(CreateSectionProperties(orientation, paperSize)); + return; + } + + var (w, h) = GetPageDimensions(paperSize); + if (orientation == PageOrientation.Landscape) + (w, h) = (h, w); + + if (pageSize.Width?.Value != w || pageSize.Height?.Value != h) + { + sectionProperties!.Remove(); + body.AppendChild(new Paragraph( + new ParagraphProperties( + sectionProperties + ), + new Run( + new LastRenderedPageBreak()))); + + body.AppendChild(CreateSectionProperties(orientation, paperSize)); + } + else + { + if (sectionProperties!.PreviousSibling() is Paragraph lastPara) + { + lastPara.AppendChild(new Run( + new Break { Type = BreakValues.Page })); + } + else + { + body.AppendChild(new Paragraph( + new Run( + new Break { Type = BreakValues.Page }))); + } + } + } + + /// + /// Inserts a page break immediately before the specified element. + /// + /// + /// When is , the page break + /// is inserted at the beginning of the document. + /// + /// + /// The converter owning the target document. + /// The element that should be preceded by a page break. + public static void AddPageBreakBefore(this HtmlConverter converter, OpenXmlElement? element) + { + var pageBreak = new Paragraph( + new Run( + new Break { Type = BreakValues.Page }), + new Run( + new LastRenderedPageBreak() + ) + ); + GetOrCreateDocumentBody(converter.mainPart).InsertBefore(pageBreak, element); + } + + /// + /// Inserts a page break immediately after the specified element. + /// + /// + /// When is , the page break + /// is inserted at the end of the document. + /// + /// + /// The converter owning the target document. + /// + /// The element that should be followed by a page break. + /// + public static void AddPageBreakAfter(this HtmlConverter converter, OpenXmlElement? element) + { + var pageBreak = new Paragraph( + new Run( + new Break { Type = BreakValues.Page }) + ); + var body = GetOrCreateDocumentBody(converter.mainPart); + if (element is null) + body.InsertOrMove(pageBreak, DocumentPosition.DocumentEnd); + else + body.InsertAfter(pageBreak, element); + } + + /// + /// Returns the document cover page, if one exists. + /// + /// The cover page is represented using a Word content control associated with + /// the built-in Cover Page gallery. + /// + /// + /// + /// The cover page content control, or when the document + /// does not contain a cover page. + /// + public static SdtBlock? GetCoverPage(this HtmlConverter converter) + => GetOrCreateDocumentBody(converter.mainPart).FindNamedSdtBlock(BuiltInGalleryCoverPageName); + + /// + /// Returns the document cover page, if one exists. + /// + /// The cover page is represented using a Word content control associated with + /// the built-in Cover Page gallery. + /// + /// + /// + /// The cover page content control, or when the document + /// does not contain a cover page. + /// + internal static SdtBlock? GetCoverPage(this Body body) + => body.FindNamedSdtBlock(BuiltInGalleryCoverPageName); + + /// + /// Creates or replaces the document cover page. + /// + /// The supplied HTML is converted using the current configuration + /// and stored inside a Word cover page content control. + /// + /// + /// If a cover page already exists, its content is replaced while the existing content control is preserved. + /// + /// + /// The converter owning the target document. + /// The HTML content to render into the cover page. + /// The cancellation token. + public static async Task SetCoverPage(this HtmlConverter converter, string html, + CancellationToken cancellationToken = default) + { + var fragment = await converter.LoadDocumentAsync(html, cancellationToken); + await converter.SetCoverPage(fragment, cancellationToken); + } + + /// + /// Creates or replaces the document cover page. + /// + /// The supplied HTML is converted using the current configuration + /// and stored inside a Word cover page content control. + /// + /// + /// If a cover page already exists, its content is replaced while the existing content control is preserved. + /// + /// + /// The converter owning the target document. + /// A parsed HTML fragment to render into the cover page. + /// The cancellation token. + public static async Task SetCoverPage(this HtmlConverter converter, HtmlFragment fragment, + CancellationToken cancellationToken = default) + { + SdtBlock? coverStdBlock = converter.GetCoverPage(); + if (coverStdBlock is null) + { + coverStdBlock = new(); + converter.mainPart.Document!.Body!.InsertAt(coverStdBlock, 0); + } + + coverStdBlock.SdtProperties ??= new(); + var partObject = coverStdBlock.SdtProperties.GetOrAddFirstChild(); + partObject.DocPartGallery ??= new() { Val = BuiltInGalleryCoverPageName }; + partObject.DocPartUnique ??= new() { Val = true }; + coverStdBlock.SdtContentBlock?.Remove(); + + var elements = await converter.ParseAsync(fragment, cancellationToken); + var content = new SdtContentBlock(); + content.Append(elements); + content.Append(new Paragraph( + new Run( + new Break() { Type = BreakValues.Page }))); + + coverStdBlock.SdtContentBlock = content; + } + + /// + /// Returns the table of contents, if one exists. + /// + /// The TOC is represented using a Word content control associated with + /// the built-in TOC gallery. + /// + /// + /// + /// The TOC content control, or when the document + /// does not contain a table of contents. + /// + public static SdtBlock? GetTableOfContents(this HtmlConverter converter) + => GetOrCreateDocumentBody(converter.mainPart).FindNamedSdtBlock(BuiltInGalleryTOCName); + + /// + /// Create or updates the document table of contents. + /// + /// The table of contents is generated from paragraphs using Word heading styles + /// (Heading 1 through Heading 9, see also ) + /// and represented as a Word content control associated with the built-in TOC gallery. + /// + /// + /// If a table of contents already exists, its content is replaced. + /// + /// The converter owning the target document. + /// The maximum heading level to include in the table of contents. Valid values + /// are typically between 1 and 9. + /// The optional caption displayed above the table of contents. + /// Specify or an empty string to omit the caption. + /// Determines where the table of contents is inserted when it does not already exist. + /// The content control representing the table of contents. + public static SdtBlock SetTableOfContents( + this HtmlConverter converter, int maxLevel = 3, + string caption = "Table Of Contents", + DocumentPosition position = DocumentPosition.AfterCover) + { + var mainPart = converter.mainPart; + var body = GetOrCreateDocumentBody(mainPart); + SdtBlock? tocStdBlock = converter.GetTableOfContents() ?? new(); + body.InsertOrMove(tocStdBlock, position); + + + tocStdBlock.SdtProperties ??= new(); + var partObject = tocStdBlock.SdtProperties.GetOrAddFirstChild(); + partObject.DocPartGallery ??= new() { Val = BuiltInGalleryTOCName }; + partObject.DocPartUnique ??= new() { Val = true }; + tocStdBlock.SdtContentBlock?.Remove(); + + // append main caption if provided + var sdtContent = new SdtContentBlock(); + if (!string.IsNullOrEmpty(caption)) + { + sdtContent.AppendChild(new Paragraph( + new ParagraphProperties { + ParagraphStyleId = converter.HtmlStyles.GetParagraphStyle(converter.HtmlStyles.DefaultStyles.TOCHeading) + }, + new Run( + new Text(caption)))); + } + + // compose list of headings. Look for styles.xml for any named heading. + var headingStyleIds = converter.HtmlStyles.CollectHeadingStyles(); + + maxLevel = Math.Max(1, Math.Min(9, maxLevel)); + var headings = body.Descendants() + .Where(p => p.ParagraphProperties?.ParagraphStyleId?.Val?.Value != null && + headingStyleIds.TryGetValue(p.ParagraphProperties.ParagraphStyleId.Val.Value, out var level) + && level <= maxLevel).ToList(); + + var parsingContext = new ParsingContext(converter, mainPart, imageLoader: null!); + foreach (var heading in headings) + { + int level = headingStyleIds[heading.ParagraphProperties!.ParagraphStyleId!.Val!.Value!]; + + // create bookmark around the heading as the landing target of the TOC heading links + string bookmarkId = EncloseHeadingInBookmark(parsingContext, heading); + + var hyperlink = new Hyperlink( + new Run( + new RunProperties(new NoProof()) { + RunStyle = converter.HtmlStyles.GetRunStyle(converter.HtmlStyles.DefaultStyles.HyperlinkStyle) + }, + new Text(heading.InnerText) + ), + new Run( + new RunProperties( + new NoProof(), + new WebHidden() + ), + new TabChar(), + // we can't reliabily guess the page number where the heading stands. + // we will leave the text empty but ready for a manual refresh from Word + new FieldChar { FieldCharType = FieldCharValues.Begin }, + new FieldCode($@" PAGEREF {bookmarkId} \h ") { + Space = SpaceProcessingModeValues.Preserve }, + new FieldChar { FieldCharType = FieldCharValues.Separate }, + new Text("") { Space = SpaceProcessingModeValues.Preserve }, + new FieldChar { FieldCharType = FieldCharValues.End } + ) + ) { + Anchor = bookmarkId, History = true }; + + sdtContent.AppendChild(new Paragraph( + new ParagraphProperties( + new Tabs( + new TabStop { Val = TabStopValues.Right, Leader = TabStopLeaderCharValues.Dot, Position = 9016 } + ) + ) { + ParagraphStyleId = converter.HtmlStyles.GetParagraphStyle($"TOC{level}") + }, + hyperlink + )); + } + + var paragraphs = sdtContent.ChildElements.OfType().Take(2); + if (paragraphs.Count() < 2) + sdtContent.AppendChild(new Paragraph()); + + Paragraph toc1 = paragraphs.ElementAt(1); + + // this fieldCode allows Word to auto-refresh the TOC + toc1.InsertAfter( + new Run( + new FieldChar { FieldCharType = FieldCharValues.Begin }, + new FieldCode($@" TOC \o ""1-{maxLevel}"" \h \z \u ") { + Space = SpaceProcessingModeValues.Preserve }, + new FieldChar { FieldCharType = FieldCharValues.Separate } + ), + toc1.ParagraphProperties + ); + sdtContent.AppendChild(new Paragraph( + new Run( + new FieldChar { FieldCharType = FieldCharValues.End }))); + + tocStdBlock.SdtContentBlock = sdtContent; + return tocStdBlock; + } + + /// + /// Ensures that the specified heading paragraph is enclosed within a bookmark. + /// If the heading already contains a bookmark, the existing bookmark name is reused. + /// Otherwise, a new bookmark is generated and inserted around the heading content. + /// + /// The bookmark name that can referenced by hyperlinks and PAGEREF fields. + private static string EncloseHeadingInBookmark(ParsingContext parsingContext, Paragraph heading) + { + var bookmark = heading.GetFirstChild(); + + if (bookmark is not null) + { + if (bookmark.Name?.HasValue == false) + bookmark.Name = parsingContext.IncrementBookmarkId().ToString(CultureInfo.InvariantCulture); + return bookmark.Name!.Value!; + } + + var bookmarkId = parsingContext.IncrementBookmarkId().ToString(CultureInfo.InvariantCulture); + var bookmarkName = "_Toc" + bookmarkId; + // need to be inserted after pPr to avoid schema warning + heading.InsertAfter(new BookmarkStart() { Id = bookmarkId, Name = bookmarkName }, heading.GetFirstChild()); + heading.AppendChild(new BookmarkEnd() { Id = bookmarkId }); + + return bookmarkName; + } + /// /// Gets the main document part associated with the document, creating it when it does not already exist. /// @@ -96,23 +453,13 @@ internal static Body GetOrCreateDocumentBody(MainDocumentPart mainPart) /// /// Generate the required OpenXml element for handling page orientation. /// - internal static SectionProperties CreateSectionProperties(PageOrientation orientation) + internal static SectionProperties CreateSectionProperties(PageOrientation orientation, PaperSize paperSize) { - 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 - }; - } + var (width, height) = GetPageDimensions(paperSize); + PageSize pageSize = new() { Width = width, Height = height }; + + if (orientation == PageOrientation.Landscape) + pageSize.FlipPage(); return new SectionProperties ( pageSize, @@ -125,14 +472,23 @@ internal static SectionProperties CreateSectionProperties(PageOrientation orient ); } - /// - /// Determines whether the specified page size represents a landscape orientation. - /// - internal static bool IsLandscape(PageSize? pageSize) + private static (uint Width, uint Height) GetPageDimensions(PaperSize paperSize) { - if (pageSize is null) - return false; + return paperSize switch { + PaperSize.A6 => (5953, 8391), + PaperSize.A5 => (8391, 11906), + PaperSize.A4 => (11906, 16838), + PaperSize.A3 => (16838, 23811), + + PaperSize.B6 => (7087, 9978), + PaperSize.B5 => (9978, 14173), + PaperSize.B4 => (14173, 20013), + PaperSize.B3 => (20013, 28346), + + PaperSize.Letter => (12240, 15840), + PaperSize.Legal => (12240, 20160), - return pageSize.Width?.Value >= A4PortraitHeight; + _ => throw new ArgumentOutOfRangeException(nameof(paperSize)) + }; } } diff --git a/src/Html2OpenXml/WordDocumentStyle.cs b/src/Html2OpenXml/WordDocumentStyle.cs index 9ef9a465..13119dd1 100755 --- a/src/Html2OpenXml/WordDocumentStyle.cs +++ b/src/Html2OpenXml/WordDocumentStyle.cs @@ -56,13 +56,26 @@ internal WordDocumentStyle(MainDocumentPart mainPart) PredefinedStyles.Heading + "4", PredefinedStyles.Heading + "5", PredefinedStyles.Heading + "6", + PredefinedStyles.Heading + "7", + PredefinedStyles.Heading + "8", + PredefinedStyles.Heading + "9", PredefinedStyles.Hyperlink, PredefinedStyles.IntenseQuote, PredefinedStyles.ListParagraph, PredefinedStyles.Quote, PredefinedStyles.QuoteChar, PredefinedStyles.TableGrid, - PredefinedStyles.Paragraph + PredefinedStyles.Paragraph, + PredefinedStyles.TOCHeading, + PredefinedStyles.TOC + "1", + PredefinedStyles.TOC + "2", + PredefinedStyles.TOC + "3", + PredefinedStyles.TOC + "4", + PredefinedStyles.TOC + "5", + PredefinedStyles.TOC + "6", + PredefinedStyles.TOC + "7", + PredefinedStyles.TOC + "8", + PredefinedStyles.TOC + "9", ]; this.mainPart = mainPart; } @@ -212,6 +225,20 @@ internal void AddStyle(string name, Style style) mainPart.StyleDefinitionsPart!.Styles!.Append(style); } + internal Dictionary CollectHeadingStyles() + { + var headingStyleIds = new Dictionary(9, StringComparer.Ordinal); + for (int i = 1; i <= 9; i++) + { + if (knownStyles.TryGetValue(DefaultStyles.HeadingStyle + i, out var style)) + { + headingStyleIds.Add(style.StyleId!.Value!, i); + } + } + + return headingStyleIds; + } + //____________________________________________________________________ // diff --git a/test/HtmlToOpenXml.Tests/LayoutTests.cs b/test/HtmlToOpenXml.Tests/LayoutTests.cs new file mode 100644 index 00000000..fc6381cf --- /dev/null +++ b/test/HtmlToOpenXml.Tests/LayoutTests.cs @@ -0,0 +1,162 @@ +using NUnit.Framework; +using DocumentFormat.OpenXml.Wordprocessing; + +namespace HtmlToOpenXml.Tests; + +/// +/// Tests parser with the document layout helpers. +/// +[TestFixture] +public class DocumentLayoutTests : HtmlConverterTestBase +{ + [Test] + public async Task SetCoverPage_ShouldAddAsFirst() + { + await converter.ParseBody("Body placeholder"); + await converter.SetCoverPage("

Cover Page

"); + + AssertThatOpenXmlDocumentIsValid(); + + var body = mainPart.Document!.Body!; + var cover = body.GetFirstChild(); + var paragraph = body.GetFirstChild(); + + using (Assert.EnterMultipleScope()) + { + Assert.That(cover, Is.Not.Null, "Cover SdtBlock is first"); + Assert.That(paragraph?.InnerText, Is.EqualTo("Body placeholder")); + } + + Assert.That(body.ChildElements.IndexOf(cover), + Is.LessThan(body.ChildElements.IndexOf(paragraph))); + } + + [Test] + public async Task SetCoverPage_ShouldReplaceExisting() + { + await converter.SetCoverPage("

Cover Page

"); + + await converter.SetCoverPage("

Cover Page 2

"); + + AssertThatOpenXmlDocumentIsValid(); + + var coverSdtBlock = converter.GetCoverPage(); + Assert.That(coverSdtBlock, Is.Not.Null); + Assert.That(coverSdtBlock.SdtContentBlock?.InnerText, Is.EqualTo("Cover Page 2")); + } + + [Test] + public async Task SetTOC_ShouldCreateNativeTOC() + { + const string legend = "Table de matières"; + await converter.ParseBody(""" +

Heading I

+

Heading I.II

+

Heading II

+ """); + converter.SetTableOfContents(maxLevel: 1, caption: legend); + + AssertThatOpenXmlDocumentIsValid(); + + var tocSdtBlock = converter.GetTableOfContents(); + Assert.That(tocSdtBlock, Is.Not.Null); + Assert.That(tocSdtBlock.SdtContentBlock, Is.Not.Null); + var paragraphs = tocSdtBlock.SdtContentBlock.Elements().ToList(); + Assert.That(paragraphs.Count, Is.EqualTo(4), "TOC Heading + 2x headings lvl1 + fieldChar:end"); + + Assert.That(paragraphs[0].InnerText, Is.EqualTo(legend)); + Assert.That(paragraphs[1].ChildElements.OfType().Select(r => r.GetFirstChild()?.InnerText), + Has.One.EqualTo(@" TOC \o ""1-1"" \h \z \u ")); + + Assert.That(tocSdtBlock.SdtProperties? + .Descendants().Single().Val?.Value, Is.EqualTo("Table of Contents"), + "This marker ensures Word recognize the content control as a TOC"); + Assert.That(tocSdtBlock.SdtProperties?.Descendants().Single().Val?.Value, Is.True); + + var hyperlinks = tocSdtBlock.SdtContentBlock.Descendants().ToList(); + Assert.That(hyperlinks, Has.Count.EqualTo(2)); + Assert.That(hyperlinks.All(h => !string.IsNullOrWhiteSpace(h.Anchor?.Value)), Is.True); + + foreach (var hyperlink in hyperlinks) + { + var anchor = hyperlink.Anchor?.Value; + var pageRef = hyperlink.Descendants().SingleOrDefault(); + Assert.That(pageRef, Is.Not.Null); + Assert.That(pageRef.InnerText, Does.StartWith(" PAGEREF ")); + Assert.That(pageRef.InnerText, Does.Contain(anchor)); + } + + var bookmarks = new HashSet(converter.mainPart.Document!.Body!.Descendants() + .Select(b => b.Name?.Value)!); + + foreach (var hyperlink in hyperlinks) + { + Assert.That(bookmarks, Does.Contain(hyperlink.Anchor?.Value)); + } + + Assert.That(tocSdtBlock.SdtContentBlock + .Descendants() + .Count(f => f.FieldCharType?.Value == FieldCharValues.Begin), + Is.EqualTo(tocSdtBlock.SdtContentBlock + .Descendants() + .Count(f => f.FieldCharType?.Value == FieldCharValues.End) + ), "Every field begin marker should have a matching field end marker."); + } + + [Test] + public async Task AddPageBreakAfter_ShouldCreateBreakAfterTOC() + { + var toc = converter.SetTableOfContents(); + converter.AddPageBreakAfter(toc); + + AssertThatOpenXmlDocumentIsValid(); + var run = mainPart.Document!.Body!.GetFirstChild()?.GetFirstChild(); + Assert.That(run, Is.Not.Null); + Assert.That(toc.IsBefore(run), Is.True); + Assert.That(run?.HasChild(), Is.True); + Assert.That(run?.GetFirstChild()?.Type?.Value, Is.EqualTo(BreakValues.Page)); + } + + [Test] + public async Task AddPageBreakBefore_ShouldCreateBreakBeforeTOC() + { + var toc = converter.SetTableOfContents(); + converter.AddPageBreakBefore(toc); + + AssertThatOpenXmlDocumentIsValid(); + var run = mainPart.Document!.Body!.GetFirstChild()?.GetFirstChild(); + Assert.That(run, Is.Not.Null); + Assert.That(toc.IsAfter(run), Is.True); + Assert.That(run?.HasChild(), Is.True); + Assert.That(run?.GetFirstChild()?.Type?.Value, Is.EqualTo(BreakValues.Page)); + } + + [Test] + public async Task AddPageWithDifferentOrientation_ShouldCreateSectionBreak() + { + await converter.ParseBody("Page Portrait"); + + converter.AddPage(PageOrientation.Landscape); + await converter.ParseBody("Page Landscape"); + + AssertThatOpenXmlDocumentIsValid(); + + var firstPage = mainPart.Document!.Body!.GetFirstChild(); + Assert.That(firstPage?.InnerText, Is.EqualTo("Page Portrait")); + var paraBreakSection = firstPage.NextSibling(); + Assert.That((paraBreakSection as Paragraph)?.GetFirstChild()?.SectionProperties, Is.Not.Null, + "The next paragraph must enclose a SectionProperties"); + var pageSize = paraBreakSection!.GetFirstChild()?.SectionProperties!.GetFirstChild(); + Assert.That(pageSize, Is.Not.Null); + Assert.That(pageSize?.IsLandscape(), Is.False, + "The first page layout is ending with this Portrait section properties"); + Assert.That(paraBreakSection.GetFirstChild()?.HasChild(), Is.True); + + var secondPage = paraBreakSection.NextSibling(); + Assert.That((secondPage as Paragraph)?.InnerText, Is.EqualTo("Page Landscape")); + + var lastChild = mainPart.Document!.Body!.LastChild; + Assert.That(lastChild, Is.TypeOf()); + Assert.That(lastChild.GetFirstChild()?.IsLandscape(), Is.True); + } +} \ No newline at end of file diff --git a/test/HtmlToOpenXml.Tests/Utilities/OpenXmlExtensions.cs b/test/HtmlToOpenXml.Tests/Utilities/OpenXmlExtensions.cs index 3167cfd2..f0a6f2e2 100755 --- a/test/HtmlToOpenXml.Tests/Utilities/OpenXmlExtensions.cs +++ b/test/HtmlToOpenXml.Tests/Utilities/OpenXmlExtensions.cs @@ -11,17 +11,27 @@ */ using DocumentFormat.OpenXml; -namespace HtmlToOpenXml.Tests +namespace HtmlToOpenXml.Tests; + +/// +/// Helper class that provide some extension methods to OpenXml SDK. +/// +[System.Diagnostics.DebuggerStepThrough] +static class OpenXmlExtensions { - /// - /// Helper class that provide some extension methods to OpenXml SDK. - /// - [System.Diagnostics.DebuggerStepThrough] - static class OpenXmlExtensions + public static bool HasChild(this OpenXmlElement element) where T : OpenXmlElement { - public static bool HasChild(this OpenXmlElement element) where T : OpenXmlElement + return element.GetFirstChild() != null; + } + + public static int IndexOf(this OpenXmlElementList collection, OpenXmlElement element) + { + for (int i = 0; i < collection.Count; i++) { - return element.GetFirstChild() != null; + if (collection[i] == element) + return i; } + + return -1; } -} \ No newline at end of file +}