日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

通过html文件生成PDF文件

發(fā)布時(shí)間:2025/3/20 编程问答 22 豆豆
生活随笔 收集整理的這篇文章主要介紹了 通过html文件生成PDF文件 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
/// <summary> /// 獲取html內(nèi)容,轉(zhuǎn)成PDF(注冊(cè))/// </summary> public void DownloadPDFByHTML(string html,string FileName) {WebClient wc = new WebClient(); // wc.Encoding = System.Text.Encoding.UTF8; //string htmlText = getWebContent(); string htmlText = html;//getWebContent(); string DataName = FileName;//下載文件名byte[] pdfFile =ConvertHtmlTextToPDF(htmlText);//如果需要保存到服務(wù)器 //string fileId = "/file_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".pdf"; //System.IO.File.WriteAllBytes(path + fileId, pdfFile); Response.ContentType = "application/octet-stream"; //通知瀏覽器下載文件 Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(DataName + ".pdf", System.Text.Encoding.UTF8)); Response.BinaryWrite(pdfFile);//文件下載二進(jìn)制流 Response.Flush(); Response.End(); 刪除服務(wù)器文件,通知下載成功之后,刪除 //FileInfo fi = new FileInfo(path + fileId); //if (fi.Exists) //{ // fi.Delete(); //} }/// <summary> /// 獲取網(wǎng)站內(nèi)容,包含了 HTML+CSS+JS /// </summary> /// <returns>String返回網(wǎng)頁(yè)信息</returns> public string getWebContent() { try { string INPATH = System.Web.HttpContext.Current.Server.MapPath("~/EmailTemplet/sa.html"); WebClient MyWebClient = new WebClient(); MyWebClient.Credentials = CredentialCache.DefaultCredentials; //獲取或設(shè)置用于向Internet資源的請(qǐng)求進(jìn)行身份驗(yàn)證的網(wǎng)絡(luò)憑據(jù) Byte[] pageData = MyWebClient.DownloadData(INPATH); //從指定網(wǎng)站下載數(shù)據(jù) string pageHtml = Encoding.UTF8.GetString(pageData); //如果獲取網(wǎng)站頁(yè)面采用的是GB2312,則使用這句 bool isBool =isMessyCode(pageHtml);//判斷使用哪種編碼 讀取網(wǎng)頁(yè)信息 if (!isBool) { string pageHtml1 = Encoding.UTF8.GetString(pageData); pageHtml = pageHtml1; } else { string pageHtml2 = Encoding.Default.GetString(pageData); pageHtml = pageHtml2; } return pageHtml; }catch (WebException webEx) { Console.WriteLine(webEx.Message.ToString()); return webEx.Message; } }/// <summary> /// 判斷是否有亂碼 /// </summary> /// <param name="txt"></param> /// <returns></returns> public static bool isMessyCode(string txt) { var bytes = Encoding.UTF8.GetBytes(txt); for (var i = 0; i < bytes.Length; i++) { if (i < bytes.Length - 3) if (bytes[i] == 239 && bytes[i + 1] == 191 && bytes[i + 2] == 189) { return true; } } return false; }/// <summary> /// 將Html文字 輸出到PDF檔里 /// </summary> /// <param name="htmlText"></param> /// <returns></returns> public static byte[] ConvertHtmlTextToPDF(string htmlText) { if (string.IsNullOrEmpty(htmlText)) { return null; } //避免當(dāng)htmlText無(wú)任何html tag標(biāo)簽的純文字時(shí),轉(zhuǎn)PDF時(shí)會(huì)掛掉,所以一律加上<p>標(biāo)簽 //htmlText = "<p>" + htmlText + "</p>"; MemoryStream outputStream = new MemoryStream();//要把PDF寫到哪個(gè)串流 byte[] data = Encoding.UTF8.GetBytes(htmlText);//字串轉(zhuǎn)成byte[] MemoryStream msInput = new MemoryStream(data); Document doc = new Document(PageSize.A4.Rotate(), 1, 1, 1, 1);//要寫PDF的文件,建構(gòu)子沒(méi)填的話預(yù)設(shè)直式A4(括號(hào)內(nèi)不填寫值默認(rèn)是A4縱向,否則是橫向) PdfWriter writer = PdfWriter.GetInstance(doc, outputStream); //指定文件預(yù)設(shè)開(kāi)檔時(shí)的縮放為100% PdfDestination pdfDest = new PdfDestination(PdfDestination.XYZ, 0, doc.PageSize.Height, 1f); //開(kāi)啟Document文件 doc.Open(); doc.Add(iTextSharp.text.PageSize.A5.Rotate()); //使用XMLWorkerHelper把Html parse到PDF檔里 XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, msInput, null, Encoding.UTF8, new UnicodeFontFactory()); //XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, msInput, null, Encoding.UTF8);//將pdfDest設(shè)定的資料寫到PDF檔 PdfAction action = PdfAction.GotoLocalPage(1, pdfDest, writer); writer.SetOpenAction(action); doc.Close(); msInput.Close(); outputStream.Close(); //回傳PDF檔案 return outputStream.ToArray();}//設(shè)置字體類 (如果字體設(shè)置有問(wèn)題,只能顯示英文) public class UnicodeFontFactory : FontFactoryImp { private static readonly string arialFontPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "arialuni.ttf");//arial unicode MS是完整的unicode字型。 private static readonly string FontTypePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "STKAITI.TTF");public override Font GetFont(string fontname, string encoding, bool embedded, float size, int style, BaseColor color, bool cached) { BaseFont bfChiness = BaseFont.CreateFont(@"C:\\WINDOWS\\FONTS\\STKAITI.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); //可用Arial或標(biāo)楷體,自己選一個(gè) BaseFont baseFont = BaseFont.CreateFont(FontTypePath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED); return new Font(bfChiness, size, style, color); } }轉(zhuǎn)載至:https://www.cnblogs.com/zhurunlai/p/7193201.html

?

轉(zhuǎn)載于:https://www.cnblogs.com/lijianli/p/9541411.html

總結(jié)

以上是生活随笔為你收集整理的通过html文件生成PDF文件的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。