开发者

ASP.NET show PDF file to user instead of "save as" dialog

My ASP.NET application return PDF file to user using code below

Context.Response.Clear();
Context.Response.ContentType = "application/pdf";
Context.Response.TransmitFile(optionEntityCmd.PathToSave);
Context.Response.End();

This code show Save As browser dialog, is it possible instead of Save As dialog load PDF file dire开发者_JAVA百科ctly in browser?


You could append the Content-Disposition header:

Context.Response.AppendHeader(
    "Content-Disposition", 
    "inline; filename=foo.pdf"
);


Is it a dynamically created file? If not, you can just hyperlink or Response.Redirect to it I believe.


I do not know for sure for classic asp.net but using mvc, streaming it to the user does what you want:

MemoryStream stream = PDF.GeneratePDFByStream();
stream.Flush(); //Always catches me out
stream.Position = 0; //Not sure if this is required
return stream;

with

public static MemoryStream GeneratePDFByStream() {
    var doc1 = new Document();
    //use a variable to let my code fit across the page...
    string path = AppDomain.CurrentDomain.BaseDirectory + "PDFs";
    MemoryStream stream = new MemoryStream();
    PdfWriter writer = PdfWriter.GetInstance(doc1, stream);
    writer.CloseStream = false;

    // Actual Writing
    doc1.Open();
    // writing comes here, you will probably just load the PDF in a stream?
    doc1.Close();

    return stream;
}

And your MVC controller returns something like

return File(GetPDFStream(id), "application/pdf");

So, I know this is not the exact answer you are looking for, but maybe you should try to stream your PDF to the user as it will open it in a new tab as far as I ever tested it.

From the top of my head, you should get something like:

Response.Clear(); 
Response.ContentType = "application/pdf"; 
Response.OutputStream.Write( objMemoryStream.ToArray(), 0,        
Convert.ToInt32(objMemoryStream.Length)); 
Response.Flush(); 
try { Response.End(); } catch{}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