protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { Code.Login Starr_model = new Code.Login(); Code.InsuranceModel.InsuranceSegment_Result result = new InsuranceModel.InsuranceSegment_Result(); try { //判断接口请求是否成功 result = Code.InsuranceDecodeJson.Starr_GetLoginDecodeJson(); if (result.Success == true) { string filepath = Server.MapPath("~") + "\\GoldenPalmInsurance\\Code\\Starr.pdf"; string[] RequestArr = { "http://dicc2.ins24.com/ah/pdf_printer/policies/" + policyid + "", "application/pdf" }; //获取PDF文件流 Stream str = Starr_model.Starr_PrinterPDF(RequestArr, result.UserCookie); StreamReader reader = new StreamReader(str, Encoding.UTF8); using (FileStream fileStream = new FileStream("" + filepath + "", FileMode.Create, FileAccess.Write)) { byte[] data = Encoding.UTF8.GetBytes(reader.ToString()); while (true) { int size = str.Read(data, 0, data.Length); if (size > 0) { fileStream.Write(data, 0, size); } else { break; } } } //这里是你文件在项目中的位置,根目录下就这么写 String FullFileName = filepath; Response.Clear(); Response.ClearHeaders(); Response.Buffer = false; Response.ContentType = "application/pdf"; Response.AddHeader("Content-Disposition", "attachment;filename=" + policyid + ".pdf"); Response.WriteFile(FullFileName); } } catch (Exception ex) { Response.Write(ex.Message); } finally { System.Web.HttpContext.Current.Response.Flush(); System.Web.HttpContext.Current.Response.End(); Response.Close(); } } }
请求返回的pdf文件流
/// <summary> /// /// </summary> /// <param name="args"></param> /// <param name="UserCookie"></param> /// <returns></returns> public Stream Starr_PrinterPDF(String[] args, CookieCollection UserCookie) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(args[0]);//将host和参数直接拼接 request.Method = "GET"; request.ContentType = args[1]; request.Accept = "*/*"; request.CookieContainer = new CookieContainer(); request.CookieContainer.Add(UserCookie);//设置req的cookie HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Console.WriteLine(((HttpWebResponse)response).StatusDescription); Stream dataStream = response.GetResponseStream(); return dataStream; }
导出的PDF文件可以用Adrode reader和福熙阅读器查看,如果出现乱码问题,请下载最新版本的reader软件。
时间: 2024-10-05 05:01:59