开发手册 欢迎您!
软件开发者资料库

.NET(C#) 使用GemBox.Document将HTML转成PDF

.NET(C#) 中将HTML转成PDF的方法比较多,可以使用GemBox.DocumentPuppeteerSharp、EO.Pdf 和 HtmlRenderer.PdfSharp等,本文主要使用GemBox.Document将HTML转成PDF的方法,以及相关的示例代码。

1、安装引用GemBox.Document

1)使用Nuget界面管理器

直接分别搜索 "GemBox.Document",找到对应的点安装即可。

相关文档:VS(Visual Studio)中Nuget的使用

2)使用Package Manager命令安装

PM> Install-Package GemBox.Document

2、使用GemBox.Document将HTML转换PDF

GemBox.Document 支持内联样式、内部和外部样式表。它使用 CSS 属性的子集和 Microsoft Word 中的一些附加任意属性(如mso-paginationmso-rotate)。它还使用@media print { ... }。转换代码如下,

using GemBox.Document;class Program{    static void Main()    {        // 如果使用专业版,需要设置序列号放在下面。        ComponentInfo.SetLicense("FREE-LIMITED-KEY");        // 加载html文件        DocumentModel document = DocumentModel.Load("Input.html");        //当读取任何HTML内容时,都会创建一个Section元素。        //我们可以使用Section元素来指定各种页面选项。         Section section = document.Sections[0];        PageSetup pageSetup = section.PageSetup;        PageMargins pageMargins = pageSetup.PageMargins;        pageMargins.Top = pageMargins.Bottom = pageMargins.Left = pageMargins.Right = 0;        // 保存输出pdf文件        document.Save("Output.pdf");    }}

3、将 HTML 转换为 PDF使用页眉和页脚

GemBox.Document 支持HeaderFooter从 HTML 内容创建元素。如果

是 HTML 文件中的第一个元素,则其内容将作为文档的默认标题读取;如果

是 HTML 文件中的最后一个元素,则其内容将作为文档的默认页脚读取。代码如下,

using System.IO;using GemBox.Document;class Program{    static void Main()    {        // 如果使用专业版,需要设置序列号放在下面。        ComponentInfo.SetLicense("FREE-LIMITED-KEY");        var html = @"  

Header text.

First page.


Second page.


Third page.


Fourth page.

Footer text.

Page 1 of 1

"; var htmlLoadOptions = new HtmlLoadOptions(); using (var htmlStream = new MemoryStream(htmlLoadOptions.Encoding.GetBytes(html))) { // 将输入的HTML文本加载为流。 var document = DocumentModel.Load(htmlStream, htmlLoadOptions); // 保存输出pdf文件 document.Save("Output.pdf"); } }}