保存 HTML 文档 – C# 示例

下载现有文件或从头开始创建 HTML 文档后,可以使用 HTMLDocument.Save() 方法之一保存更改。还有一些重载方法可以将文档保存到文件、URL 或数据流中。

请注意,我们在创建输出文件时有两种不同的概念:

  • 第一种构想基于生成类似 HTML 的文件作为输出。作为这种方法的基类, SaveOptions 有助于处理相关资源(如脚本、样式、图像等)的保存过程。ResourceHandler 类负责处理资源。它的开发目的是将 HTML 内容和资源保存到数据流中,并提供一些方法让您控制资源的处理过程。
  • 第二个概念可用于创建 HTML 的可视化表示结果。这个概念的基类是 RenderingOptions;它有专门的方法来指定页面大小、页边距、分辨率、用户风格等。

本文仅介绍如何使用 SaveOptionsResourceHandler 类。要了解有关呈现机制的更多信息,请参阅 呈现器呈现选项 这两篇文章。

保存选项和资源处理选项

SaveOptions 是一个基类,允许为保存操作指定附加选项,并有助于管理链接的资源。SaveOptions 类的 ResourceHandlingOptions 属性用于配置资源处理。 ResourceHandlingOptions 类表示资源处理选项,可用选项列表如下表所示:

OptionDescription
UrlRestrictionApplies restrictions to the host or folders where resources are located.
MaxHandlingDepthIf you need to save not the only specified HTML document, but also the linked HTML pages, this option gives you the ability to control the depth of the linked pages that should be saved.
JavaScriptThis option specifies how do we need to treat the JavaScript files: it could be saved as a separated linked file, embed into HTML file or even be ignored.
DefaultThis option specifies behavior for other than JavaScript files. Gets or sets an enum, which represents the default way of resource handling. Currently, Save, Ignore, and Embed values are supported. The default value is Save.

保存 HTML

完成 HTML 更改后,您可能需要保存文档。您可以使用 HTMLDocument 类的 Save() 方法来保存文档。下面的示例是保存 HTML 文件的最简单方法:

 1// Save HTML to a file using C#
 2
 3// Prepare an output path for a document saving
 4string documentPath = Path.Combine(OutputDir, "save-to-file.html");
 5
 6// Initialize an empty HTML document
 7using (HTMLDocument document = new HTMLDocument())
 8{
 9    // Create a text element and add it to the document
10    Text text = document.CreateTextNode("Hello, World!");
11    document.Body.AppendChild(text);
12
13    // Save the HTML document to the file on a disk
14    document.Save(documentPath);
15}

在上面的示例中,我们使用 HTMLDocument() 构造函数来初始化一个空的 HTML 文档。HTMLDocument 类的 CreateTextNode(data) 方法会根据指定的字符串创建一个文本节点。Save(path) 方法会将文档保存到由 path 指定的本地文件中。

上面的示例非常简单。不过,在实际应用中,您往往需要对保存过程进行额外的控制。接下来的几节将介绍如何使用资源处理选项或将文档保存为不同格式。

将 HTML 保存到文件

下面的代码片段展示了如何使用 SaveOptions 类的 ResourceHandlingOptions 属性来管理与文档文件的链接。

 1// Save HTML with a linked resources using C#
 2
 3// Prepare an output path for an HTML document 
 4string documentPath = Path.Combine(OutputDir, "save-with-linked-file.html");
 5
 6// Prepare a simple HTML file with a linked document
 7File.WriteAllText(documentPath, "<p>Hello, World!</p>" +
 8                                "<a href='linked.html'>linked file</a>");
 9
