利用SelectPdf外掛將網頁生成PDF

conanl5566發表於2020-10-26

簡介

適用於.NET Framework和.NET Core的HTML至PDF轉換器

SelectPdf提供的線上html到pdf轉換器使用.NET的Select.Pdf庫中的html到pdf轉換器。用於.NET的SelectPdf SDK提供了建立新pdf文件,載入現有文件,合併現有pdf文件,拆分pdf文件,向新建立或現有pdf文件新增元素的可能性。
用於.NET的Select.Pdf庫中的html到pdf轉換器可以在任何.NET應用程式中使用,從完整的網頁或原始html程式碼生成pdf文件,就像線上html到pdf轉換器一樣。該免費試用版包含可立即使用的示例,這些示例以Windows窗體,ASP.NET,帶有Razor和ASPX引擎的ASP.NET MVC的C#和VB.NET編碼。

實現

1、nuget 引用 

Install-Package Select.HtmlToPdf

2、方法

using SelectPdf;using System.Collections.Specialized;using System.IO;using System.Web;
namespace BQoolCommon.Helpers.File{    public class WebToPdf    {        public WebToPdf()        {            //SelectPdf.GlobalProperties.LicenseKey = "your-license-key";        }
        /// <summary>        /// 將 Html 轉成 PDF,並儲存成檔案        /// </summary>        /// <param name="html">html</param>        /// <param name="fileName">絕對路徑</param>        public void SaveToFileByHtml(string html, string fileName)        {            var doc = SetPdfDocument(html);            doc.Save(fileName);        }
        /// <summary>        /// 傳入 Url 轉成 PDF,並儲存成檔案        /// </summary>        /// <param name="url">url</param>        /// <param name="fileName">絕對路徑</param>        /// <param name="httpCookies">Cookies</param>        public void SaveToFileByUrl(string url, string fileName, NameValueCollection httpCookies)        {            var doc = SetPdfDocument(url, httpCookies);            doc.Save(fileName);        }
        /// <summary>        /// 將 Html 轉成 PDF,並輸出成 byte[] 格式        /// </summary>        /// <param name="html">html</param>        /// <returns></returns>        public byte[] GetFileByteByHtml(string html)        {            var doc = SetPdfDocument(html);            return doc.Save();        }
        /// <summary>        /// 傳入 Url 轉成 PDF,並輸出成 byte[] 格式        /// </summary>        /// <param name="url">url</param>        /// <param name="httpCookies">Cookies</param>        /// <returns></returns>        public byte[] GetFileByteByUrl(string url, NameValueCollection httpCookies)        {            var doc = SetPdfDocument(url, httpCookies);            return doc.Save();        }
        /// <summary>        /// 將 Html 轉成 PDF,並輸出成 Stream 格式        /// </summary>        /// <param name="html">html</param>        /// <returns></returns>        public Stream GetFileStreamByHtml(string html)        {            var doc = SetPdfDocument(html);            var pdfStream = new MemoryStream();
            doc.Save(pdfStream);            pdfStream.Position = 0;
            return pdfStream;        }
        /// <summary>        /// 傳入 Url 轉成 PDF,並輸出成 Stream 格式        /// </summary>        /// <param name="html">html</param>        /// <returns></returns>        public Stream GetFileStreamByUrl(string url, NameValueCollection httpCookies)        {            var doc = SetPdfDocument(url, httpCookies);            var pdfStream = new MemoryStream();
            doc.Save(pdfStream);            pdfStream.Position = 0;
            return pdfStream;        }
        private PdfDocument SetPdfDocument(string html)        {            var converter = new HtmlToPdf();
            converter.Options.WebPageWidth = 1200;            html = HttpUtility.HtmlDecode(html);
            return converter.ConvertHtmlString(html);        }
        private PdfDocument SetPdfDocument(string url, NameValueCollection httpCookies)        {            var converter = new HtmlToPdf();            converter.Options.WebPageWidth = 1200;
            if (httpCookies != null && httpCookies.Count != 0)            {                converter.Options.HttpCookies.Add(httpCookies);            }
            return converter.ConvertUrl(url);        }
    }}

3、呼叫

/// <summary>        /// 下載pdf        /// </summary>        public void Downpdf(string data)        {            var stream = new BQoolCommon.Helpers.File.WebToPdf().GetFileStreamByHtml(Gethtml(data));            Response.Clear();            //二進位制流資料(如常見的檔案下載)            Response.ContentType = "application/octet-stream";            //通知瀏覽器下載檔案而不是開啟            Response.AddHeader("Content-Disposition", "attachment;  filename=" + HttpUtility.UrlEncode("Profit and Loss Statement.pdf", System.Text.Encoding.UTF8));            var bytes = StreamToBytes(stream);            Response.BinaryWrite(bytes);            Response.Flush();            stream.Close();            stream.Dispose();
            Response.End();        }

那麼如何獲取指定頁面的html 呢 傳入對應的model  獲得指定動態的html​​​​​​​

private string Gethtml(string data)        {            string str = "";
            str = this.ControllerContext.RenderViewToString("ProfitDetails", data);
            return str;        }

​​​​​​​

using BQoolCommon.Helpers.Format;using Newtonsoft.Json;using OrdersManager.Models.ViewModel.Report;using System;using System.Collections.Generic;using System.IO;using System.Linq;using System.Web;using System.Web.Mvc;
namespace OrdersManager.Web.Infrastructure{    public static class HelperExtensions    {        public static string RenderViewToString(this ControllerContext context, string viewName, string data)        {            if (string.IsNullOrEmpty(viewName))                viewName = context.RouteData.GetRequiredString("action");
            context.Controller.ViewData.Model = JsonConvert.DeserializeObject<ProfitDetailsmodel>(StringTools.Base64Decode(StringTools.Base64Decode(data)));
            using (var sw = new StringWriter())            {                ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(context, viewName);                var viewContext = new ViewContext(context,                                                  viewResult.View,                                                  context.Controller.ViewData,                                                  context.Controller.TempData,                                                  sw);                try                {                    viewResult.View.Render(viewContext, sw);                }                catch (Exception ex)                {                    throw;                }
                return sw.GetStringBuilder().ToString();            }        }    }}

 

相關文章