如何在 C# 中将 HTML 页面转换为 PDF

本快速教程提供了有关如何在 C#** 中将 HTML 页面转换为 PDF 的详细信息,其中源 HTML 文件是从磁盘加载的。可以通过设置不同的属性(如标题、修改日期等)来配置输出 PDF 文件。使用 C#** 将 **HTML 转换为 PDF 最终通过保存 PDF 文件以及上述属性来完成。

在 C# 中将 HTML 页面转换为 PDF 的步骤

  1. 将项目配置为从 NuGet 包管理器添加 Aspose.HTML
  2. 使用 HTMLDocument 类加载源 HTML 文件以转换为 PDF
  3. 初始化 PdfSaveOptions 对象以配置输出 PDF 文件
  4. 设置输出 PDF 文档的标题、修改日期和背景颜色
  5. 通过调用 C# 中的 Save 方法将 HTML 导出为 PDF

这些使用 C#* 将 HTML 转换为 PDF 的步骤表明,首先添加了必要的库,然后使用 HTMLDocument 类加载源 HTML 文件。在下一步中,将创建包含各种属性的 PdfSaveOptions 类对象,例如 DocumentInfo 类对象,该对象进一步包含不同的属性,包括上面提到的 Title 和 ModificationDate。同样,PdfSaveOptions 类对象包含本教程中设置的背景颜色属性。

使用 C# 将 HTML 转换为 PDF 的代码

using System;
using System.Drawing;
using Aspose.Html;
using Aspose.Html.Converters;
using Aspose.Html.Saving;
namespace KBAspose.HTML
{
public class ConvertHtmlPageToPdfInCSharp
{
public static void HtmlToPDF() // Function to convert HTML to PDF
{
// Initialize license to avoid watermark in output PDF created from HTML page
License lic = new License();
lic.SetLicense(@"Aspose.Html.lic");
// Initialize an HTML document from the file for conversion to PDF
HTMLDocument sourceHtmlFile = new HTMLDocument("SampleInput.html");
// Initialize PdfSaveOptions to configure output PDF
PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
//Set the document title, modification date and background color of the output PDF
pdfSaveOptions.DocumentInfo.Title = "Title set by user";
pdfSaveOptions.DocumentInfo.ModificationDate = new System.DateTime(2022, 2, 15);
pdfSaveOptions.BackgroundColor = Color.LightGreen;
// Convert HTML to PDF with the specified configuration
Converter.ConvertHTML(sourceHtmlFile, pdfSaveOptions, "SampleOutput.pdf");
}
}
}

此代码使用 HTMLDocument 类对象从磁盘加载文件,但是还有许多其他重载可用,例如您可以使用 URL 加载 HTML 页面、从 RequestMessage 创建 HTML 文档、从流加载等等。同样,PdfSaveOptions 包含其他属性,如加密、页面设置、水平和垂直分辨率等。

通过使用 C# 从 HTML 生成 PDF,使用上面给出的详细步骤和代码示例很容易实现。如果您想将 HTML 转换为其他格式(如文本),请参阅 如何在 C# 中将 HTML 转换为文本 上的文章。

 简体中文