10// Prepare a simple linked HTML file
11File.WriteAllText(Path.Combine(OutputDir, "linked.html"), "<p>Hello, linked file!</p>");
12
13// Load the "save-with-linked-file.html" into memory
14using (HTMLDocument document = new HTMLDocument(documentPath))
15{
16    // Create a save options instance
17    HTMLSaveOptions options = new HTMLSaveOptions();
18
19    // The following line with value '0' cuts off all other linked HTML-files while saving this instance
20    // If you remove this line or change value to the '1', the 'linked.html' file will be saved as well to the output folder
21    options.ResourceHandlingOptions.MaxHandlingDepth = 1;
22
23    // Save the document with the save options
24    document.Save(Path.Combine(OutputDir, "save-with-linked-file_out.html"), options);
25}

将 HTML 保存到本地文件系统存储中

HTML 文档可以包含不同的资源,如 CSS、外部图像和文件。Aspose.HTML for .NET提供了一种将HTML与所有链接文件一起保存的方法– ResourceHandler类就是为将HTML内容和资源保存到流中而开发的。该类负责处理资源,提供的方法允许您控制对每个资源的处理。

让我们来看一个将带资源的 HTML 保存到用户指定的本地文件存储空间的例子。源文件 with-resources.html 及其链接的图像文件位于同一目录中。 FileSystemResourceHandler(customOutDir) 构造函数接收一个路径,指明带有资源的文档的保存位置,并创建一个 FileSystemResourceHandler 对象。Save(resourceHandler) 方法会使用该对象并将 HTML 保存到输出存储区。

 1// Save HTML with resources to local storage using C#
 2
 3// Prepare a path to a source HTML file
 4string inputPath = Path.Combine(DataDir, "with-resources.html");
 5
 6// Prepare a full path to an output directory 
 7string customOutDir = Path.Combine(Directory.GetCurrentDirectory(), "./../../../../tests-out/saving/");
 8
 9// Load the HTML document from a file
10using (HTMLDocument doc = new HTMLDocument(inputPath))
11{
12    // Save HTML with resources
13    doc.Save(new FileSystemResourceHandler(customOutDir));
14}

将 HTML 保存为 Zip 档案

您可以通过创建 ZipResourceHandler 类来实现 ResourceHandler。通过它,您可以创建包含 HTML 文档和相关资源的结构化压缩归档文件,使其适用于归档和存储优化等应用场景。ZipResourceHandler 类中的 HandleResource()方法用于自定义在 Zip 存档中处理和存储单个资源的行为。

在下面的示例中,ZipResourceHandler 类用于将 with-resources.html 文档及其链接资源保存到 Zip 压缩包中:

 1// Save an HTML document with all linked resources into a ZIP archive using C#
 2
 3// Prepare a path to a source HTML file 
 4string inputPath = Path.Combine(DataDir, "with-resources.html");
 5
 6string dir = Directory.GetCurrentDirectory();
 7
 8// Prepare a full path to an output zip storage
 9string customArchivePath = Path.Combine(dir, "./../../../../tests-out/saving/archive.zip");
10
11// Load the HTML document 
12using (HTMLDocument doc = new HTMLDocument(inputPath))
13{
14    // Initialize an instance of the ZipResourceHandler class
15    using (ZipResourceHandler resourceHandler = new ZipResourceHandler(customArchivePath))
16    {
17        // Save HTML with resources to a Zip archive
18        doc.Save(resourceHandler);
19    }
20}

