首页 > 编程技术 > csharp

c# 免费组件html转pdf的实现过程

发布时间:2022-6-9 13:17 作者:looper.zhuo

免费组件html转pdf

背景

我们在公司可能遇到一些文件转pdf的场景,这里主要讲述html转pdf。

通常在c#里面有很多html转pdf的组件,我们采用第三方的组件,比如 iTextSharp, aspose等,但是有些组件用起来复杂,需要很多配置,而且在转换出来之后可能出现排版不正确的场景

下面主要介绍Select.HtmlToPdf的使用,很简单且方面,可以一次性生成几百页不是问题,关键是免费哦。

1.在guget下载组件

如上有Select.HtmlToPdf和 Select.HtmlToPdf.netcore,两种的使用差不多,只是Select.HtmlToPdf.netcore支持css效果更好,不过Select.HtmlToPdf.netcore只支持win,不支持linux,这个有点坑,其他还好,接下来我们使用Select.HtmlToPdf.netcore进行演示

2.使用:直接上代码

 static void Main(string[] args)
        {
            try
            {
                string fullPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "文件夹", "文件夹下的html文件");
                string line = "";
                var testStr = new StringBuilder();
                using (StreamReader sr = new StreamReader(fullPath))
                {
                    while ((line = sr.ReadLine()) != null)
                    {
                        testStr.Append(line);
                    }
                }
                SelectPdf.HtmlToPdf converter = new SelectPdf.HtmlToPdf();
                PdfDocument doc = new PdfDocument();
                for (int i = 0; i < 10; i++)
                {
                    testStr.Replace("#ImageUrl#", Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "文件夹", "文件夹下的图片"));//由于html中图片,使用相对地址解析不出来,所以使用替换方式去解决
                    var docStr = converter.ConvertHtmlString(testStr.ToString());
                    doc.Append(docStr);
                }
                doc.Save("xxxx");保存到xxx路径下
                doc.Close();
 
            }
            catch (Exception e)
            {
                //dosomething 
            }
            Console.ReadLine();
        }
    }

如上一次性打印多张pdf,思路:

1.在本地找到要转换的html文件,当然你也可以配置在程序里面,通过流的形式读出来,也可用file的方法去读,拿到html字符串

2.创建一个html转pdf的对象,创建一个新的pdf文件对象

3.通过html转pdf对象的converthtmlstring去获取html字符串,另外还提供converurl的方法去把一个网页转换换成pdf,是不是很方便切功能强大。

4.save用来保存pdf的路径,关闭pdf对象,操作文成,即可看到

这样就是实现了html 转pdf,另外,这个组件还提供了很多api可用

附上链接:https://selectpdf.com/docs/Index.htm

C#如何将html转pdf

public string HtmlToPdf(string url)
        {
            bool success = true;
           // string dwbh = url.Split('?')[1].Split('=')[1];
            //CommonBllHelper.CreateUserDir(dwbh);
            //url = Request.Url.Host + "/html/" + url;
            string guid = DateTime.Now.ToString("yyyyMMddhhmmss");
            string pdfName =   "1.pdf";
            //string path = Server.MapPath("~/kehu/" + dwbh + "/pdf/") + pdfName;
            string path = "D:\\" + pdfName;
            try
            {
                if (string.IsNullOrEmpty(url) || string.IsNullOrEmpty(path))
                    success = false;
                string str = Server.MapPath("~\\bin\\wkhtmltopdf.exe");
                Process p = System.Diagnostics.Process.Start(str, url+" "+path);
                p.WaitForExit();
                if (!System.IO.File.Exists(str))
                    success = false;
                if (System.IO.File.Exists(path))
                {
                    FileStream fs = new FileStream(path, FileMode.Open);
                    byte[] bytes = new byte[(int)fs.Length];
                    fs.Read(bytes, 0, bytes.Length);
                    fs.Close();
                    if (Request.UserAgent != null)
                    {
                        string userAgent = Request.UserAgent.ToUpper();
                        if (userAgent.IndexOf("FIREFOX", StringComparison.Ordinal) <= 0)
                        {
                            Response.AddHeader("Content-Disposition",
                                          "attachment;  filename=" + HttpUtility.UrlEncode(pdfName, Encoding.UTF8));
                        }
                        else
                        {
                            Response.AddHeader("Content-Disposition", "attachment;  filename=" + pdfName);
                        }
                    }
                    Response.ContentEncoding = Encoding.UTF8;
                    Response.ContentType = "application/octet-stream";
                    //通知浏览器下载文件而不是打开
                    Response.BinaryWrite(bytes);
                    Response.Flush();
                    Response.End();
                    fs.Close();
                    System.IO.File.Delete(path);
                }
                else
                {
                    Response.Write("文件未找到,可能已经被删除");
                    Response.Flush();
                    Response.End();
                }
            }
            catch (Exception ex)
            {
                success = false;
            }
            return "";
        }

protected void Page_Load(object sender, EventArgs e)
{
HtmlToPdf("http://www.deriva.cn");
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持猪先飞。

原文出处:https://blog.csdn.net/qq_40677590/article/details/102874012

标签:[!--infotagslink--]

您可能感兴趣的文章: