在浏览器中打开PDF而不是下载它

我正在使用iTextSharp在按钮点击时将面板打印成PDF。 单击按钮后,PDF正在下载到客户端的计算机。 而不是这个我需要在浏览器中打开PDF而不是下载。 用户可以从浏览器下载PDF到他的PC。

我正在使用以下代码:

Response.ContentType = "application/pdf"; Response.AddHeader("content-disposition", "attachment;filename=" + filename + ".pdf"); Response.Cache.SetCacheability(HttpCacheability.NoCache); StringWriter sw = new StringWriter(); HtmlTextWriter hw = new HtmlTextWriter(sw); pnl_print.RenderControl(hw); StringReader sr = new StringReader(sw.ToString()); Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 100f, 0f); HTMLWorker htmlparser = new HTMLWorker(pdfDoc); PdfWriter.GetInstance(pdfDoc, Response.OutputStream); pdfDoc.Open(); htmlparser.Parse(sr); pdfDoc.Close(); Response.Write(pdfDoc); Response.End(); sr.Close(); hw.Close(); sw.Close(); 

content-disposition更改为inline而不是attachment

那么你的片段的第二行就是

 Response.AddHeader("content-disposition", "inline;filename=" + filename + ".pdf"); 

请参阅内容处理:“内联”和“附件”之间有什么区别? 了解更多详情。

试试此代码:

行动:

 Response.AddHeader("content-disposition", "attachment;filename=" + filename + ".pdf"); 

要在新标签/窗口中打开:

 @Html.ActionLink("view pdf", "getpdf", "somecontroller", null, new { target = "_blank" }) 

要么

  

你应该看一下“Content-Disposition”标题; 例如,将“Content-Disposition”设置为“attachment; filename = FileName.pdf”将提示用户(通常)使用“另存为:FileName.pdf”对话框,而不是打开它。 但是,这需要来自正在进行下载的请求,因此在重定向期间无法执行此操作。 但是,ASP.NET为此提供了Response.TransmitFile。 例如(假设您没有使用MVC,它有其他首选选项):

 Response.Clear(); Response.ContentType = "application/pdf"; Response.AppendHeader("Content-Disposition", "attachment; filename=FileName.pdf"); Response.TransmitFile(Server.MapPath("~/folder/Sample.pdf")); Response.End(); 

如果您尝试打开apicontroller中的文件将流转换为bytesarray然后填写内容

 HttpResponseMessage result = null; result = Request.CreateResponse(HttpStatusCode.OK); FileStream stream = File.OpenRead(path); byte[] fileBytes = new byte[stream.Length]; stream.Read(fileBytes, 0, fileBytes.Length); stream.Close(); result.Content = new ByteArrayContent(fileBytes); result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment"); result.Content.Headers.ContentDisposition.FileName = "FileName.pdf"; 

我认为它会对你有所帮助……