HTML 转图像技术能够将动态网页内容(包括文本、图形、CSS 样式和布局)完整转换为 PNG/JPEG 等静态图片格式,完美保留原始页面的视觉呈现效果。该技术特别适用于网页内容存档、生成高质量缩略图、确保跨平台显示一致性等应用场景,同时还能解决动态内容在打印或分享时可能出现的格式问题,为内容传播提供了更可靠的解决方案。
在本文中,您将学习如何使用 C# 和 Spire.Doc for .NET 将 HTML 文件或字符串转换为图片。
安装 Spire.Doc for .NET
首先,您需要添加 Spire.Doc for .NET 包中包含的 DLL 文件作为 .NET 项目中的引用。DLL 文件可以从此链接下载或通过 NuGet 安装。
PM> Install-Package Spire.Doc
C# 将 HTML 文件转换为图片
使用 Spire.Doc for .NET,您可以利用 Document.LoadFromFile() 方法直接加载 HTML 文件。加载完成后,您可以使用 Document.SaveToImages() 方法将文档转换为位图图像。之后,您可以循环查看生成的图像,并将每个图像保存为 PNG、JPG 或 BMP 等广泛使用的图像格式。
以下是如何在 C# 中使用 Spire.Doc 将 HTML 文件转换为图片的步骤:
- 创建一个 Document 对象。
- 使用 Document.LoadFromFile() 方法加载 HTML 文件。
- 调整边距等属性,这将影响输出图像的布局。
- 调用 Document.SaveToImages() 方法将加载的文档转换为 Bitmap 图像数组。
- 迭代这些图像并将每个图像保存为您所需的输出格式。
- C#
using Spire.Doc;
using Spire.Doc.Documents;
using System.Drawing;
using System.Drawing.Imaging;
namespace ConvertHtmlFileToPng
{
class Program
{
static void Main(string[] args)
{
// 创建一个Document对象
Document document = new Document();
// 加载 HTML 文件
document.LoadFromFile(@"C:\Users\Administrator\Desktop\MyHtml.html", FileFormat.Html, XHTMLValidationType.None);
// 获取第一个章节
Section section = document.Sections[0];
// 设置页面边距
section.PageSetup.Margins.All = 2;
// 将文档转换为位图图像数组
Image[] images = document.SaveToImages(ImageType.Bitmap);
// 遍历图像
for (int index = 0; index < images.Length; index++)
{
// 指定输出文件名
string fileName = string.Format(@"C:\Users\Administrator\Desktop\Output\image_{0}.png", index);
// 将每个图像保存为 PNG 文件
images[index].Save(fileName, ImageFormat.Png);
}
// 释放资源
document.Dispose();
}
}
}
C# 将 HTML 字符串转换为图片
在某些情况下,您可能需要将 HTML 字符串直接转换为图片。这种方法对于处理动态生成的内容或当您不希望依赖外部 HTML 文件时特别有用。
以下是如何在 C# 中使用 Spire.Doc 将 HTML 字符串转换为图片的步骤:
- 创建一个 Document 对象。
- 向文档中添加一个节和一个段落。
- 调整边距等属性,这将影响输出图像的布局。
- 从文件中读取 HTML 字符串或直接在脚本中定义。
- 使用 Paragraph.AppendHTML() 方法在文档中添加 HTML 内容。
- 调用 Document.SaveToImages() 方法将文档转换为 Bitmap 图像数组。
- 迭代这些图像并将每个图像保存为您所需的输出格式。
- C#
using Spire.Doc;
using Spire.Doc.Documents;
using System.Drawing;
using System.Drawing.Imaging;
namespace ConvertHtmlStringToPng
{
class Program
{
static void Main(string[] args)
{
// 创建一个Document对象
Document document = new Document();
// 向文档中添加一个节
Section section = document.AddSection();
// 设置页面边距
section.PageSetup.Margins.All = 2;
// 向节中添加一个段落
Paragraph paragraph = section.AddParagraph();
// 从文件中读取HTML字符串
string htmlFilePath = @"C:\Users\Administrator\Desktop\Html_CN.html";
string htmlString = File.ReadAllText(htmlFilePath, System.Text.Encoding.UTF8);
// 将HTML字符串附加到段落
paragraph.AppendHTML(htmlString);
// 将文档转换为Bitmap图像数组
Image[] images = document.SaveToImages(ImageType.Bitmap);
// 迭代这些图像
for (int index = 0; index < images.Length; index++)
{
// 指定输出文件名
string fileName = string.Format(@"C:\Users\Administrator\Desktop\Output\image_{0}.png", index);
// 将每个图像保存为PNG文件
images[index].Save(fileName, ImageFormat.Png);
}
// 释放资源
document.Dispose();
}
}
}
申请临时 License
如果您希望删除结果文档中的评估消息,或者摆脱功能限制,请该Email地址已收到反垃圾邮件插件保护。要显示它您需要在浏览器中启用JavaScript。获取有效期 30 天的临时许可证。