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

1、安装引用PDF Metamorphosis .Net

需要 .NET Framework 4.0 或更高版本。兼容所有 .NET 语言,并支持所有可以使用 .NET Framework 和 .NET Core 的操作系统。PDF Metamorphosis .Net 完全用托管 C# 编写,这使其绝对独立和独立的库。

1)使用Nuget界面管理器

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

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

2)使用Package Manager命令安装

PM> Install-Package sautinsoft.pdfmetamorphosis

2、C# 中将 HTML 字符串转换为 PDF

使用PDF Metamorphosis .Net将 HTML 字符串转换为PDF 文件,代码如下,

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            SautinSoft.PdfMetamorphosis p = new SautinSoft.PdfMetamorphosis();

            if (p != null)
            {
                string htmlPath = @"c:\Doctor Zhivago.htm";
                string pdfPath = Path.ChangeExtension(htmlPath, ".pdf");
                string htmlString = "";

                // 1. 获取HTML字符串
                htmlString = ReadFromFile(htmlPath);

                // 2. 将HTML字符串转PDF
                // 指定BaseUrl来帮助转换器找到相对图像CSS的完整路径。
                p.HtmlSettings.BaseUrl = Path.GetDirectoryName(Path.GetFullPath(htmlPath));
                byte[] pdfBytes = p.HtmlToPdfConvertStringToByte(htmlString);

                if (pdfBytes != null)
                {
                    // 3. 将PDF文档保存到一个文件中以供查看。
                    File.WriteAllBytes(pdfPath, pdfBytes);
                    System.Diagnostics.Process.Start(pdfPath);
                }
            }
        }
    }
}

3、C# 中将 URL 转换为 PDF

使用PDF Metamorphosis .Net将 URL转换为PDF 文件,代码如下,

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            SautinSoft.PdfMetamorphosis p = new SautinSoft.PdfMetamorphosis();

            if (p != null)
            {
                string htmlPath = @"http://www.google.com/";
                string pdfPath = @"c:\w3.pdf";

                // HTML 转换为 PDF
                int result = p.HtmlToPdfConvertFile(htmlPath, pdfPath);
            }
        }
    }
}

推荐文档