将 HTML 转换为 PDF(.NET)

概述

本文档说明如何 使用 C# 将 HTML 转换为 PDF。它涵盖以下主题。

以下代码片段同样适用于 Aspose.PDF.Drawing 库。

Aspose.PDF for .NET 是一套 PDF 操作 API,能够无缝将任意现有 HTML 文档转换为 PDF。HTML 转 PDF 的过程可以灵活定制。

将 HTML 转换为 PDF

以下 C# 示例代码展示了如何将 HTML 文档转换为 PDF。

将 HTML 转换为 PDF

  1. 创建 HtmlLoadOptions 类的实例。
  2. 初始化 Document 对象。
  3. 调用 Document.Save() 方法保存输出的 PDF 文档。
// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void ConvertHTMLtoPDF()
{
    // The path to the documents directory
    var dataDir = RunExamples.GetDataDir_AsposePdf();

    // Load the HTML file into a document using HtmlLoadOptions
    var options = new Aspose.Pdf.HtmlLoadOptions();

    // Open HTML document
    using (var document = new Aspose.Pdf.Document(dataDir + "test.html", options))
    {
        // Save PDF document
        document.Save(dataDir + "ConvertHTMLtoPDF_out.pdf");
    }
}

高级 HTML 转 PDF 转换

HTML 转换引擎提供了多种选项,帮助我们控制转换过程。

媒体查询支持

媒体查询是一种流行技术,用于向不同设备提供定制的样式表。我们可以使用 HtmlMediaType 属性设置设备类型。

// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void ConvertHTMLtoPDFAdvancedMediaType()
{
    // The path to the documents directory
    var dataDir = RunExamples.GetDataDir_AsposePdf();

    // Load the HTML file into a document using HtmlLoadOptions with Print media type
    var options = new HtmlLoadOptions
    {
        // Set Print or Screen mode
        HtmlMediaType = Aspose.Pdf.HtmlMediaType.Print
    };

    // Open HTML document
    using (var document = new Aspose.Pdf.Document(dataDir + "test.html", options))
    {
        // Save PDF document
        document.Save(dataDir + "ConvertHTMLtoPDFAdvancedMediaType_out.pdf");
    }
}

启用(禁用)字体嵌入

HTML 页面常常使用字体(例如本地文件夹中的字体、Google Fonts 等)。我们也可以通过 IsEmbedFonts 属性控制文档中字体的嵌入。

 // For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
 private static void ConvertHTMLtoPDFAdvancedEmbedFonts()
 {
     // The path to the documents directory
     var dataDir = RunExamples.GetDataDir_AsposePdf();

     // Load the HTML file into a document using HtmlLoadOptions with the font embedding option set
     var options = new Aspose.Pdf.HtmlLoadOptions
     {
         // Disable font embedding
         IsEmbedFonts = false
     };

     // Open HTML document
     using (var document = new Aspose.Pdf.Document(dataDir + "test_fonts.html", options))
     {
         // Save PDF document
         document.Save(dataDir + "ConvertHTMLtoPDFAdvanced_EmbedFonts_out.pdf");
     }
 }

管理外部资源加载

转换引擎提供了一种机制,允许您控制与 HTML 文档关联的某些资源的加载。
HtmlLoadOptions 类拥有属性 CustomLoaderOfExternalResources,可用于定义资源加载器的行为。
假设我们需要将所有 PNG 图像替换为单个图像 test.jpg,并将外部 URL 替换为内部资源的 URL。
为此我们可以定义自定义加载器 SamePictureLoader,并将 CustomLoaderOfExternalResources 指向该名称。

// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void ConvertHTMLtoPDFAdvanced_DummyImage()
{
    // The path to the documents directory
    var dataDir = RunExamples.GetDataDir_AsposePdf();

    // Load the HTML file into a document with a custom resource loader for external images
    var options = new Aspose.Pdf.HtmlLoadOptions
    {
        CustomLoaderOfExternalResources = SamePictureLoader
    };

    // Open HTML document
    using (var document = new Aspose.Pdf.Document(dataDir + "test.html", options))
    {
        // Save PDF document
        document.Save(dataDir + "html_test.pdf");
    }
}

