码迷,mamicode.com
首页 > Web开发 > 详细

使用Select.HtmlToPdf 把html内容生成pdf文件

时间:2020-06-24 15:55:57      阅读:109      评论:0      收藏:0      [点我收藏+]

标签:内容   form   uil   static   rem   try   使用   调用   文件下载   

1、nuget 引用 

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();
            }
        }
    }
}

 

使用Select.HtmlToPdf 把html内容生成pdf文件

标签:内容   form   uil   static   rem   try   使用   调用   文件下载   

原文地址:https://www.cnblogs.com/lyl6796910/p/13187743.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!