Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
16 changes: 16 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,21 @@
# Changelog

## 4.2.0

Ease of Use Improvements:

- New `WordDocumentFactory.Create()` helper.
- New `HtmlConverter(WordProcessingDocument)` constructor overload.
- Automatic creation of missing document structure (`MainDocumentPart`, `Body`).
- New `PageOrientation` support for document creation.
- Introduce a new companion library: `HtmlToOpenXml.CssInliner`

- Improve numbering list items which do not inherit styling from the parent list #252
- Fix text-align: left being ignored- #263, thanks to @cyril265
- Numbering list now support border style.
- Fix indentation and hanging of nested paragraph in numbering list.
- Improve code robustness and quality

## 4.1.0

- Support CSS shorthand for `border` style, co-authored with @AyUsH18102001.
Expand Down
8 changes: 2 additions & 6 deletions Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,9 @@
<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.1.0</Version>
</PropertyGroup>

<PropertyGroup>
<DocumentFormatOpenXmlPackageVersion>3.5.1</DocumentFormatOpenXmlPackageVersion>
<Version>4.2.0</Version>
</PropertyGroup>

<PropertyGroup Condition="'$(PackageVersion)' != ''">
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>
3 changes: 2 additions & 1 deletion HtmlToOpenXml.slnx
Original file line number Diff line number Diff line change
@@ -1,10 +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/Benchmark/Benchmark.csproj" />
<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>
13 changes: 3 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,7 @@ When creating a blank document:
await using var generatedDocument = new MemoryStream();
using var package = WordprocessingDocument.Create(generatedDocument, WordprocessingDocumentType.Document);

