【C#】ASP.NET將WEB端HTML頁(yè)面轉(zhuǎn)換并導(dǎo)出PDF文件
當(dāng)前位置:點(diǎn)晴教程→知識(shí)管理交流
→『 技術(shù)文檔交流 』
通過(guò)Url地址或者h(yuǎn)tml內(nèi)容生成到PDF文件,并部署到IIS,轉(zhuǎn)換內(nèi)容不支持Webpack構(gòu)建的前端項(xiàng)目。 這里使用的是TuesPechkin,引用下面2個(gè)Nuget包 封裝簡(jiǎn)單工具類 /// <summary> /// html轉(zhuǎn)pdf幫助類 /// </summary> public static class HtmlToPdfHelper { private static readonly string _fileDir = "htmlToPdf"; private static readonly string _savePath = System.Web.Hosting.HostingEnvironment.MapPath("/" + _fileDir); private static IConverter _converter = null; //官方要求在程序生命周期內(nèi),只能實(shí)例化一次 private static string _domainUrl; /// <summary> /// 獲取當(dāng)前站點(diǎn)域名 /// </summary> /// <returns></returns> public static string DomainUrl { get { Uri uri = HttpContext.Current.Request.Url; _domainUrl = uri.Scheme + "://" + uri.Host; if (!uri.IsDefaultPort) { _domainUrl += ":" + uri.Port; } return _domainUrl; } } static HtmlToPdfHelper() { _converter = new ThreadSafeConverter( new RemotingToolset<PdfToolset>( new WinAnyCPUEmbeddedDeployment( new TempFolderDeployment()))); //_converter.Begin += ConverterOnBegin; //_converter.PhaseChange += ConverterOnPhaseChange; //_converter.ProgressChange += ConverterOnProgressChange; //_converter.Finish += ConverterOnFinish; _converter.Warning += new EventHandler<WarningEventArgs>((o, w) => { Console.WriteLine("HtmlToPdfHelper類,html轉(zhuǎn)換PDF,產(chǎn)生警告信息:" + w.WarningMessage); }); _converter.Error += new EventHandler<TuesPechkin.ErrorEventArgs>((o, e) => { Console.WriteLine("HtmlToPdfHelper類,html轉(zhuǎn)換PDF,產(chǎn)生錯(cuò)誤信息:" + e.ErrorMessage); }); } /// <summary> /// 轉(zhuǎn)換為pdf字節(jié) /// </summary> /// <param name="doc"></param> /// <returns></returns> private static byte[] Filing(IDocument doc) { byte[] result = _converter.Convert(doc); return result; } /// <summary> /// 構(gòu)建PDF服務(wù)器訪問(wèn)地址 /// </summary> /// <param name="pdfName"></param> /// <returns></returns> private static string BuildUrl(string pdfName) { return $@"{DomainUrl}/{_fileDir}/{pdfName}.pdf"; } /// <summary> /// 構(gòu)建PDF保存路徑 /// </summary> /// <param name="pdfName"></param> /// <returns></returns> private static string BuildSaveSrc(string pdfName) { return $@"{_savePath}\{pdfName}.pdf"; } /// <summary> /// 查找已轉(zhuǎn)換的PDF文件 /// </summary> /// <param name="pdfName">已保存PDF名稱</param> /// <returns>返回保存Url地址</returns> private static string FindSaveHtmlPdf(string pdfName) { //把文件讀進(jìn)文件流 var fileSrc = BuildSaveSrc(pdfName); if (!File.Exists(fileSrc)) { return string.Empty; } return BuildUrl(pdfName); } /// <summary> /// 保存已轉(zhuǎn)換的PDF文件 /// </summary> /// <param name="fileName">PDF文件名</param> /// <param name="bf">保存字節(jié)集</param> /// <returns>保存成功返回url</returns> private static string SaveHtmlToPdfFile(string fileName, byte[] bf) { var path = _savePath; if (!Directory.Exists(path)) { Directory.createDirectory(path); } System.IO.File.WriteAllBytes(BuildSaveSrc(fileName), bf); return BuildUrl(fileName); } /// <summary> /// 根據(jù)類型轉(zhuǎn)換PDF為字節(jié) /// </summary> /// <param name="document">保存文檔</param> /// <param name="type">保存的類型</param> /// <returns></returns> private static byte[] BuildDocumentByType(string document, EHtmlToPdfDocumentType type) { byte[] saveBuffer = null; if (type == EHtmlToPdfDocumentType.HtmlUrl) { saveBuffer = ConvertHtmlUrlToPDF(document); } else if (type == EHtmlToPdfDocumentType.HtmlText) { saveBuffer = ConvertHtmlTextToPDF(document); } return saveBuffer; } /// <summary> /// 轉(zhuǎn)換htmltext為PDF /// </summary> /// <param name="htmlText">html文檔內(nèi)容</param> /// <returns></returns> public static byte[] ConvertHtmlTextToPDF(string htmlText) { if (string.IsNullOrWhiteSpace(htmlText)) { new ArgumentNullException("htmlText", "html的內(nèi)容不能為空"); } var document = new HtmlToPdfDocument { GlobalSettings = { }, Objects = { new ObjectSettings { HtmlText = htmlText, WebSettings =new WebSettings { DefaultEncoding="UTF-8", LoadImages=true, } } }, }; var result = _converter.Convert(document); return result; } /// <summary> /// 轉(zhuǎn)換htmlUrl為PDF /// </summary> /// <param name="htmlText">html文檔內(nèi)容</param> /// <returns></returns> public static byte[] ConvertHtmlUrlToPDF(string htmlUrl) { if (string.IsNullOrWhiteSpace(htmlUrl)) { new ArgumentNullException("htmlUrl", "html的Url地址不能為空"); } var doc = new HtmlToPdfDocument(); doc.Objects.Add(new ObjectSettings { PageUrl = htmlUrl }); byte[] result = Filing(doc); return result; } /// <summary> /// 獲取Html轉(zhuǎn)換后的PDF文件Url(如果文件不存在,并先執(zhí)行保存,在返回url地址) /// </summary> /// <param name="pdfName">要保存PDF名稱</param> /// <param name="document">要保存的Hmtl文檔內(nèi)容,(例如,htmlTXT,htmlurl)</param> /// <param name="type">保存的type類型</param> /// <param name="IsCover">是否覆蓋(默認(rèn)不覆蓋)</param> /// <returns></returns> public static string GetHtmlToPdfSaveUrl(string pdfName, string document, EHtmlToPdfDocumentType type, bool IsCover = false) { string pdfSaveUrl = FindSaveHtmlPdf(pdfName); if (string.IsNullOrEmpty(pdfSaveUrl) || IsCover) { //獲取轉(zhuǎn)換成功后PDF字節(jié) byte[] saveBuffer = BuildDocumentByType(document, type); //返回保存成功后PDF文件url return SaveHtmlToPdfFile(pdfName, saveBuffer); } return pdfSaveUrl; } /// <summary> /// 下載Html轉(zhuǎn)換后的PDF文件字節(jié)流(如果文件不存在,并先執(zhí)行保存,在返回下載字節(jié)流) /// </summary> /// <param name="pdfName">要保存PDF名稱</param> /// <param name="document">要保存的Hmtl文檔內(nèi)容,(例如,htmlTXT,htmlurl)</param> /// <param name="type">保存的type類型</param> /// <param name="IsCover">是否覆蓋(默認(rèn)不覆蓋)</param> /// <returns></returns> public static byte[] DownloadHtmlToPdf(string pdfName, string document, EHtmlToPdfDocumentType type, bool IsCover = false) { byte[] saveBuffer = DownloadSaveHtmlToPdf(pdfName); if (saveBuffer == null || IsCover) { //獲取轉(zhuǎn)換成功后PDF字節(jié) saveBuffer = BuildDocumentByType(document, type); //保存PDF文件 SaveHtmlToPdfFile(pdfName, saveBuffer); return saveBuffer; } return saveBuffer; } /// <summary> /// 獲取已存在服務(wù)器上的PDF文件字節(jié) /// </summary> /// <param name="pdfName">文件名稱</param> /// <returns></returns> public static byte[] DownloadSaveHtmlToPdf(string pdfName) { //把文件讀進(jìn)文件流 var fileSrc = BuildSaveSrc(pdfName); if (!File.Exists(fileSrc)) { return null; } FileStream fs = new FileStream(fileSrc, FileMode.Open); byte[] file = new byte[fs.Length]; fs.Read(file, 0, file.Length); fs.Close(); return file; } } /// <summary> /// 文檔轉(zhuǎn)換類型 /// </summary> public enum EHtmlToPdfDocumentType { HtmlUrl = 0, HtmlText = 1, } 測(cè)試代碼 public string GetHtmlToPdf(string pdfName, string url) { if (string.IsNullOrWhiteSpace(url)) { string[] arrs = new string[] { "http://www.baidu.com", "https://news.qq.com/", "https://www.sogou.com/" }; var index = new Random().Next(0, arrs.Length); url = arrs[index]; } if (string.IsNullOrWhiteSpace(pdfName)) { pdfName = DateTime.Now.ToString("yyyyMMdd_HHmmss"); } var res = HtmlToPdfHelper.GetHtmlToPdfSaveUrl(pdfName, url, EHtmlToPdfDocumentType.HtmlUrl); return res; } 測(cè)試調(diào)用 轉(zhuǎn)換結(jié)果 該文章在 2023/5/15 10:17:35 編輯過(guò) |
關(guān)鍵字查詢
相關(guān)文章
正在查詢... |