新彩天欢迎您!
幻海优品

.NET(C#) 使用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);            }        }    }}

免责声明:以上内容(如有图片或视频亦包括在内)有转载其他网站资源,如有侵权请联系删除