c# 免費組件html轉(zhuǎn)pdf的實現(xiàn)過程
免費組件html轉(zhuǎn)pdf
背景
我們在公司可能遇到一些文件轉(zhuǎn)pdf的場景,這里主要講述html轉(zhuǎn)pdf。
通常在c#里面有很多html轉(zhuǎn)pdf的組件,我們采用第三方的組件,比如 iTextSharp, aspose等,但是有些組件用起來復雜,需要很多配置,而且在轉(zhuǎn)換出來之后可能出現(xiàn)排版不正確的場景
下面主要介紹Select.HtmlToPdf的使用,很簡單且方面,可以一次性生成幾百頁不是問題,關(guān)鍵是免費哦。
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.在本地找到要轉(zhuǎn)換的html文件,當然你也可以配置在程序里面,通過流的形式讀出來,也可用file的方法去讀,拿到html字符串
2.創(chuàng)建一個html轉(zhuǎn)pdf的對象,創(chuàng)建一個新的pdf文件對象
3.通過html轉(zhuǎn)pdf對象的converthtmlstring去獲取html字符串,另外還提供converurl的方法去把一個網(wǎng)頁轉(zhuǎn)換換成pdf,是不是很方便切功能強大。
4.save用來保存pdf的路徑,關(guān)閉pdf對象,操作文成,即可看到
這樣就是實現(xiàn)了html 轉(zhuǎn)pdf,另外,這個組件還提供了很多api可用
附上鏈接:https://selectpdf.com/docs/Index.htm
C#如何將html轉(zhuǎn)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("文件未找到,可能已經(jīng)被刪除"); Response.Flush(); Response.End(); } } catch (Exception ex) { success = false; } return ""; }
protected void Page_Load(object sender, EventArgs e) { HtmlToPdf("http://www.deriva.cn"); }
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
WinForm中變Enter鍵為Tab鍵實現(xiàn)焦點轉(zhuǎn)移的方法
這篇文章主要介紹了WinForm中變Enter鍵為Tab鍵實現(xiàn)焦點轉(zhuǎn)移的方法,主要通過一個ControlTools類來實現(xiàn)該功能,需要的朋友可以參考下2014-08-08c# List find()方法返回值的問題說明(返回結(jié)果為對象的指針)
本篇文章主要介紹了c#中List find()方法返回值的問題說明(返回結(jié)果為對象的指針) 需要的朋友可以過來參考下,希望對大家有所幫助2014-01-01C#中緩存System.Web.Caching用法總結(jié)
本文詳細講解了C#中緩存System.Web.Caching的用法,文中通過示例代碼介紹的非常詳細。對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-04-04