用 C# 将 HTML 转换为 PDF
在本指南中,您将了解如何使用 Aspose.HTML for .NET 库将 HTML 文档转换为便携文档格式(PDF)文件格式。我们将详细介绍如何使用 Converter 类的 ConvertHTML() 方法将 HTML 转换为 PDF,以及如何应用 PdfSaveOptions 和 ICreateStreamProvider 参数。
要继续学习本教程,您应在 C# 项目中 安装并配置 Aspose.HTML for .NET 库。我们的代码示例将帮助您使用 C# 库将 HTML 转换为 PDF 并生成 PDF 文件。
用一行代码将 HTML 转换为 PDF
HTML 到 PDF 的转换非常流行。为了实现这一功能,Aspose.HTML for .NET 提供了 Converter 类的静态方法,作为一种简单易懂的方法,只需一行代码就能将 HTML 代码转换为 PDF 文件!
1// Convert HTML to PDF using C#
2
3// Invoke the ConvertHTML() method to convert HTML to PDF
4Converter.ConvertHTML(@"<h1>Convert HTML to PDF!</h1>", ".", new PdfSaveOptions(), Path.Combine(OutputDir, "convert-with-single-line.pdf"));
在线 HTML 转换器
您可以检查 Aspose.HTML API 功能并实时转换 HTML。请从本地文件系统加载 HTML,选择输出格式并运行示例。在示例中,默认设置了保存选项。您将立即以单独文件的形式收到结果。
如果您想通过编程将 HTML 转换为 PDF,请参阅以下 C# 代码示例。
用 C# 将 HTML 转换为 PDF
任何 HTML 到 PDF 的转换都需要加载 HTML 文档并将其保存为 PDF 格式。你可以从文件、HTML 代码、流或 URL 中加载 HTML(请参阅 创建 HTML 文档 一文)。这可能是不同的情况,但只需几个必要的步骤即可完成:
- 使用
HTMLDocument 类的 HTMLDocument() 构造函数之一加载 HTML 文件。在示例中,我们使用
HTMLDocument(
string
) 构造函数从文件初始化 HTML 文档。 - 创建一个新的 PdfSaveOptions 对象。
- 使用转换器类的 ConvertHTML() 方法将 HTML 保存为 PDF 文件。您需要向 ConvertHTML() 方法传递 HTMLDocument、PdfSaveOptions 和输出文件路径,以便将 HTML 转换为 PDF。
为了继续本指南的学习,我们需要使用一些 HTML 文件。下面是我们将在下一个 C# 示例中使用的 HTML 文件示例 – spring.html。在浏览器中打开它,你会看到
请看下面的 C# 代码片段,它显示了 spring.html 文件的 HTML 到 PDF 的转换过程。
1// Convert HTML to PDF in C#
2
3// Prepare a path to a source HTML file
4string documentPath = Path.Combine(DataDir, "spring.html");
5
6// Prepare a path to save the converted file
7string savePath = Path.Combine(OutputDir, "spring-output.pdf");
8
9// Initialize an HTML document from the file
10using HTMLDocument document = new HTMLDocument(documentPath);
11
12// Initialize PdfSaveOptions
13PdfSaveOptions options = new PdfSaveOptions();
14
15// Convert HTML to PDF
16Converter.ConvertHTML(document, options, savePath);
PdfSaveOptions
您可以根据需要使用保存选项来增强 PDF 创建功能。Aspose.HTML 允许使用默认或自定义保存选项将 HTML 转换为 PDF。通过 PdfSaveOptions,您可以自定义渲染过程;您可以指定页面大小、页边距、文件权限、Css 等。
Property | Description |
---|---|
JpegQuality | Specifies the quality of JPEG compression for images. The default value is 95. |
Css | Gets a CssOptions object which is used for configuration of CSS properties processing. |
DocumentInfo | This property contains information about the output PDF document. |
BackgroundColor | This property sets the color that will fill the background of every page. By default, this property is Transparent. |
PageSetup | This property gets a page setup object and uses it for configuration output page-set. |
HorizontalResolution | Sets horizontal resolution for output images in pixels per inch. The default value is 300 dpi. |
VerticalResolution | Sets vertical resolution for output images in pixels per inch. The default value is 300 dpi. |
Encryption | This property gets or sets encryption details. If it is not set, then no encryption will be performed. |
要了解有关 PdfSaveOptions 的更多信息,请阅读 微调转换器 一文。您可以从 GitHub 下载完整的示例和数据文件。
使用 PdfSaveOptions 将 HTML 转换为 PDF
使用 Aspose.HTML,您可以通过编程转换文件,并完全控制各种转换参数。要使用指定的 PdfSaveOptions 将 HTML 转换为 PDF,您需要遵循以下几个步骤:
- 使用 HTMLDocument 类的 HTMLDocument() 构造函数之一加载 HTML 文件。
- 创建一个新的 PdfSaveOptions对象,并指定所需的属性。PdfSaveOptions 类提供了大量属性,可让你完全控制各种参数,并改进 HTML 转换为 PDF 格式的过程。
- 使用转换器类的
ConvertHTML() 方法将 HTML 保存为 PDF 文件。ConvertHTML() 方法接收
document
,options
, 输出文件路径savePath
并执行转换操作。
下面的示例展示了如何使用 PdfSaveOptions,创建带有自定义保存选项的 PDF 文件:
1// Convert HTML to PDF in C# with custom page settings
2
3// Prepare a path to a source HTML file
4string documentPath = Path.Combine(DataDir, "drawing.html");
5
6// Prepare a path to save the converted file
7string savePath = Path.Combine(OutputDir, "drawing-options.pdf");
8
9// Initialize an HTML document from the file
10using HTMLDocument document = new HTMLDocument(documentPath);
11
12// Initialize PdfSaveOptions. Set up the page-size 600x300 pixels, margins, resolutions and change the background color to AliceBlue
13PdfSaveOptions options = new PdfSaveOptions()
14{
15 HorizontalResolution = 200,
16 VerticalResolution = 200,
17 BackgroundColor = System.Drawing.Color.AliceBlue,
18 JpegQuality = 100
19};
20options.PageSetup.AnyPage = new Page(new Aspose.Html.Drawing.Size(600, 300), new Margin(20, 10, 10, 10));
21
22// Convert HTML to PDF
23Converter.ConvertHTML(document, options, savePath);
在上述示例中,我们使用
JpegQuality
属性,用于指定图像的 JPEG 压缩质量;BackgroundColor
属性用于设置填充背景的颜色。默认的BackgroundColor
是透明色;HorizontalResolution
和VerticalResolution
属性以每英寸像素为单位设置输出图像的水平/垂直分辨率。默认情况下,这些属性为 300 dpi;PageSetup
属性指定 page size 和 margins。
将 HTML 转换为 PDF 可以灵活定制,以获得所需的结果。在以下文章中,你将找到有关 HTML 转换为 PDF 的常见问题的答案:
输出流提供商
如果需要将文件保存在远程存储器(如云、数据库等)中,则可以实现 ICreateStreamProvider 接口来手动控制文件创建过程。该接口被设计为一个回调对象,用于在文档/页面开始时创建一个流(取决于输出格式),并在渲染文档/页面后释放早期创建的流。
Aspose.HTML C# 库允许将 MemoryStreamProvider 类作为 ICreateStreamProvider 接口的自定义实现来实现。MemoryStreamProvider 类提供 C# MemoryStream 对象作为写入数据的输出流,这些数据可作为流存储在内存中:
1// Implement a custom MemoryStream provider for advanced control over HTML rendering output streams
2
3class MemoryStreamProvider : Aspose.Html.IO.ICreateStreamProvider
4{
5 // List of MemoryStream objects created during the document rendering
6 public List<MemoryStream> Streams { get; } = new List<MemoryStream>();
7
8 public Stream GetStream(string name, string extension)
9 {
10 // This method is called when only one output stream is required, for instance for XPS, PDF or TIFF formats
11 MemoryStream result = new MemoryStream();
12 Streams.Add(result);
13 return result;
14 }
15
16 public Stream GetStream(string name, string extension, int page)
17 {
18 // This method is called when the creation of multiple output streams are required. For instance, during the rendering HTML to list of image files (JPG, PNG, etc.)
19 MemoryStream result = new MemoryStream();
20 Streams.Add(result);
21 return result;
22 }
23
24 public void ReleaseStream(Stream stream)
25 {
26 // Here you can release the stream filled with data and, for instance, flush it to the hard-drive
27 }
28
29 public void Dispose()
30 {
31 // Releasing resources
32 foreach (MemoryStream stream in Streams)
33 stream.Dispose();
34 }
35}
以下 C# 代码演示了如何使用 MemoryStreamProvider 类和 Aspose.HTML for .NET 库将 HTML 转换为 PDF 并将结果保存到文件中。
1// Convert HTML to PDF in C# using memory stream
2
3// Create an instance of MemoryStreamProvider
4using MemoryStreamProvider streamProvider = new MemoryStreamProvider();
5
6// Initialize an HTML document
7using HTMLDocument document = new HTMLDocument(@"<h1>Convert HTML to PDF File Format!</h1>", ".");
8
9// Convert HTML to PDF using the MemoryStreamProvider
10Converter.ConvertHTML(document, new PdfSaveOptions(), streamProvider);
11
12// Get access to the memory stream that contains the result data
13MemoryStream memory = streamProvider.Streams.First();
14memory.Seek(0, SeekOrigin.Begin);
15
16// Flush the result data to the output file
17using (FileStream fs = File.Create(Path.Combine(OutputDir, "stream-provider.pdf")))
18{
19 memory.CopyTo(fs);
20}
您可以从 GitHub 下载完整的示例和数据文件。
下载 Aspose.HTML for .NET库,它能让您成功、快速、轻松地将 HTML、MHTML、EPUB、SVG 和 Markdown 文档转换为最流行的格式。
Aspose.HTML 提供免费的在线 HTML 到 PDF 转换器,可将 HTML 高质量、方便快捷地转换为 PDF。只需上传、转换您的文件,几秒钟就能得到结果!