我正在使用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();
答案 0 :(得分:21)
将content-disposition
更改为inline
而不是attachment
。
您的代码段的第二行将是
Response.AddHeader("content-disposition", "inline;filename=" + filename + ".pdf");
有关详细信息,请参阅Content-Disposition:What are the differences between "inline" and "attachment"?。
答案 1 :(得分:3)
试用此代码:
动作:
Response.AddHeader("content-disposition", "attachment;filename=" + filename + ".pdf");
要在新标签/窗口中打开:
@Html.ActionLink("view pdf", "getpdf", "somecontroller", null,
new { target = "_blank" })
OR
<a href="GeneratePdf.ashx?somekey=10" target="_blank">
答案 2 :(得分:0)
你应该看看&#34; Content-Disposition&#34;报头;例如设置&#34; Content-Disposition&#34;到&#34;附件;文件名= FileName.pdf&#34;将提示用户(通常)使用&#34;另存为:FileName.pdf&#34;对话,而不是打开它。但是,这需要来自正在进行下载的请求,因此您无法在重定向期间执行此操作。但是,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";
我认为它会对你有帮助......