private static Aspose.Pdf.LoadOptions.ResourceLoadingResult SamePictureLoader(string resourceURI)
{
    // The path to the documents directory
    var dataDir = RunExamples.GetDataDir_AsposePdf();
    Aspose.Pdf.LoadOptions.ResourceLoadingResult result;

    if (resourceURI.EndsWith(".png"))
    {
        byte[] resultBytes = File.ReadAllBytes(dataDir + "test.jpg");
        result = new Aspose.Pdf.LoadOptions.ResourceLoadingResult(resultBytes)
        {
            // Set MIME Type
            MIMETypeIfKnown = "image/jpeg"
        };
    }
    else
    {
        result = new Aspose.Pdf.LoadOptions.ResourceLoadingResult(GetContentFromUrl(resourceURI));
    }
    return result;
}

private static byte[] GetContentFromUrl(string url)
{
    var httpClient = new System.Net.Http.HttpClient();
    return httpClient.GetByteArrayAsync(url).GetAwaiter().GetResult();
}

在单页中渲染所有 HTML 内容

Aspose.PDF for .NET 提供了在将 HTML 文件转换为 PDF 格式时将所有内容渲染到单页的能力。例如,当 HTML 内容的输出尺寸超过一页时,您可以使用此选项将输出数据渲染到单个 PDF 页面。为启用此选项,HtmlLoadOptions 类新增了 IsRenderToSinglePage 标志。下面的代码片段展示了如何使用此功能。

 // For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
 private static void ConvertHTMLtoPDFAdvancedSinglePageRendering()
 {
     // The path to the documents directory
     var dataDir = RunExamples.GetDataDir_AsposePdf();

     // Initialize HtmlLoadOptions
     var options = new Aspose.Pdf.HtmlLoadOptions
     {
         // Set Render to single page property
         IsRenderToSinglePage = true
     };

     // Open PDF document
     using (var document = new Aspose.Pdf.Document(dataDir + "HTMLToPDF.html", options))
     {
         // Save PDF document
         document.Save(dataDir + "RenderContentToSamePage_out.pdf");
     }
 }

使用 SVG 数据渲染 HTML

Aspose.PDF for .NET 能够将 HTML 页面转换为 PDF 文档。由于 HTML 允许在页面中以标签形式添加 SVG 图形元素,Aspose.PDF 也支持将此类数据转换为生成的 PDF 文件。以下代码片段展示了如何将包含 SVG 图形标签的 HTML 文件转换为带标签的 PDF 文档。

// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void ConvertHTMLtoPDFWithSVG()
{
    // The path to the documents directory
    var dataDir = RunExamples.GetDataDir_AsposePdf();

    // Initialize HtmlLoadOptions
    var options = new Aspose.Pdf.HtmlLoadOptions(Path.GetDirectoryName(dataDir + "HTMLSVG.html"));

    // Initialize Document object
    using (var document = new Aspose.Pdf.Document(dataDir + "HTMLSVG.html", options))
    {
        // Save PDF document
        document.Save(dataDir + "RenderHTMLwithSVGData_out.pdf");
    }
}

从 HTML 标签创建逻辑结构

为了满足可访问性要求,PDF 文档应包含定义阅读顺序的逻辑结构元素,为屏幕阅读器提供替代文本以描述文档的插图部分,并标记内容层次结构。

许多 HTML 文档已经包含此类逻辑结构。Aspose.PDF 可以在 HTML‑to‑PDF 转换过程中保留并转移这些结构到 PDF。

HtmlLoadOptions.CreateLogicalStructure 属性设为 true,即可使用 PDF 逻辑结构元素复制原始 HTML 文档的结构。

将网页转换为 PDF

将网页转换为 PDF 与转换本地 HTML 文档略有不同。为了将网页内容转换为 PDF 格式,我们可以先使用 HttpClient 实例获取 HTML 页面内容,创建 Stream 对象,将内容传递给 Document 对象并渲染为 PDF。

在将托管于 Web 服务器的网页转换为 PDF 时:

将网页转换为 PDF

  1. 使用 HttpClient 对象读取页面内容。
  2. 实例化 HtmlLoadOptions 对象并设置基准 URL。
  3. 在传入流对象的同时初始化 Document 对象。
  4. (可选)设置页面尺寸和/或方向。
// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void ConvertHTMLtoPDFAdvanced_WebPage()
{
    // The path to the documents directory
    var dataDir = RunExamples.GetDataDir_AsposePdf();

    const string url = "https://en.wikipedia.org/wiki/Aspose_API";

    // Set page size A3 and Landscape orientation;   
    var options = new Aspose.Pdf.HtmlLoadOptions(url)
    {
        PageInfo =
        {
            Width = 842,
            Height = 1191,
            IsLandscape = true
        }
    };

    // Load the web page content as a stream and create a PDF document
    using (var document = new Aspose.Pdf.Document(GetContentFromUrlAsStream(url), options))
    {
        // Save PDF document
        document.Save(dataDir + "html_test.pdf");
    }
}

private static Stream GetContentFromUrlAsStream(string url, System.Net.ICredentials credentials = null)
{
    using (var handler = new System.Net.Http.HttpClientHandler { Credentials = credentials })
    using (var httpClient = new System.Net.Http.HttpClient(handler))
    {
        return httpClient.GetStreamAsync(url).GetAwaiter().GetResult();
    }
}

为网页转 PDF 提供凭据

有时我们需要转换需要身份验证和访问权限的 HTML 文件,以便只有授权用户才能获取页面内容。这也包括 HTML 中引用的某些资源/数据需要从要求身份验证的外部服务器获取的场景。为满足此需求,ExternalResourcesCredentials 属性已添加到 HtmlLoadOptions 类中。下面的代码片段展示了在将 HTML 文件转换为 PDF 时传递凭据以请求 HTML 及其相应资源的步骤。

 // For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
 private static void ConvertHTMLtoPDFAdvancedAuthorized()
 {
     // The path to the documents directory
     var dataDir = RunExamples.GetDataDir_AsposePdf();

     const string url = "http://httpbin.org/basic-auth/user1/password1";
     var credentials = new System.Net.NetworkCredential("user1", "password1");

     var options = new Aspose.Pdf.HtmlLoadOptions(url)
     {
         ExternalResourcesCredentials = credentials
     };

     using (var document = new Aspose.Pdf.Document(GetContentFromUrlAsStream(url, credentials), options))
     {
         // Save PDF document
         document.Save(dataDir + "HtmlTest_out.pdf");
     }
 }

private static Stream GetContentFromUrlAsStream(string url, System.Net.ICredentials credentials = null)
{
    using (var handler = new System.Net.Http.HttpClientHandler { Credentials = credentials })
    using (var httpClient = new System.Net.Http.HttpClient(handler))
    {
        return httpClient.GetStreamAsync(url).GetAwaiter().GetResult();
    }
}

将 MHTML 转换为 PDF

MHTML,即 MIME HTML,是一种网页归档格式,用于将通常通过外部链接(如图像、Flash 动画、Java 小程序和音频文件)表示的资源与 HTML 代码合并为单个文件。MHTML 文件的内容被编码为类似 HTML 电子邮件的 MIME 类型 multipart/related。Aspose.PDF for .NET 能将 HTML 文件转换为 PDF 格式,并且在 Aspose.PDF for .NET 9.0.0 版本中,我们引入了将 MHTML 文件转换为 PDF 格式的新功能。下面的代码片段展示了如何使用 C# 将 MHTML 文件转换为 PDF 格式:

将 MHTML 转换为 PDF

  1. 创建 MhtLoadOptions 类的实例。
  2. 初始化 Document 对象。
  3. 调用 Document.Save() 方法保存输出的 PDF 文档。
// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void ConvertMHTtoPDF()
{
    // The path to the documents directory
    var dataDir = RunExamples.GetDataDir_AsposePdf();

    // Initialize MhtLoadOptions with page setup
    var options = new Aspose.Pdf.MhtLoadOptions()
    {
        PageInfo = { Width = 842, Height = 1191, IsLandscape = true }
    };

    // Initialize Document object using the MHT file and options
    using (var document = new Aspose.Pdf.Document(dataDir + "fileformatinfo.mht", options))
    {
        // Save PDF document
        document.Save(dataDir + "MhtmlTest_out.pdf");
    }
}