ResourceHandler 类是为客户实现而设计的。ZipResourceHandler 类扩展了 ResourceHandler 基类,提供了一种方便的方法来管理将与 HTML 文档链接的资源处理和存储到 Zip 压缩包的整个过程:

 1// Custom resource handler to save HTML with resources into a ZIP archive
 2
 3internal class ZipResourceHandler : ResourceHandler, IDisposable
 4{
 5    private FileStream zipStream;
 6    private ZipArchive archive;
 7    private int streamsCounter;
 8    private bool initialized;
 9
10    public ZipResourceHandler(string name)
11    {
12        DisposeArchive();
13        zipStream = new FileStream(name, FileMode.Create);
14        archive = new ZipArchive(zipStream, ZipArchiveMode.Update);
15        initialized = false;
16    }
17
18    public override void HandleResource(Resource resource, ResourceHandlingContext context)
19    {
20        string zipUri = (streamsCounter++ == 0
21            ? Path.GetFileName(resource.OriginalUrl.Href)
22            : Path.Combine(Path.GetFileName(Path.GetDirectoryName(resource.OriginalUrl.Href)),
23                Path.GetFileName(resource.OriginalUrl.Href)));
24        string samplePrefix = String.Empty;
25        if (initialized)
26            samplePrefix = "my_";
27        else
28            initialized = true;
29
30        using (Stream newStream = archive.CreateEntry(samplePrefix + zipUri).Open())
31        {
32            resource.WithOutputUrl(new Url("file:///" + samplePrefix + zipUri)).Save(newStream, context);
33        }
34    }
35
36    private void DisposeArchive()
37    {
38        if (archive != null)
39        {
40            archive.Dispose();
41            archive = null;
42        }
43
44        if (zipStream != null)
45        {
46            zipStream.Dispose();
47            zipStream = null;
48        }
49
50        streamsCounter = 0;
51    }
52
53    public void Dispose()
54    {
55        DisposeArchive();
56    }
57}

将 HTML 保存到内存流

MemoryResourceHandler 类中的 ResourceHandler 类实现允许将 HTML 保存到内存流中。以下代码展示了如何使用 MemoryResourceHandler 类在内存中存储 HTML 文档,收集并打印所处理资源的相关信息。

  1. 使用指定的 HTML 文件路径初始化 HTML 文档。
  2. 创建 MemoryResourceHandler 类的实例。该类用于在资源处理过程中捕获和存储内存流中的资源。
  3. 调用 HTML 文档的 Save() 方法,并将 MemoryResourceHandler 实例作为参数传递给它。这将把 MemoryResourceHandler 的资源处理逻辑与 HTML 文档保存过程关联起来。
  4. 使用 MemoryResourceHandler 的 PrintInfo() 方法打印所处理资源的相关信息。
 1// Save HTML with resources to memory streams using C#
 2
 3// Prepare a path to a source HTML file 
 4string inputPath = Path.Combine(DataDir, "with-resources.html");
 5
 6// Load the HTML document 
 7using (HTMLDocument doc = new HTMLDocument(inputPath))
 8{
 9    // Create an instance of the MemoryResourceHandler class and save HTML to memory
10    MemoryResourceHandler resourceHandler = new MemoryResourceHandler();
11    doc.Save(resourceHandler);
12    resourceHandler.PrintInfo();
13}

示例运行后,将打印有关内存存储的信息:

uri:memory:///with-resources.html, length:256
uri:memory:///photo1.png, length:57438

ResourceHandler 是一个支持创建和管理输出流的基类。内存资源处理程序MemoryResourceHandler类允许您捕获并在内存流中存储资源,提供了一种动态、灵活的方式来处理资源,而无需将其实际保存到文件系统中。以下代码片段展示了在MemoryResourceHandler类中实现ResourceHandler的过程:

 1// In-memory resource handler that captures and stores HTML resources as streams
 2
 3internal class MemoryResourceHandler : ResourceHandler
 4{
 5    public List<Tuple<Stream, Resource>> Streams;
 6
 7    public MemoryResourceHandler()
 8    {
 9        Streams = new List<Tuple<Stream, Resource>>();
10    }
11
12    public override void HandleResource(Resource resource, ResourceHandlingContext context)
13    {
14        MemoryStream outputStream = new MemoryStream();
15        Streams.Add(Tuple.Create<Stream, Resource>(outputStream, resource));
16        resource
17            .WithOutputUrl(new Url(Path.GetFileName(resource.OriginalUrl.Pathname), "memory:///"))
18            .Save(outputStream, context);
19    }
20
21    public void PrintInfo()
22    {
23        foreach (Tuple<Stream, Resource> stream in Streams)
24            Console.WriteLine($"uri:{stream.Item2.OutputUrl}, length:{stream.Item1.Length}");
25    }
26}

