說明:
- 當傳遞的參數字符過多時需將其壓縮纔可以進行get的請求;
- _domain是配置文件中的配置:<add key="Domain" value="http://localhost/hotelSys" /> ;
- _hqPdfFilePath同樣是配置文件的PDF保存路徑;
- HtmlToPdf.exe是一個程序,可以前往下載,下載地址: https://download.csdn.net/download/qq_35481871/12197661
- 在asp.net mvc中如何用return File實現下載文件時,需要注意的是將下載文件名進行編碼Url.Encode(downName),否則可能出現錯誤或文件名亂碼
protected static readonly string _domain = ConfigurationManager.AppSettings["Domain"];
/// <summary>
/// 下載Pdf行程單
/// </summary>
/// <param name="RouteBase"></param>
/// <param name="RouteList"></param>
/// <param name="DownName"></param>
/// <returns></returns>
[HttpPost]
public ActionResult DownSchedulePdf(string RouteBase, string RouteList, string DownName)
{
var downName = DownName + ".pdf";//下載名稱
var pdfname = "hq" + DateTime.Now.ToString("HHmmssffff") + ".pdf";//保存pdf名稱
var _pdfFilePath = _hqPdfFilePath + pdfname;//pdf文件路徑
try
{
#region 壓縮字符串
byte[] b1 = Compress(RouteBase);
var routeBase = Convert.ToBase64String(b1);
byte[] b2 = Compress(RouteList);
var routeList = Convert.ToBase64String(b2);
#endregion
var pageUrl = "";
if (_mvcTest == "Y")
{
pageUrl = "http://localhost" + Url.Action("SchedulePdf", "DownLoad", new { RouteBase = routeBase, RouteList = routeList });
}
else
{
pageUrl = _domain + Url.Action("SchedulePdf", "DownLoad", new { RouteBase = routeBase, RouteList = routeList });
}
//判斷是否有該路徑 沒有則創建
if (!Directory.Exists(_hqPdfFilePath))
{
Directory.CreateDirectory(_hqPdfFilePath);
}
#region 調用html轉pdf接口
//程序
string str = Server.MapPath("~/Exes/HtmlToPdf.exe");
//參數
var arguments = " \"" + pageUrl + "\" " + _pdfFilePath;
Process p = Process.Start(str, arguments);
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.RedirectStandardError = true;
p.WaitForExit();//等待進程關閉或退出執行以下步驟
p.Close();
#endregion
}
catch (Exception e)
{
Log.InfoFormat("error:{0}", e.Message);
}
return File(_pdfFilePath, "text/plain", Url.Encode(downName));
}