wkhtmtopdf--高分辨率HTML轉PDF(三)


代碼篇

瀏覽了很多實例,總找不到既能把HTML保存為PDF,同時實現流拋出的,所以自己琢磨了許久,終於實現了這樣兩個需求的結合體,下面來貢獻一下吧~~

下面我們來選擇一個網頁打印下,保存為PDF,而且實現流拋出保存,假設我們選擇“http://www.cnblogs.com/ITGirl00/

頁面截圖如:

image

目標:我們需要做出上面這個效果的PDF。

1.步驟

  • 首先新建一個項目HTMLtoPDFOutPutStream
  • 新建目錄output;作為臨時輸出目錄
  • 新建resoure目錄,用於保存wkhtmltopdf.exe等各個組件
  • 接着添加一個WebForm1.aspx,在頁面上添加一個按鈕
  • 最后在按鈕的點擊事件上寫代碼

2.按鈕的點擊處理代碼:

  string fileName = Guid.NewGuid().ToString();
            string outputPath = Server.MapPath("output");
            string savepath = string.Format(outputPath + "\\" + fileName + ".pdf");//最終保存
 
            string url = "http://www.cnblogs.com/ITGirl00/";
 
            try
            {
                if (!string.IsNullOrEmpty(url) || !string.IsNullOrEmpty(savepath))
                {
                    Process p = new Process();
                    string resource = HttpContext.Current.Server.MapPath("resoure");
                    string dllstr = string.Format(resource + "\\wkhtmltopdf.exe");
 
                    if (System.IO.File.Exists(dllstr))
                    {
 
 
                        p.StartInfo.FileName = dllstr;
                        p.StartInfo.Arguments = " \"" + url + "\"  \"" + savepath + "\"";
                        p.StartInfo.UseShellExecute = false;
                        p.StartInfo.RedirectStandardInput = true;
                        p.StartInfo.RedirectStandardOutput = true;
                        p.StartInfo.RedirectStandardError = true;
                        p.StartInfo.CreateNoWindow = true;
                        p.Start();
                        p.WaitForExit();
 
                        try
                        {
                            FileStream fs = new FileStream(savepath, FileMode.Open);
                            byte[] file = new byte[fs.Length];
                            fs.Read(file, 0, file.Length);
                            fs.Close();
                            Response.Clear();
                            Response.AddHeader("content-disposition", "attachment; filename=" + fileName + ".pdf");//強制下載
                            Response.ContentType = "application/octet-stream";
                            Response.BinaryWrite(file);
                        }
                        catch (Exception ee)
                        {
 
                            throw new Exception(ee.ToString());
                        }
 
 
                    }
                }
 
 
            }
            catch (Exception ex)
            {
                throw new Exception(ex.ToString());
            }
 
 
3.效果圖
image
 
===小小提示===

(1)使用wkhtmltopdf時,PDF保存的文件夾不能有非Ansi字符,如中文、日文等,且轉換gb2312、韓文charset、日文charset等非utf-8\ansi等網頁時,會出現亂碼

(2)網頁上圖片無法正確顯示是由於圖片有鏈接

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM