HTML and MHTML in .NET
Edit on GitHubParse HTML and MHTML safely in .NET and turn web content into PDF, images, Word, Markdown or RTF with one HTML engine, PSWriteOffice and the CLI.
- Packages
- OfficeIMO.Html
dotnet add package OfficeIMO.Html - OfficeIMO.Html.Pdf
dotnet add package OfficeIMO.Html.Pdf
- OfficeIMO.Html
- Works with
- .NET
- PowerShell
Install-Module PSWriteOffice - CLI
dotnet tool install --global OfficeIMO.Tool
- Target frameworks
- netstandard2.0, net10.0, net472
- Limits
- The managed renderer handles static HTML and CSS; JavaScript, animation and live browser state are outside this path. OfficeIMO.Html support matrix, OfficeIMO.Html.Pdf support matrix
- Verified
- Examples compiled against the source on
OfficeIMO.Html parses HTML into an HtmlConversionDocument with bounded limits, URL policy and base-URI handling. That one parsed document feeds every destination adapter, so Word, Markdown, RTF, PDF and image output agree on how the page was read. Install only the adapter for your destination:
| Destination | Package | Call |
|---|---|---|
| PDF and images (PNG, JPEG, TIFF, WebP, SVG) | OfficeIMO.Html.Pdf | SaveAsPdf, ToImage, SaveAsImages |
| Word | OfficeIMO.Word.Html | ToWord |
| Markdown | OfficeIMO.Markdown.Html | ToMarkdown |
| RTF | OfficeIMO.Html.Rtf | ToRtf |
| MHTML archives | OfficeIMO.Mhtml | MhtmlDocument.Load |
| Search and ingestion | OfficeIMO.Reader.Html | Reader handlers |
dotnet add package OfficeIMO.Html.Pdf
Parse HTML from a string or file
Untrusted input is the default: no local file or network reads, and strict size and depth limits. Mark input as trusted only for your own templates.
C#
using OfficeIMO.Html;
HtmlConversionDocument fromText = HtmlConversionDocument.Parse(
"<h1>Status</h1><p>Generated by OfficeIMO.</p>");
Console.WriteLine(fromText.NormalizedHtml);
File.WriteAllText("report.html", "<html><body><h1>Report</h1></body></html>");
HtmlConversionDocument fromFile = HtmlConversionDocument.Load("report.html", new HtmlConversionDocumentOptions {
Trust = HtmlInputTrust.Trusted,
BaseUri = new Uri(Path.GetFullPath(".") + Path.DirectorySeparatorChar)
});
Console.WriteLine(fromFile.SourceHtml.Length);
PowerShell
$document = New-OfficeHtmlConversionOptions -BaseUri (Resolve-Path .\Assets) -NoBodyContentsOnly
Convert-OfficeDocument -Path .\Report.html -To Word -OutputPath .\Report.docx -Options $document
Convert HTML to PDF
C#
using OfficeIMO.Html;
using OfficeIMO.Html.Pdf;
HtmlConversionDocument
.Parse("<h1>Status</h1><p>All systems normal.</p>")
.SaveAsPdf("status.pdf");
PowerShell
Convert-OfficeDocument -Path .\Report.html -OutputPath .\Report.pdf
CLI
officeimo html convert report.html --output report.pdf
List what the renderer supports
The capability list is generated from the same catalog the .NET API uses.
CLI
officeimo html capabilities --format json