Opening a PDF in browser instead of downloading it

前端 未结 3 740
慢半拍i
慢半拍i 2020-12-09 17:19

I\'m using iTextSharp to print a panel into PDF on button click. After clicking on the button, the PDF is downloading to the client\'s computer. Instead of this I need the P

相关标签:
3条回答
  • 2020-12-09 17:41

    You should look at the "Content-Disposition" header; for example setting "Content-Disposition" to "attachment; filename=FileName.pdf" will prompt the user (typically) with a "Save as: FileName.pdf" dialog, rather than opening it. This, however, needs to come from the request that is doing the download, so you can't do this during a redirect. However, ASP.NET offers Response.TransmitFile for this purpose. For example (assuming you aren't using MVC, which has other preferred options):

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

    If you are try to open then the file in apicontroller Convert stream to bytesarray and then Fill the content

    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";            
    

    I think it will help you...

    0 讨论(0)
  • 2020-12-09 17:44

    Change the content-disposition to inline instead of attachment.

    The second line of your snippet would then be

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

    See Content-Disposition:What are the differences between "inline" and "attachment"? for further details.

    0 讨论(0)
  • 2020-12-09 17:51

    Try This Code :

    Action:

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

    To open in new Tab/Window:

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

    OR

    <a href="GeneratePdf.ashx?somekey=10" target="_blank">
    
    0 讨论(0)
提交回复
热议问题