代碼篇css
瀏覽了不少實例,總找不到既能把HTML保存爲PDF,同時實現流拋出的,因此本身琢磨了許久,終於實現了這樣兩個需求的結合體,下面來貢獻一下吧~~html
下面咱們來選擇一個網頁打印下,保存爲PDF,並且實現流拋出保存,假設咱們選擇「http://www.cnblogs.com/ITGirl00/」app
頁面截圖如:ui
目標:咱們須要作出上面這個效果的PDF。url
1.步驟spa
2.按鈕的點擊處理代碼:.net
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());
}
(1)使用wkhtmltopdf時,PDF保存的文件夾不能有非Ansi字符,如中文、日文等,且轉換gb23十二、韓文charset、日文charset等非utf-8\ansi等網頁時,會出現亂碼code
(2)網頁上圖片沒法正確顯示是因爲圖片有連接orm