Force browser to download PDF document instead of opening it

后端 未结 5 1596
太阳男子
太阳男子 2020-12-01 12:14

I want to make the browser download a PDF document from server instead of opening the file in browser itself. I am using C#.

Below is my sample code which I used. It

5条回答
  •  日久生厌
    2020-12-01 12:46

    If you want to render the file(s) so that you could save them at your end instead of opening in the browser, you may try the following code snippet:

    //create new MemoryStream object and add PDF file’s content to outStream.
    MemoryStream outStream = new MemoryStream();
    
    //specify the duration of time before a page cached on a browser expires
    Response.Expires = 0;
    
    //specify the property to buffer the output page
    Response.Buffer = true;
    
    //erase any buffered HTML output
    Response.ClearContent();
    
    //add a new HTML header and value to the Response sent to the client
    Response.AddHeader(“content-disposition”, “inline; filename=” + “output.pdf”);
    
    //specify the HTTP content type for Response as Pdf
    Response.ContentType = “application/pdf”;
    
    //write specified information of current HTTP output to Byte array
    Response.BinaryWrite(outStream.ToArray());
    
    //close the output stream
    outStream.Close();
    
    //end the processing of the current page to ensure that no other HTML content is sent
    Response.End();
    

    However, if you want to download the file using a client application then you'll have to use the WebClient class.

提交回复
热议问题