c#中将HTML文件转换成PDF文件
一、Pechkin:html->pdf
1.WinForm中轉換為PDF
a.在項目添加引用,引用 -> 管理NuGet程序包
?
b.在導出PDF按鈕中添加方法
?
1 SynchronizedPechkin sc = new SynchronizedPechkin(new GlobalConfig()2 .SetMargins(new Margins() { Left = 10, Right = 10, Top = 0, Bottom = 0 }) //設置邊距3 .SetPaperOrientation(false) //設置紙張方向為橫向4 .SetPaperSize(ConvertToHundredthsInch(210), ConvertToHundredthsInch(297))); //設置紙張為A4紙大小5 6 byte[] buf = sc.Convert(new ObjectConfig(), getWebContent());7 8 if (buf == null)9 { 10 MessageBox.Show("Error converting!"); 11 return; 12 } 13 14 File.WriteAllBytes(@"d:\google-news123.pdf", buf); 15 16 try 17 { 18 string fn = Path.GetTempFileName() + ".pdf"; 19 FileStream fs = new FileStream(fn, FileMode.Create); 20 fs.Write(buf, 0, buf.Length); 21 fs.Close(); 22 23 //MessageBox.Show("操作成功,文件已保存至F盤下", "提示"); 24 25 Process myProcess = new Process(); 26 myProcess.StartInfo.FileName = fn; 27 myProcess.Start(); 28 29 //SaveFileDialog(); 30 } 31 catch { }View Code
?相關方法
?
1 private int ConvertToHundredthsInch(int millimeter)2 {3 return (int)((millimeter * 10.0) / 2.54);4 }5 6 /// <summary>7 /// 獲取網站內容,包含了 HTML+CSS+JS8 /// </summary>9 /// <returns>String返回網頁信息</returns> 10 public string getWebContent() 11 { 12 try 13 { 14 WebClient MyWebClient = new WebClient(); 15 MyWebClient.Credentials = CredentialCache.DefaultCredentials; 16 //獲取或設置用于向Internet資源的請求進行身份驗證的網絡憑據 17 Byte[] pageData = MyWebClient.DownloadData("http://a4.keyue.com.cn/out/fwd/2fenhd/yuludan_new.asp?nstr=jwmlYCBYPDcHJlX2VudHJ5X2lkPTIyMjkyMDE1MDc5MTk1MjcyOSZ0b2lwPTExNA=="); 18 //從指定網站下載數據 19 string pageHtml = Encoding.UTF8.GetString(pageData); 20 //如果獲取網站頁面采用的是GB2312,則使用這句 21 bool isBool = isMessyCode(pageHtml);//判斷使用哪種編碼 讀取網頁信息 22 if (!isBool) 23 { 24 string pageHtml1 = Encoding.UTF8.GetString(pageData); 25 pageHtml = pageHtml1; 26 } 27 else 28 { 29 string pageHtml2 = Encoding.Default.GetString(pageData); 30 pageHtml = pageHtml2; 31 } 32 return pageHtml; 33 } 34 35 catch (WebException webEx) 36 { 37 Console.WriteLine(webEx.Message.ToString()); 38 return webEx.Message; 39 } 40 } 41 42 /// <summary> 43 /// 判斷是否有亂碼 44 /// </summary> 45 /// <param name="txt"></param> 46 /// <returns></returns> 47 public bool isMessyCode(string txt) 48 { 49 var bytes = Encoding.UTF8.GetBytes(txt); //239 191 189 50 for (var i = 0; i < bytes.Length; i++) 51 { 52 if (i < bytes.Length - 3) 53 if (bytes[i] == 239 && bytes[i + 1] == 191 && bytes[i + 2] == 189) 54 { 55 return true; 56 } 57 } 58 return false; 59 }相關方法
優缺點
1.只能保存到制定的目錄中,并且直接打開文件
2.網頁中的圖片導不出來
3.可能會出現亂碼
4.生成項目的時候需要把相應的DLL拷貝進去,不然不能生成
?
這是另外一種方法:http://www.cnblogs.com/lsgsanxiao/p/4878077.html
?
?
?
2.WEB網站中轉換為PDF
項目Demo?http://pan.baidu.com/s/1gfhRR8n
a.項目相關引用與上面相同
b.網站中采用JS調用一般處理程序的方式
?
1 function createPdf() { 2 window.open("CreatePdf.ashx?html=222222222222233324243"); 3 }View Code
?
1 using System;2 using System.Drawing.Printing;3 using System.IO;4 using System.Net;5 using System.Text;6 using System.Web;7 using Pechkin;8 using Pechkin.Synchronized;9 10 namespace WebApplication311 {12 /// <summary>13 /// CreatePdf 的摘要說明14 /// </summary>15 public class CreatePdf : IHttpHandler16 {17 18 public void ProcessRequest(HttpContext context)19 {20 string htmlFile = context.Request["html"];21 22 string html = getWebContent();23 SynchronizedPechkin sc = new SynchronizedPechkin(new GlobalConfig()24 .SetMargins(new Margins() { Left = 0, Right = 0, Top = 0, Bottom = 0 }) //設置邊距25 .SetPaperOrientation(false) //設置紙張方向為橫向26 .SetPaperSize(ConvertToHundredthsInch(210), ConvertToHundredthsInch(297))); //設置紙張大小50mm * 100mm27 28 byte[] buf = sc.Convert(new ObjectConfig(), html);29 30 if (buf == null)31 {32 context.Response.ContentType = "text/plain";33 context.Response.Write("Error converting!");34 }35 36 try37 {38 context.Response.Clear();39 40 41 //方式1:提示瀏覽器下載pdf 42 context.Response.AddHeader("content-disposition", "attachment;filename=" + htmlFile + ".pdf");43 context.Response.ContentType = "application/octet-stream";44 context.Response.BinaryWrite(buf);45 46 //方式2:直接在瀏覽器打開pdf47 //context.Response.ContentType = "application/pdf";48 //context.Response.OutputStream.Write(buf, 0, buf.Length);49 50 context.Response.End();51 52 }53 catch (Exception e)54 {55 context.Response.ContentType = "text/plain";56 context.Response.Write(e.Message);57 }58 }59 60 public bool IsReusable61 {62 get63 {64 return false;65 }66 }67 68 private int ConvertToHundredthsInch(int millimeter)69 {70 return (int)((millimeter * 10.0) / 2.54);71 }72 73 /// <summary>74 /// 獲取網站內容,包含了 HTML+CSS+JS75 /// </summary>76 /// <returns>String返回網頁信息</returns>77 public string getWebContent()78 {79 try80 {81 WebClient MyWebClient = new WebClient();82 MyWebClient.Credentials = CredentialCache.DefaultCredentials;83 //獲取或設置用于向Internet資源的請求進行身份驗證的網絡憑據84 Byte[] pageData = MyWebClient.DownloadData("http://a4.keyue.com.cn/out/fwd/2fenhd/yuludan.asp?nstr=AAfFJb_SVvcHJlX2VudHJ5X2lkPTIyMzEyMDE1MDgxMTY0NDUzOSZ0b2lwPTExNA==");85 //從指定網站下載數據86 string pageHtml = Encoding.UTF8.GetString(pageData);87 //如果獲取網站頁面采用的是GB2312,則使用這句 88 bool isBool = isMessyCode(pageHtml);//判斷使用哪種編碼 讀取網頁信息89 if (!isBool)90 {91 string pageHtml1 = Encoding.UTF8.GetString(pageData);92 pageHtml = pageHtml1;93 }94 else95 {96 string pageHtml2 = Encoding.Default.GetString(pageData);97 pageHtml = pageHtml2;98 }99 return pageHtml; 100 } 101 102 catch (WebException webEx) 103 { 104 Console.WriteLine(webEx.Message.ToString()); 105 return webEx.Message; 106 } 107 } 108 109 /// <summary> 110 /// 判斷是否有亂碼 111 /// </summary> 112 /// <param name="txt"></param> 113 /// <returns></returns> 114 public bool isMessyCode(string txt) 115 { 116 var bytes = Encoding.UTF8.GetBytes(txt); //239 191 189 117 for (var i = 0; i < bytes.Length; i++) 118 { 119 if (i < bytes.Length - 3) 120 if (bytes[i] == 239 && bytes[i + 1] == 191 && bytes[i + 2] == 189) 121 { 122 return true; 123 } 124 } 125 return false; 126 } 127 } 128 }//***************************
Pechkin開源組件使用wkhtmlbox,可以解析CSS樣式,將網頁轉換為PDF文件,支持URL,或者HTML字符串。
在 Nuget 管理器中搜索“Pechkin”,請選擇 CPechkin For .Net20+,這個組件是作者在 Pechkin 基礎上修改的,剔除了 Common.Loging 依賴,描述中說項目必須是x86編譯,但我發現,設置成 Any CPU也可以,但是如果是Web項目,部署到IIS后,應用程序池高級設置中必須選擇啟用32位應用程序,否則運行會報錯。
包加載完畢后,會在項目根目錄下放置幾個DLL,這些是 Pechkin 依賴的,如果想刪除,請先將這幾個DLL拷貝到bin下
編譯后,BIN下面有7個相關的DLL,這就是 Pechkin 的全部
調用代碼很簡單
SynchronizedPechkin sc = new SynchronizedPechkin(new GlobalConfig()
? ? .SetMargins(new Margins() { Left = 50, Right = 50, Top = 50, Bottom = 50 }) //設置邊距
? ? .SetPaperOrientation(false) //設置紙張方向為橫向
? ? .SetPaperSize(ConvertToHundredthsInch(210), ConvertToHundredthsInch(297)) //設置紙張大小210mm * 297mm
);
?
byte[] buf = sc.Convert(new ObjectConfig(), html);
?
if (buf == null)
{
? ? MessageBox.Show("Error converting!");
}
?
try
{
? ? string fn = "D:\XXX.pdf";
? ? FileStream fs = new FileStream(fn, FileMode.Create);
? ? fs.Write(buf, 0, buf.Length);
? ? fs.Close();
?
? ? Process myProcess = new Process();
? ? myProcess.StartInfo.FileName = fn;
? ? myProcess.Start();
}
catch (Exception ex)
{
?? ?MessageBox.Show($"PDF {ex.Message}");
}
生成PDF
?
總結
以上是生活随笔為你收集整理的c#中将HTML文件转换成PDF文件的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 在 vscode 中使用 Git :拉取
- 下一篇: 解决: Failed to execut