隐藏

在.NET(C#)中使用Aspose.Pdf将HTML转成PDF的方法

发布:2023/1/3 22:25:34作者:管理员 来源:本站 浏览次数:306

1、安装引用Aspose.Pdf

1)使用Nuget界面管理器


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


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


2)使用Package Manager命令安装


PM> Install-Package Aspose.Pdf

注意:使用Aspose是需要有License的,如没有也可以网上找一下破解版本。


2、使用Aspose.Pdf将HTML转成PDF

使用Aspose.Pdf也可以将HTML文件转换PDF文件,代码如下,


using Aspose.Pdf;

using System;


namespace ConsoleApplication

{

   class Program

   {

       static void Main(string[] args)

       {

           var license = new Aspose.Pdf.License();

           license.SetLicense("Aspose.Pdf.lic");

           HtmlLoadOptions options = new HtmlLoadOptions();

           /*

            * 设置打印样式

             HtmlLoadOptions options = new HtmlLoadOptions

           {

               HtmlMediaType = HtmlMediaType.Print

           };*/

           Document pdfDocument = new Document("test.html", options);

           pdfDocument.Save("cjavapy.PDF");

           

           Console.ReadKey();

       }

   }

}

3、使用Aspose.Pdf将URL中HTML转换PDF

使用HttpClient请求获取URL中HTML,然后使用Aspose.Pdf将URL中HTML转换PDF,代码如下,


using Aspose.Pdf;

using System;

using System.Collections.Generic;

using System.IO;

using System.Linq;

using System.Net;

using System.Net.Http;

using System.Text;

using System.Threading.Tasks;


namespace ConsoleApplication

{

   class Program

   {


       private static Stream GetContentFromUrlAsStream(string url, ICredentials credentials = null)

       {

           using (var handler = new HttpClientHandler { Credentials = credentials })

           using (var httpClient = new HttpClient(handler))

           {

               return httpClient.GetStreamAsync(url).GetAwaiter().GetResult();

           }

       }

       static void Main(string[] args)

       {

           var license = new Aspose.Pdf.License();

           license.SetLicense("Aspose.Pdf.lic");

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

           // 设置页面大小A3,横向;

           LoadOptions options = new HtmlLoadOptions(url)

           {

               PageInfo = { Width = 842, Height = 1191, IsLandscape = true }

           };

           Document pdfDocument = new Document(GetContentFromUrlAsStream(url),options);

           pdfDocument.Save("cjavapy.PDF");


           Console.ReadKey();

       }

   }

}