zoukankan      html  css  js  c++  java
  • 使用Select.HtmlToPdf 把html内容生成pdf文件

    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();
                }
            }
        }
    }
  • 相关阅读:
    利用杨辉三角和阶乘计算组合数
    验证字符串是否为回文数
    利用线性同余产生伪随机数+可变参数使用
    根据RandomStr.java:使用类型转换生成六位验证字符串。
    Java语言基础问题
    从命令行输入参数值,输出求和值。
    愚公移山_节选(伪代码)
    CodeForces
    CodeForces
    E
  • 原文地址:https://www.cnblogs.com/lyl6796910/p/13187743.html
Copyright © 2011-2022 走看看