var mainPart = package.AddMainDocumentPart();
new Document(new Body()).Save(mainPart);
HtmlConverter converter = new(mainPart);
HtmlConverter converter = new(package);
await converter.ParseBody(html);
```

Expand All @@ -33,14 +31,9 @@ When inserting inside an existing document:
```csharp
await using var generatedDocument = new MemoryStream();
await templateFileStream.CopyToAsync(generatedDocument);
generatedDocument.Position = 0L;
using var package = WordprocessingDocument.Open(generatedDocument, true);
MainDocumentPart? mainPart = package.MainDocumentPart;
if (mainPart == null)
{
mainPart = package.AddMainDocumentPart();
new Document(new Body()).Save(mainPart);
}
HtmlConverter converter = new(mainPart);
HtmlConverter converter = new(package);
await converter.ParseBody(html);
```

Expand Down
17 changes: 7 additions & 10 deletions docs/.vuepress/public/nuspec-ai.txt
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
#NuSpec.AI/v2 HtmlToOpenXml 4.0.0
#NuSpec.AI/v2 HtmlToOpenXml 4.2.0
#desc Convert simple or advanced HTML into OpenXML Word content while reusing existing document styles, numbering, and templates.
#tfm netstandard2.0;net462;net8.0;net10.0
#dep AngleSharp|1.8.0|0;DocumentFormat.OpenXml|3.5.1|0;Microsoft.Extensions.Logging.Abstractions|6.0.0|0;System.ValueTuple|4.5.0|0
#dep AngleSharp|1.8.6|0;DocumentFormat.OpenXml|3.5.1|0;Microsoft.Extensions.Logging.Abstractions|6.0.0|0;System.ValueTuple|4.6.2|0
@e AcronymPosition "Controls where the definition of an acronym or abbreviation is rendered during conversion. AcronymFor example, the definition assocaited with an HTML abbr element can be rendered at the end of the page or collected at the end of the document."
.ev PageEnd=0,DocumentEnd=1
@c DefaultStyles [entity] "Contains the default OpenXml style mappings used by HtmlToOpenXml.HtmlConverter. Styles selected through these mappings provide the base formatting. CSS attributes defined on HTML elements are still applied on top of the resulting Word style. Several commonly used Word styles such as headings, hyperlinks, captions, tables, footnotes and quotes can be created automatically when missing from the document. Customise these mappings to use your own style names during conversion."
Expand All @@ -18,14 +18,12 @@
.p QuoteStyle:string "Default style for quotes (quote, cite)."
.p IntenseQuoteStyle:string "Default style for intense quotes (blockquote)."
.p TableStyle:string "Default style for tables (table)."
.p HeaderStyle:string "Default style for any paragraphs (p) in the header section (DocumentFormat.OpenXml.Packaging.HeaderPart )."
.p ParagraphHeaderStyle:string "Default style for any paragraphs (p) in the header section (DocumentFormat.OpenXml.Packaging.HeaderPart )."
.p FooterStyle:string "Default style for any paragraphs (p) in the footer section (DocumentFormat.OpenXml.Packaging.FooterPart )."
.p ParagraphFooterStyle:string "Default style for any paragraphs (p) in the footer section (DocumentFormat.OpenXml.Packaging.FooterPart )."
.p Paragraph:string "Default style for body paragraph (body or any top level tag in HTML source)."
.p ParagraphBodyStyle:string "Default style for paragraph (p or body or any top level tag in HTML source) in the body section."
@c HtmlConverter "Primary entry point for converting HTML into OpenXml Word document. The converter can be used with newly created documents as well as existing document templates. When a template is used, styles, themes, numbering definitions, bookmarks, and other Word settings are automatically reused. Supports both left-to-right (LTR) and right-to-left (LTR) visual flow content. Direction can be specified using the HTML dir attribute (recommended) or inferred from the lang attribute. When not specified, the converter preserves the layout defined by the target Word document. Supports full OpenXML table translation, including complex structural elements (nested tables, `colspan`/`rowspan`) and precise dimension mapping (`px`, `%`), column definitions, vertical text, and automatic conversion of table widths. Table widths can be specified using auto, percentages, or fixed dimensions (px/pt). Use HtmlToOpenXml.HtmlConverter.HtmlStyles to customise styling and HtmlToOpenXml.IO.IWebRequest to customise external resource retrieval. Typical usage: Create an HtmlConverter from a MainDocumentPart obtained from a WordProcessingDocument. Call ParseBody() to append the converted content to the document body. Advanced scenarios can use ParseAsync() to control where the generated OpenXml elements are inserted."
.ctor (MainDocumentPart mainPart, IWebRequest? webRequester = null) "Create a converter bound to a Word document. Reuse the same HtmlConverter instance for the lifetime of a document to avoid reloading cached configuration such as styles and bookmarks. Do not use the same converter instance with multiple documents."
.ctor (WordprocessingDocument package, IWebRequest? webRequester = null) "Create a converter bound to a Word document. Reuse the same HtmlConverter instance for the lifetime of a document to avoid reloading cached configuration such as styles and bookmarks. Do not use the same converter instance with multiple documents."
.m Parse:IList<OpenXmlCompositeElement>(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<IEnumerable<OpenXmlCompositeElement>>(string html, CancellationToken cancellationToken = null) "Convert HTML into OpenXml elements and return them to the caller. However, the conversion process itself may still update the underlying document by creating styles, numbering definitions, image parts, bookmarks, or other resources required by the generated content. Use this method when you need full control over the insertion point or need to inspect or modify the generated elements before adding them to the document. For most scenarios, prefer ParseBody()."
.m ParseAsync:Task<IEnumerable<OpenXmlCompositeElement>>(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()."
Expand All @@ -43,11 +41,6 @@
.p SupportsHeadingNumbering:bool "Defines whether (h1-h6) elements are mapped to the corresponding Word heading style. Missing heading styles are added automatically when required. When heading text begins with a numbering pattern such as "1.", "1.1.", or "1 " or when the heading uses the `decimal-tiered` CSS class, the converter interprets it as a numbered heading. Any associated heading numbering is then managed by Word through the Heading styles. This feature is enabled by default."
@e ImageProcessingMode "Controls whether images are embedded in the generated document or kept as external references."
.ev Embed=0,LinkExternal=1,EmbedDataUriOnly=2
@c DataUri "Represents a Data URI containing inline content encoded directly in the URI string, typically using Base64 encoding. Data URIs are commonly used to embed images in HTML without referencing an external resource, for example: data:image/png;base64,..."
.m TryCreate:bool(string uri, out DataUri? result) "Parse an instance of the Data URI scheme."
.m IsWellFormed:bool(string uri) "Indicates whether the string is well-formed by attempting to construct a DataUri with the string."
.p Mime:string "Gets the MIME type declared by the Data URI, such as image/png or image/jpeg."
.p Data:byte[] "Gets the decoded binary content extracted from the Data URI."
@c DefaultWebRequest "Default implementation of HtmlToOpenXml.IO.IWebRequest. Supports http, https, local file and inline data (base64). Derive from this class to customise resource retrieval, authentication, image processing, URL resolution, or content transformation while reusing the built-in behaviour."
.ctor (ILogger? logger = null) "Initialize a new instance of the HtmlToOpenXml.IO.DefaultWebRequest class."
.ctor (HttpClient httpClient, ILogger? logger = null) "Initialize a new instance of the HtmlToOpenXml.IO.DefaultWebRequest class with the specified HttpClient. Supply your own HttpClient to customise how external resources are retrieved, for example to configure cookies, authentication headers, API keys, proxies, or message handlers."
Expand All @@ -62,6 +55,8 @@
.p Headers:string> "Optional response Http headers. Content-Type is used when the resource type cannot be determined from the URL."
.p Content:Stream "Gets the resource content stream. The stream must be readable.Resource type detection may inspect the beginning of the stream and reset its position afterwards, therefore the stream should support seeking."
.m Dispose:void()
@e PageOrientation "Specifies the page orientation used when creating a new Word document. The orientation determines whether pages are laid out vertically (portrait) or horizontally (landscape)."
.ev Portrait=0,Landscape=1
@s QuoteChars "Predefined quote style as defined by the browser (used for the q HTML tag)."
.ctor (string begin, string end) "Predefined quote style as defined by the browser (used for the q HTML tag)."
.f IE:QuoteChars "Internet Explorer style: « abc »"
Expand All @@ -70,6 +65,8 @@
@c StyleEventArgs [entity] "Provides information about a style requested during conversion that could not be found in the Word document. The HtmlToOpenXml.WordDocumentStyle.StyleMissing event uses these arguments to indicate which style should be dynamically provisioned and which OpenXml style type is expected."
.p Name:string "Gets the identifier of the missing style. Use this value when creating and registering the style."
.p Type:StyleValues "Gets the OpenXml style type expected by the converter, such as paragraph, table or character."
@c WordDocumentFactory [factory] "Provides helper methods for creating Word documents configured for use with HtmlToOpenXml.HtmlConverter. This factory simplifies the creation of new DOCX documents by configuring the required OpenXML package structure, document parts, and page settings. The generated documents can be used directly with HtmlToOpenXml.HtmlConverter to convert HTML content into WordProcessingML."
.m Create:WordprocessingDocument(Stream stream, PageOrientation orientation = Portrait) "Create a new Word document on the specified stream and configures its page settings. The created document contains the minimum required OpenXML structure, including a main document part and an empty body. The returned document can be passed directly to HtmlToOpenXml.HtmlConverter or further customised using the Open XML SDK."
@c WordDocumentStyle "Provides style-related services used during HTML conversion. HTML class names may be mapped directly to Word styles with the same name (case insensitive). When a referenced style cannot be found, the HtmlToOpenXml.WordDocumentStyle.StyleMissing event allows it to be provisioned dynamically."
.m AddStyle:void(Style style) "Adds a new style to the Word document and refreshes the converter's internal style cache. Use this method in conjunction with the HtmlToOpenXml.WordDocumentStyle.StyleMissing event to inject styles required by a template that are absent from the source document."
.p DefaultStyles:DefaultStyles "Contains the default styles for new OpenXml elements, created during the conversion process."
Expand Down
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.
2 changes: 1 addition & 1 deletion docs/guide/images.md
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@ class WebPWebRequest : DefaultWebRequest
if (resource.Content is not null && requestUri.OriginalString.EndsWith(".webp"))
{
// Load, convert to PNG stream, and replace the original resource content.
using var img = await Image.LoadAsync(resource.Content, cancellationToken);
using var img = await SixLabors.ImageSharp.Image.LoadAsync(resource.Content, cancellationToken);
var convertedStream = new MemoryStream();
await img.SaveAsPngAsync(convertedStream, cancellationToken);

Expand Down
Loading
Loading