将 HTML 保存为 MHTML

在某些情况下,您需要将网页保存为单个文件。在这种情况下,MHTML文档就能派上用场,因为它是一个网页归档文件,可以将所有内容都保存在其中。HTMLSaveFormat 枚举指定了文档的保存格式,可以是 HTML、MHTML 和 MD 格式。下面的示例展示了如何使用 Save(path, saveFormat) 方法将 HTML 保存为 MHTML 格式。

 1// Save HTML as MHTML using C#
 2
 3// Prepare an output path for a document saving
 4string savePath = Path.Combine(OutputDir, "save-to-mhtml.mht");
 5
 6// Prepare a simple HTML file with a linked document
 7File.WriteAllText("save-to-mhtml.html", "<p>Hello, World!</p>" +
 8                                        "<a href='linked-file.html'>linked file</a>");
 9
10// Prepare a simple linked HTML file
11File.WriteAllText("linked-file.html", "<p>Hello, linked file!</p>");
12
13// Load the "save-to-mhtml.html" into memory
14using (HTMLDocument document = new HTMLDocument("save-to-mhtml.html"))
15{
16    // Save the document to MHTML format
17    document.Save(savePath, HTMLSaveFormat.MHTML);
18}

保存的 “save-to-mhtml.mht “文件存储了 “document.html “和 “linked-file.html “文件的 HTML。

将 HTML 保存为 Markdown

Markdown 是一种使用纯文本语法的标记语言。除了 HTML 转 MHTML 的示例外,您还可以使用 HTMLSaveFormat 将 HTML 保存为 MD。请看下面的示例:

 1// Save HTML as Markdown using C#
 2
 3// Prepare an output path for a document saving
 4string documentPath = Path.Combine(OutputDir, "save-html-to-markdown.md");
 5
 6// Prepare HTML code
 7string html_code = "<H2>Hello, World!</H2>";
 8
 9// Initialize a document from a string variable
10using (HTMLDocument document = new HTMLDocument(html_code, "."))
11{
12    // Save the document as a Markdown file
13    document.Save(documentPath, HTMLSaveFormat.Markdown);
14}

有关如何使用 HTML 转换器的更多信息,请访问 Convert HTML to Markdown 文章。

保存 SVG

通常,SVG是 HTML 文件的一部分,用于表示页面上的矢量数据:图像、图标、表格等。不过,SVG 也可以从网页中提取出来,您可以用与 HTML 文档类似的方式对其进行操作。

由于 SVGDocumentHTMLDocument 基于相同的 WHATWG DOM 标准,因此这两种文档的所有操作(如加载、读取、编辑、转换和保存)都是相似的。因此,所有在 HTMLDocument 中可以看到的操作示例也适用于 SVGDocument。

要保存更改,请执行以下操作:

 1// Create and save SVG image using C#
 2
 3// Prepare an output path for a document saving
 4string documentPath = Path.Combine(OutputDir, "create-and-save-svg.svg");
 5
 6// Prepare SVG code
 7string code = @"
 8    <svg xmlns='http://www.w3.org/2000/svg' height='200' width='300'>
 9        <g fill='none' stroke-width= '10' stroke-dasharray='30 10'>
10            <path stroke='red' d='M 25 40 l 215 0' />
11            <path stroke='black' d='M 35 80 l 215 0' />
12            <path stroke='blue' d='M 45 120 l 215 0' />
13        </g>
14    </svg>";
15
16// Initialize an SVG instance from the content string
17using (SVGDocument document = new SVGDocument(code, "."))
18{
19    // Save the SVG file to a disk
20    document.Save(documentPath);
21}

有关 SVG 基础知识绘图以及处理和呈现 SVG 文档的 API 使用的更多信息,请参阅 Aspose.SVG for .NET 文档

您可以从 GitHub 下载完整的示例和数据文件。

Subscribe to Aspose Product Updates

Get monthly newsletters & offers directly delivered to your mailbox.