Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
4a3a4ad
Extend HtmlConverter to allow inheritance from CssInliner
onizet Nov 6, 2026
c4784b2
Fix merge conflict
onizet Nov 6, 2026
fa73efc
Fix full namespace in the sample for converting webP
onizet Nov 1, 2026
3897bd4
Align the comment with the real code location
onizet Nov 2, 2026
43eee0a
Fix list items which do not inherit styling from the parent list #252
onizet Nov 2, 2026
94b4435
Numbering list with borders returned a framed table containing the li…
onizet Nov 2, 2026
ed1e873
Optimised way to copy the stream to a filestream
onizet Nov 2, 2026
33d7630
The unit test for `style` tag was invalid. Fix the unit test
onizet Nov 2, 2026
51fefeb
Add missing Trim(), thanks to @AyUsH18102001
onizet Nov 2, 2026
45368e6
Early resolve the Word document body and ensure SectionProperties is …
onizet Nov 2, 2026
4354232
Update changelog
onizet Nov 4, 2026
30fc09a
Remove benchmark project
onizet Nov 4, 2026
7ecc828
Nested List Start Attribute & Indentation Regression (#264)
AyUsH18102001 Nov 6, 2026
7160d40
Extend HtmlConverter to allow inheritance from CssInliner
onizet Nov 7, 2026
bf40a39
Document the new extension methods
onizet Nov 8, 2026
6c310d0
Add unit test to asser the behaviour of CssInliner
onizet Nov 8, 2026
d9d249c
Improve wording
onizet Nov 8, 2026
8fadb02
Improvement wording of documentation
onizet Nov 9, 2026
b4feb43
Write unit test and debug the features to reuse our WebConverter
onizet Nov 9, 2026
27a476f
Merge branch 'dev' into css-inliner
onizet Nov 9, 2026
2f86379
Enhance styling documentation with detailed descriptions
onizet Nov 10, 2026
8c884ff
Fix numbering indentation (#267)
onizet Nov 13, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 1 addition & 5 deletions Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,11 @@
<PropertyGroup>
<Copyright>Copyright 2009-$([System.DateTime]::Today.Year) Olivier Nizet</Copyright>
<Nullable>enable</Nullable>
<LangVersion>latest</LangVersion>
<LangVersion>preview</LangVersion>
<ImplicitUsings>enable</ImplicitUsings>
<Version>4.2.0</Version>
</PropertyGroup>

<PropertyGroup>
<DocumentFormatOpenXmlPackageVersion>3.5.1</DocumentFormatOpenXmlPackageVersion>
</PropertyGroup>

<PropertyGroup Condition="'$(PackageVersion)' != ''">
<PackageVersion>$(PackageVersion)</PackageVersion>
</PropertyGroup>
Expand Down
39 changes: 39 additions & 0 deletions Directory.Packages.props
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
<Project>
<PropertyGroup>
<ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>
</PropertyGroup>

<ItemGroup>
<!-- Primitives -->
<PackageVersion Include="System.ValueTuple" Version="4.6.2" />
<!-- Html Parser -->
<PackageVersion Include="AngleSharp" Version="1.8.6" />
<PackageVersion Include="AngleSharp.Css" Version="1.3.0" />
<!-- OpenXml SDK -->
<PackageVersion Include="DocumentFormat.OpenXml" Version="3.5.1" />
<!-- Framework Abstractions -->
<PackageVersion Include="Microsoft.Extensions.Logging.Abstractions" Version="6.0.0" />
<PackageVersion Include="PolySharp" Version="1.16.0" />
</ItemGroup>

<ItemGroup Label="Build">
<PackageVersion Include="Microsoft.SourceLink.GitHub" Version="10.0.403" />
<PackageVersion Include="NuSpec.AI" Version="3.1.1" />
</ItemGroup>

<ItemGroup Label="Testing">
<PackageVersion Include="coverlet.msbuild" Version="10.1.0" />
<PackageVersion Include="Microsoft.NET.Test.Sdk" Version="18.11.0" />
<!-- NUnit -->
<PackageVersion Include="NUnit" Version="5.0.0" />
<PackageVersion Include="NUnit.Analyzers" Version="4.15.0" />
<PackageVersion Include="NUnit3TestAdapter" Version="6.3.1" />
<!-- Mock -->
<PackageVersion Include="Moq" Version="4.21.0" />
</ItemGroup>

<ItemGroup Label="Global Analyzers">
<GlobalPackageReference Include="Roslynator.Analyzers" Version="5.0.0" />
<GlobalPackageReference Include="Microsoft.CodeAnalysis.Analyzers" Version="5.9.0" />
</ItemGroup>
</Project>
2 changes: 2 additions & 0 deletions HtmlToOpenXml.slnx
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
<Solution>
<Folder Name="/src/">
<Project Path="src/Html2OpenXml/HtmlToOpenXml.csproj" />
<Project Path="src/Html2OpenXml.CssInliner/HtmlToOpenXml.CssInliner.csproj" />
</Folder>
<Folder Name="/test/">
<Project Path="examples/Demo/Demo.csproj" />
<Project Path="test/HtmlToOpenXml.Tests/HtmlToOpenXml.Tests.csproj" />
<Project Path="test/HtmlToOpenXml.CssInliner.Tests/HtmlToOpenXml.CssInliner.Tests.csproj" />
</Folder>
</Solution>
38 changes: 38 additions & 0 deletions docs/guide/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,3 +45,41 @@ Purpose: Converts HTML into a standalone, actionable collection of OpenXML eleme
* **Use Case:** You are building a custom element, merging snippets from multiple sources, or needing to inspect and modify the generated code before injecting it into a document.

* **Note on Synchronicity**: Use `Parse()` for basic, non-resource-dependent conversions. Use `ParseAsync()` when the content requires external resource fetching (images, links) or longer processing time.

## Advanced Extension Hooks (Optional)

`HtmlConverter` can be extended by overriding two virtual methods that participate in the HTML parsing pipeline.
These hooks are intended for advanced scenarios such as CSS inlining, DOM transformations, custom AngleSharp integrations, URL rewriting, or document validation before conversion.

### `GetParserConfiguration()`

* **Purpose:** Provides the `AngleSharp` configuration used to parse the input HTML before conversion begins.

* **Use Case:** Override this method to register AngleSharp extensions, services, or features required during
document parsing. Typical scenario include enabling support for CSS processing, custom resource loaders, or other AngleSharp integrations.

* **Default Behavior:** Returns `Configuration.Default`, providing standard HTML parsing behaviour.

```csharp
protected override IConfiguration GetParserConfiguration()
{
return Configuration.Default
.WithCss();
}
```

### `OnDocumentLoadedAsync()`

* **Purpose:** Executes after the HTML has been parsed into an AngleSharp document but before any OpenXML elements or image resources are generated.

* **Use Case:** Inspect or alter the DOM before conversion. Typical sccenarios include:
* Inlining CSS stylesheets
* Rewriting image URLs
* Removing unsupported elements
* Adding custom attributes
* Performing document validation

* **Default Behavior:** Performs no action.

* **Note:** Any changes made to the DOM are used by all subsequent conversion stages, including the image discovery,
resource loading, and OpenXML conversion.
40 changes: 34 additions & 6 deletions docs/guide/styling.md
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
---
lang: en-US
title: Styling
description:
description: Documentation for HTML, CSS, and OpenXml style handling, including class mapping, default styles and CSS inlining.
---

The `HtmlToOpenXml` converter serves as the bridge between the flexible structure of HTML and the rigorous object model of DOCX. The resulting fidelity depends on how you leverage the built-in style detection and mapping capabilities of the converter.
Expand Down Expand Up @@ -41,7 +41,8 @@ To override the default behavior or apply a unique style, use the `class` attrib
<table class="Standard_Table TableWhite">...</table>
```

*The converter attempts to locate and apply styles matching the class names (`Standard_Table`, `TableWhite`).*
*The converter attempts to locate and apply styles matching the class names (`Standard_Table`, `TableWhite`), performing a runtime translation
between your HTML structure and the target DOCX.*

## OpenXml style mapping

Expand Down Expand Up @@ -91,7 +92,7 @@ If it is not found, you can provide your own OpenXml style definition.

In this sample, the converter will try to find a style with the name **Standard_Table** and if not found, **TableWhite**.

### Provision your style
### Advanced Workflow: Handling Missing Styles

If you add this line of code in the startup example and run it again, you will not see the "Heading 1" style applied.

Expand All @@ -102,8 +103,6 @@ If you add this line of code in the startup example and run it again, you will n
In fact, the "Heading 1" style is well applied but this style does not exists in the document ; when you create a new document, no styles are defined : it's up to you. HtmlToOpenXml handles automatically the hyperlink style for you but it does not deal with every styles.
You can subscribe to the StyleMissing event to be warned and add them yourself.



Generally, you will load in memory an existing document template and append the Html conversion inside it. MS Word 2007 embeds a lot of informations (like styles, themes, document properties, ...) that you don't really want to bother with.

## Dynamic Style Provisioning
Expand Down Expand Up @@ -131,11 +130,40 @@ converter.HtmlStyles.StyleMissing += delegate(object sender, StyleEventArgs args

## Note on External CSS

The converter does not process external stylesheets (`<link rel="stylesheet">`) or `<style>` block content by default. To ensure visual fidelity, you must use a pre-processing tool (like [PreMailer.Net](https://www.nuget.org/packages/PreMailer.Net)) to inline the CSS into the HTML tags before passing it to the converter.
`HtmlToOpenXml` handles standard inline HTML layouts and native **inline CSS** styles (e.g., `style="color: red;"`) out of the box with zero configuration.

By default, the converter **does not** process global stylesheets (`<link rel="stylesheet">`) or `<style>` block content. If your HTML template relies on classes and standalone CSS sheets, you must pre-process and inline the CSS into the HTML tags before conversion using one of these options:

### Option A: The First-Party Inliner (Recommended)

> An optimized pre-processing extension that automatically compiles and flattens global `<style>` declarations into native inline attributes using an asynchronous DOM pipeline.

Add our dedicated companion package to automate style compilation in a single, unified execution chain:

1. Add a reference this NuGet package `dotnet add package HtmlToOpenXml.CssInliner`.
2. Instantiate `CssStyleHtmlConverter`.

```csharp
var converter = new CssStyleHtmlConverter();
await converter.ParseHtmlAsync(mainPart, htmlWithStyleTags);
```

The `CssProcessing` property controls how stylesheets are resolved during conversion.

| Mode | Description | Use Case |
| :--- | :--- | :--- |
| `InternalOnly` | Processes only `<style>` elements embedded in the HTML document. | Network access is unavailable, HTML originates from untrusted sources or all required styles are already embedded in the document. |
| `All` (default) | Processes both the `<style>` elements and external stylesheets referenced through the `<link rel="stylesheet">` tag. | HTML relies on shared stylesheets or external CSS frameworks. Perform a network access, through `IWebRequest`. |

### Option B: Third-Party Pre-Processing (PreMailer.Net)

If you prefer a standalone utility or are already using **PreMailer.Net** in an email template workflow, you can explicitly move your CSS inline manually before parsing. The downside is the HTML is going to be parsed twice. This was the recommended option until v4.

```csharp
string html = ResourceHelper.GetString("Resources.CompleteRunTest.html");
string css = ResourceHelper.GetString("Resources.style.css");

// Compile separate CSS declarations straight into inline attributes
var result = PreMailer.Net.PreMailer.MoveCssInline(html, css: css);
html = result.Html;

Expand Down
2 changes: 1 addition & 1 deletion examples/Demo/Demo.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="DocumentFormat.OpenXml" Version="$(DocumentFormatOpenXmlPackageVersion)" />
<PackageReference Include="DocumentFormat.OpenXml" />
</ItemGroup>

<ItemGroup>
Expand Down
30 changes: 30 additions & 0 deletions src/Html2OpenXml.CssInliner/CssProcessingMode.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
/* 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.
*/
namespace HtmlToOpenXml.CssInliner;

/// <summary>
/// Controls whether external stylesheets are ignored or downloaded and processed.
/// </summary>
public enum CssProcessingMode
{
/// <summary>
/// Process internal <c>style</c> tags embedded within the HTML document.
/// No external web requests are initiated for linked resources.
/// </summary>
InternalOnly,

/// <summary>
/// Process internal style tags and automatically download external stylesheets
/// referenced via <c>&lt;link rel="stylesheet" href="..."&gt;</c> tags.
/// </summary>
All
}
167 changes: 167 additions & 0 deletions src/Html2OpenXml.CssInliner/CssStyleHtmlConverter.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,167 @@
/* Copyright (C) Olivier Nizet https://github.com/onizet/html2openxml - All Rights Reserved
*
* This source is subject to the Microsoft Permissive License.
* Please see the License.txt file for more information.
* All other rights reserved.
*
* THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY
* KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
* PARTICULAR PURPOSE.
*/
using AngleSharp;
using AngleSharp.Css.Dom;
using AngleSharp.Css.Parser;
using AngleSharp.Dom;
using DocumentFormat.OpenXml.Packaging;

namespace HtmlToOpenXml.CssInliner;

/// <summary>
/// An extended HTML-to-OpenXML converter that automatically compiles and inlines
/// global <c>&lt;style&gt;</c> sheets into native HTML element attributes before document processing.
/// </summary>
public class CssStyleHtmlConverter : HtmlConverter
{
/// <summary>
/// Create a converter bound to a Word document, with global CSS style sheet support enabled.
///
/// <para>
/// Reuse the same HtmlConverter instance for the lifetime of a document
/// to avoid reloading cached configuration such as styles and bookmarks.
/// </para>
/// Do not use the same converter instance with multiple documents.
/// </summary>
/// <param name="mainPart">The mainDocumentPart must be the document MainDocumentPart where converted content will be inserted.</param>
/// <param name="webRequester">Control retrieval of external resources such as images.</param>
public CssStyleHtmlConverter(MainDocumentPart mainPart, IO.IWebRequest? webRequester = null)
: base (mainPart, webRequester)
{
}

/// <summary>
/// Create a converter bound to a Word document, with global CSS style sheet support enabled.
///
/// <para>
/// Reuse the same HtmlConverter instance for the lifetime of a document
/// to avoid reloading cached configuration such as styles and bookmarks.
/// </para>
/// Do not use the same converter instance with multiple documents.
/// </summary>
/// <param name="package">The top-level class of a Word document where converted content will be inserted.</param>
/// <param name="webRequester">Control retrieval of external resources such as images.</param>
public CssStyleHtmlConverter(WordprocessingDocument package, IO.IWebRequest? webRequester = null)
: base (package, webRequester)
{
}

/// <summary>
/// Controls how external style sheets are handled during conversion.
///
/// <para>
/// Internal style tags are evaluated and inlined into elements by default.
/// External resources can be resolved through web loaders, which can be configured
/// to support relative URLs or skipped entirely to optimize processing speeds.
/// </para>
/// Default: <see cref="CssProcessingMode.All"/>.
/// </summary>
/// <remarks>
/// <para>
/// Use <see cref="CssProcessingMode.InternalOnly"/> to only process internal style tags,
/// avoiding external network calls and keeping processing fast and safe.
/// </para>
/// <para>
/// Use <see cref="CssProcessingMode.All"/> to automatically download, parse, and
/// merge external stylesheets referenced by link elements into the structural flow,
/// as well as internal style tags.
/// </para>
/// </remarks>
public CssProcessingMode CssProcessing { get; set; } = CssProcessingMode.All;


/// <inheritdoc />
protected override IConfiguration GetParserConfiguration()
{
// Enables downloading the external stylesheets
if (CssProcessing == CssProcessingMode.All)
{
return Configuration.Default
.With(new WebRequestRequester(WebRequester))
.WithDefaultLoader(new AngleSharp.Io.LoaderOptions {
IsResourceLoadingEnabled = true
})
.WithCss();
}

return Configuration.Default.WithCss();
}

/// <inheritdoc />
protected override async Task OnDocumentLoadedAsync(IDocument document, IBrowsingContext browsingContext,
CancellationToken cancellationToken)
{
InlineStyles(document);
}

/// <summary>
/// Compiles internal CSS rules found in &lt;style&gt; tags into native inline attributes
/// on the matched HTML elements within the document. This process effectively merges
/// embedded stylesheets into the structural content during conversion.
/// </summary>
protected void InlineStyles(IDocument document)
{
var cssParser = new CssParser();

foreach (var stylesheet in document.StyleSheets.OfType<ICssStyleSheet>())
{
// map selectors down into raw inline style strings
ApplyCssRules(document, cssParser, stylesheet.Rules);
}

// gather all <style> tags using AngleSharp.Css
var styleElements = document.QuerySelectorAll("style");
foreach (var styleEl in styleElements)
{
var stylesheet = cssParser.ParseStyleSheet(styleEl.TextContent);

ApplyCssRules(document, cssParser, stylesheet.Rules);

// Remove the style tag so it isn't parsed again
styleEl.Remove();
}
}

private void ApplyCssRules(IDocument document, CssParser cssParser, ICssRuleList rules)
{
// map selectors down into raw inline style strings
foreach (var rule in rules.OfType<ICssStyleRule>())
{
var matchingElements = document.QuerySelectorAll(rule.SelectorText);
foreach (var element in matchingElements)
{
// Convert rule.Style into native inline attributes
AppendStylesToElement(element, rule.Style, cssParser);
}
}
}

private static void AppendStylesToElement(IElement element, ICssStyleDeclaration newStyles, CssParser parser)
{
string? currentStyleText = element.GetAttribute("style") ?? "";
var currentStyles = parser.ParseDeclaration(currentStyleText);
if (currentStyles is null)
return;

foreach (var property in newStyles)
{
var priority = newStyles.GetPropertyPriority(property.Name);
bool isPriority = priority.Equals("important", StringComparison.OrdinalIgnoreCase);
if (string.IsNullOrEmpty(currentStyles.GetPropertyValue(property.Name)) || isPriority)
{
currentStyles.SetProperty(property.Name, property.Value, isPriority? priority : null);
}
}

element.SetAttribute("style", currentStyles.ToCss());
}
}
Loading
Loading