代碼篇
瀏覽了很多實例,總找不到既能把HTML保存為PDF,同時實現流拋出的,所以自己琢磨了許久,終于實現了這樣兩個需求的結合體,下面來貢獻一下吧~~
下面我們來選擇一個網頁打印下,保存為PDF,而且實現流拋出保存,假設我們選擇“http://www.survivalescaperooms.com/ITGirl00/”
頁面截圖如:
目標:我們需要做出上面這個效果的PDF。
1.步驟
2.按鈕的點擊處理代碼:
string fileName = Guid.NewGuid().ToString();
string outputPath = Server.MapPath("output");
string savepath = string.Format(outputPath + "http://" + fileName + ".pdf");//最終保存
string url = "http://www.survivalescaperooms.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 + "http://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.效果圖
(1)使用wkhtmltopdf時,PDF保存的文件夾不能有非Ansi字符,如中文、日文等,且轉換gb2312、韓文charset、日文charset等非utf-8/ansi等網頁時,會出現亂碼
(2)網頁上圖片無法正確顯示是由于圖片有鏈接
Technorati 標簽: wkhtmtopdf,HTMLTOPDF,HTML轉換PDF,outputStream
|
新聞熱點
疑難解答