Skip to content
Open
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
1 change: 1 addition & 0 deletions html/arabic/net/generate-jpg-and-png-images/_index.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ Aspose.HTML for .NET هي مكتبة قوية تتيح للمطورين إنشا
تعلم كيفية تمكين مضاد التعرج عند تحويل ملفات DOCX إلى صور PNG أو JPG باستخدام Aspose.HTML.
### [تحويل docx إلى png – إنشاء أرشيف zip في C# – دليل تعليمي](./convert-docx-to-png-create-zip-archive-c-tutorial/)
تعلم كيفية تحويل ملفات docx إلى صور PNG وإنشاء أرشيف ZIP باستخدام C# و Aspose.HTML.
### [تحويل HTML إلى PNG في C# – دليل كامل](./render-html-to-png-in-c-complete-guide/)

## خاتمة

Expand Down

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions html/chinese/net/generate-jpg-and-png-images/_index.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@ Aspose.HTML for .NET 提供了一种将 HTML 转换为图像的简单方法。
了解如何在使用 Aspose.HTML for .NET 将 DOCX 文档转换为 PNG 或 JPG 图像时启用抗锯齿,以提升图像质量。
### [使用 C# 将 docx 转换为 png 并创建 zip 存档教程](./convert-docx-to-png-create-zip-archive-c-tutorial/)
学习如何使用 C# 将 DOCX 文档转换为 PNG 图像并打包为 ZIP 文件的完整步骤。
### [在 C# 中将 HTML 渲染为 PNG – 完整指南](./render-html-to-png-in-c-complete-guide/)
本教程详细介绍如何使用 Aspose.HTML for .NET 在 C# 中将 HTML 渲染为 PNG 图像的完整步骤。

## 结论

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,334 @@
---
category: general
date: 2026-08-06
description: 使用 Aspose.HTML 在 C# 中将 HTML 渲染为 PNG。学习如何将 HTML 转换为图像、应用字体样式、抗锯齿和文本提示,全部在一个可运行的示例中。
draft: false
images:
- PLACEHOLDER_URL/og-image.png
keywords:
- render html to png
- convert html to image
- Aspose.HTML rendering
- C# image rendering
- HTML to PNG conversion
language: zh
lastmod: 2026-08-06
og_description: 使用 Aspose.HTML for .NET 将 HTML 渲染为 PNG。本教程展示如何将 HTML 转换为图像,应用粗斜体样式、抗锯齿和文本提示。
og_image_alt: Screenshot of a PNG file generated by rendering HTML to PNG in C#
og_title: 在 C# 中将 HTML 渲染为 PNG – 使用 Aspose.HTML 的逐步指南
schemas:
- author: Aspose
dateModified: '2026-08-06'
description: Render html to png with Aspose.HTML in C#. Learn how to convert html
to image, apply font styles, antialiasing, and text hinting in a single, runnable
example.
headline: Render html to png in C# – complete guide
type: TechArticle
- description: Render html to png with Aspose.HTML in C#. Learn how to convert html
to image, apply font styles, antialiasing, and text hinting in a single, runnable
example.
name: Render html to png in C# – complete guide
steps:
- name: Create the HTML document
text: We start with a minimal HTML string that contains a paragraph styled with
the Arial font. Using `HTMLDocument` lets us work entirely in memory—no temporary
files are created.
- name: Apply bold‑italic styling with `WebFontStyle`
text: Aspose.HTML exposes the `WebFontStyle` enumeration to combine common CSS
font‑weight and font‑style values. Setting it to `BoldItalic` makes the text
appear both bold and italic without writing additional CSS.
- name: Enable antialiasing for smoother edges
text: Antialiasing smooths the borders of shapes and text, reducing jagged pixels
especially on high‑DPI displays.
- name: Activate text hinting
text: Text hinting aligns glyphs to the pixel grid, making characters look sharper
at low resolutions.
- name: Render the document to a PNG file
text: Finally, we create an `ImageRenderer`, pass the document and the two option
objects, and write the output to disk.
- name: Rendering to other image formats
text: '`ImageRenderer` supports BMP, GIF, JPEG, and TIFF. Change the file extension
in `RenderToFile` and optionally adjust `ImageRenderingOptions`:'
- name: Scaling the output
text: 'If you need a higher‑resolution PNG (e.g., for retina displays), set the
`ImageWidth` and `ImageHeight` properties:'
- name: Handling complex CSS
text: 'Aspose.HTML fully supports external stylesheets, media queries, and SVG.
Just load the HTML from a file or URL:'
- name: Thread‑safety considerations
text: '`HTMLDocument` and `ImageRenderer` are not thread‑safe. If you need to
render many pages in parallel, create a separate `HTMLDocument` instance per
thread or use a thread‑pool pattern.'
type: HowTo
tags:
- Aspose.HTML
- C#
- Image rendering
title: 在 C# 中将 HTML 渲染为 PNG – 完整指南
url: /zh/net/generate-jpg-and-png-images/render-html-to-png-in-c-complete-guide/
---

{{< blocks/products/pf/main-wrap-class >}}
{{< blocks/products/pf/main-container >}}
{{< blocks/products/pf/tutorial-page-section >}}

# 在 C# 中将 html 渲染为 png – 完整指南

如果您需要快速且可靠地 **render html to png**,本指南将向您展示如何使用 Aspose.HTML for .NET 完成此操作。您还将看到如何 **convert html to image**,并控制字体样式、抗锯齿和文字提示,以便最终的 PNG 在任何屏幕上都保持清晰。

我们将逐步演示每个必需的步骤——从安装 NuGet 包到生成可投入生产的 PNG 文件。教程结束时,您将拥有一个自包含、可运行的程序,能够直接嵌入任何 C# 项目中。

## 您将学习的内容

* 如何在 .NET 项目中设置 Aspose.HTML。
* 如何创建内存中的 HTML 文档并应用 `WebFontStyle.BoldItalic` 枚举。
* 如何启用抗锯齿和文字提示以获得更平滑的渲染。
* 如何使用 `ImageRenderer` 将文档渲染为 PNG 文件。
* 常见的变体,例如渲染为其他图像格式或缩放输出。

无需外部工具或手动图像转换步骤——所有操作均通过代码完成。

## 前提条件

* .NET 6.0 SDK 或更高版本(代码同样适用于 .NET Framework 4.7+)。
* Visual Studio 2022(或任何支持 C# 的 IDE)。
* 有效的 Aspose.HTML for .NET 许可证(或免费评估密钥)。
* 对 C# 语法有基本了解。

> **专业提示:** 如果您使用的是免费评估版,生成的 PNG 将包含水印。购买许可证后会自动去除水印。

---

## 将 html 转换为图像 – 环境设置

1. **创建一个新的控制台项目**

```bash
dotnet new console -n HtmlToPngDemo
cd HtmlToPngDemo
```

2. **添加 Aspose.HTML NuGet 包**

```bash
dotnet add package Aspose.HTML
```

此命令会拉取渲染 HTML 为图像所需的所有程序集。

3. **(可选)添加许可证文件**

将您的 `Aspose.Total.lic` 文件放置在项目根目录,并在 `Program.cs` 开头添加以下代码行:

```csharp
Aspose.Html.License license = new Aspose.Html.License();
license.SetLicense("Aspose.Total.lic");
```

许可证步骤对免费试用不是必需的,但它可以防止出现水印。

## 使用 Aspose.HTML 将 html 渲染为 png

本教程的核心是一个五步流程,与你提供的代码相对应。每一步都会详细解释,以便您了解 **为什么** 需要此调用,而不仅仅是 **它做了什么**。

### 步骤 1:创建 HTML 文档

我们从一个包含使用 Arial 字体样式的段落的最小 HTML 字符串开始。使用 `HTMLDocument` 可以完全在内存中工作——无需创建临时文件。

```csharp
using Aspose.Html;
using Aspose.Html.Drawing;
using Aspose.Html.Rendering.Image;

// Step 1 – Build an in‑memory HTML document
HTMLDocument document = new HTMLDocument(
"<html><body><p style='font-family:Arial;'>Hello</p></body></html>"
);
```

*为什么重要:* `HTMLDocument` 解析标记并构建渲染器可以遍历的 DOM。由于文档驻留在内存中,操作快速且线程安全。

### 步骤 2:使用 `WebFontStyle` 应用粗斜体样式

Aspose.HTML 提供了 `WebFontStyle` 枚举,用于组合常见的 CSS font‑weight 和 font‑style 值。将其设置为 `BoldItalic` 可使文本同时呈现粗体和斜体,而无需编写额外的 CSS。

```csharp
// Step 2 – Define font styling (bold and italic)
FontInfo fontInfo = new FontInfo();
fontInfo.WebFontStyle = WebFontStyle.BoldItalic;
```

> **为什么使用 `WebFontStyle`?**
> 它消除了嵌入 style 块或外部样式表的需求,减少了在服务器端渲染图像时需要管理的 HTML 量。

### 步骤 3:启用抗锯齿以获得更平滑的边缘

抗锯齿可以平滑形状和文本的边缘,尤其在高 DPI 显示器上减少锯齿像素。

```csharp
// Step 3 – Turn on antialiasing
ImageRenderingOptions imageOptions = new ImageRenderingOptions();
imageOptions.UseAntialiasing = true;
```

*影响:* 当 `UseAntialiasing` 为 `true` 时,渲染器会使用子像素算法,生成更清晰的 PNG,尤其在对角线或小字号时效果显著。

### 步骤 4:激活文字提示

文字提示将字形对齐到像素网格,使字符在低分辨率下看起来更清晰。

```csharp
// Step 4 – Enable text hinting
TextOptions textOptions = new TextOptions();
textOptions.UseHinting = true;
```

*何时禁用:* 如果您之后要渲染基于矢量的 PDF,可能会跳过提示以保留原始轮廓。对于光栅 PNG 输出,提示几乎总是有益的。

### 步骤 5:将文档渲染为 PNG 文件

最后,我们创建 `ImageRenderer`,传入文档和两个选项对象,并将输出写入磁盘。

```csharp
// Step 5 – Render to PNG
ImageRenderer renderer = new ImageRenderer(document, imageOptions, textOptions);
renderer.RenderToFile("output.png");
```

该调用会阻塞,直至文件完全写入,确保程序退出时 `output.png` 已存在。

#### 预期输出

运行程序后会在项目文件夹中生成 **output.png**。该图像显示了使用 Arial 粗斜体的 **Hello**,居中于白色背景,且因抗锯齿和提示而拥有平滑的边缘。

![渲染的 PNG,显示粗斜体 “Hello” 文本](render-html-to-png.png){.img-fluid alt="渲染 html 为 png 示例输出"}

> **注意:** 上图为占位符。在您自己的项目中,PNG 将反映您提供的确切 HTML。

---

## 完整、可运行的源代码

下面是完整的 `Program.cs` 文件。将其复制到您之前创建的控制台项目中,恢复 NuGet 包,然后运行 `dotnet run`。

```csharp
using Aspose.Html;
using Aspose.Html.Drawing;
using Aspose.Html.Rendering.Image;

class Program
{
static void Main()
{
// Optional: load a license to remove evaluation watermark
// var license = new Aspose.Html.License();
// license.SetLicense("Aspose.Total.lic");

// Step 1 – Build an in‑memory HTML document
HTMLDocument document = new HTMLDocument(
"<html><body><p style='font-family:Arial;'>Hello</p></body></html>"
);

// Step 2 – Apply bold‑italic styling
FontInfo fontInfo = new FontInfo();
fontInfo.WebFontStyle = WebFontStyle.BoldItalic;

// Step 3 – Enable antialiasing
ImageRenderingOptions imageOptions = new ImageRenderingOptions();
imageOptions.UseAntialiasing = true;

// Step 4 – Turn on text hinting
TextOptions textOptions = new TextOptions();
textOptions.UseHinting = true;

// Step 5 – Render to PNG file
ImageRenderer renderer = new ImageRenderer(document, imageOptions, textOptions);
renderer.RenderToFile("output.png");

System.Console.WriteLine("HTML has been rendered to PNG successfully.");
}
}
```

运行程序会输出:

```
HTML has been rendered to PNG successfully.
```

并在可执行文件旁生成 `output.png`。

---

## 变体和边缘情况

### 渲染为其他图像格式

`ImageRenderer` 支持 BMP、GIF、JPEG 和 TIFF。修改 `RenderToFile` 中的文件扩展名,并可选地调整 `ImageRenderingOptions`:

```csharp
imageOptions.ImageFormat = Aspose.Html.Rendering.Image.ImageFormat.Jpeg;
renderer.RenderToFile("output.jpeg");
```

### 缩放输出

如果需要更高分辨率的 PNG(例如用于视网膜显示),请设置 `ImageWidth` 和 `ImageHeight` 属性:

```csharp
imageOptions.ImageWidth = 800; // pixels
imageOptions.ImageHeight = 600; // pixels
renderer.RenderToFile("large-output.png");
```

渲染器将在指定尺寸下光栅化 HTML,同时保持矢量质量。

### 处理复杂的 CSS

Aspose.HTML 完全支持外部样式表、媒体查询和 SVG。只需从文件或 URL 加载 HTML 即可:

```csharp
HTMLDocument document = new HTMLDocument("file:///C:/path/to/page.html");
```

相同的渲染管道适用,因此您可以 **convert html to image** 任意网页,而不仅限于简单字符串。

### 线程安全注意事项

`HTMLDocument` 和 `ImageRenderer` 不是线程安全的。如果需要并行渲染多个页面,请为每个线程创建单独的 `HTMLDocument` 实例,或使用线程池模式。

---

## 常见陷阱及避免方法

| 问题 | 产生原因 | 解决方案 |
|-------|----------------|-----|
| PNG 是空白或缺少文字 | 服务器上未找到字体 | 在机器上安装所需字体,或通过 CSS `@font-face` 嵌入字体。 |
| 出现水印 | 使用评估许可证 | 使用有效的许可证文件(`Aspose.Total.lic`)。 |
| 输出模糊 | 抗锯齿未启用 | 设置 `imageOptions.UseAntialiasing = true`。 |
| 文字看起来很细 | 提示未启用 | 设置 `textOptions.UseHinting = true`。 |

## 结论

您现在拥有一个完整、端到端的 **render html to png** C# 解决方案。本教程涵盖了安装 Aspose.HTML、创建 HTML 文档、应用粗斜体样式、启用抗锯齿和文字提示,最后将 PNG 写入磁盘。

接下来您可以探索:

* **Convert html to image** 用于批量处理电子邮件模板。
* 通过将 `ImageRenderer` 替换为 `PdfRenderer` 来渲染为 PDF。
* 使用 Aspose.HTML 的 DOM API 在渲染前操作 HTML。

随意尝试不同的 CSS、更大的画布或其他输出格式。祝您渲染愉快!

## 接下来您应该学习什么?

以下教程涵盖与本指南技术密切相关的主题。每个资源都包含完整的可运行代码示例和逐步说明,帮助您掌握更多 API 功能,并在自己的项目中探索替代实现方案。

- [如何使用 Aspose 将 HTML 渲染为 PNG – 步骤指南](/html/english/net/rendering-html-documents/how-to-use-aspose-to-render-html-to-png-step-by-step-guide/)
- [如何使用 Aspose 将 HTML 渲染为 PNG – 完整指南](/html/english/net/rendering-html-documents/how-to-render-html-to-png-with-aspose-complete-guide/)
- [.NET 中使用 Aspose.HTML 将 HTML 转换为 PNG](/html/english/net/html-extensions-and-conversions/convert-html-to-png/)

{{< /blocks/products/pf/tutorial-page-section >}}
{{< /blocks/products/pf/main-container >}}
{{< /blocks/products/pf/main-wrap-class >}}
{{< blocks/products/products-backtop-button >}}
2 changes: 2 additions & 0 deletions html/czech/net/generate-jpg-and-png-images/_index.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@ Naučte se používat Aspose.HTML pro .NET k manipulaci s dokumenty HTML, převo
Naučte se, jak při převodu dokumentů DOCX na PNG nebo JPG povolit antialiasing pro hladší výstup.
### [Převod docx na png – vytvoření zip archivu C# tutoriál](./convert-docx-to-png-create-zip-archive-c-tutorial/)
Naučte se převést soubory DOCX na PNG a zabalit je do ZIP archivu pomocí C# a Aspose.HTML.
### [Vykreslete HTML do PNG v C# – kompletní průvodce](./render-html-to-png-in-c-complete-guide/)
Kompletní návod, jak pomocí Aspose.HTML pro .NET převést HTML na PNG v jazyce C#.

## Závěr

Expand Down
Loading