1

I want to display a pdf. My current code displayit using a pdf reader. But I want to open it in a seperate tab of the browser. How can i do it? I have a link button inside the web page. I have set this in onClick method. How to open it using back end code? (not using a link in aspx)

Here is my code

string name = ddlAppealList.SelectedValue.ToString();
int refNo = Convert.ToInt32(name);
string FilePath = Server.MapPath("~/filesPDF/" + refNo + ".pdf");
WebClient User = new WebClient();
Byte[] FileBuffer = User.DownloadData(FilePath);
if (FileBuffer != null)
{
     Response.ContentType = "application/pdf";
     Response.AddHeader("content-length", FileBuffer.Length.ToString());
     Response.BinaryWrite(FileBuffer);
}
Mike
  • 1,017
  • 4
  • 19
  • 34
  • 2
    Open the target in new window beforehand, for example `View PDF`. Gotten from [How to open PDF file in a new tab or window instead of downloading it (using asp.net)?](http://stackoverflow.com/questions/8294057/how-to-open-pdf-file-in-a-new-tab-or-window-instead-of-downloading-it-using-asp) – Keyur PATEL Sep 13 '16 at 09:12
  • 1
    isn't this behavior also tied to the brwoser configuration and/or availability of a inline pdf viewer ? – Steve B Sep 13 '16 at 11:29

3 Answers3

1

Response.ContentType = "Application/pdf"; Response.TransmitFile(PDFfilepath);

For opening the PDF file in a new tab or windows you can use following html code:

<a href="view.aspx" target="_blank">View</a>

I hope it helps you.

Ashouri
  • 906
  • 4
  • 19
  • @Ashouri, this code doesn't work as i expected. It opens a tab. But again close it automatically and as usal it asks to open the pdf file. How to fix it? – Mike Sep 13 '16 at 09:36
0

I encountered a similar situation a few weeks ago. This piece of code, inspired by this answer, helped me solve the issue:

Response.AppendHeader("Content-Disposition", new System.Net.Mime.ContentDisposition { Inline = true, FileName = "pdfname.pdf" }.ToString());
Community
  • 1
  • 1
avi
  • 912
  • 8
  • 22
0

Here is an example to open a pdf in a C# web application with ActionResult. You can also store the pdf as a byte[] in the database to make this code simpler.

public async Task<ActionResult> ViewPdf()
{    
    MemoryStream ms = new MemoryStream();
    FileStream stream = new FileStream("mypdf.pdf", FileMode.Open, FileAccess.Read);
    stream.CopyTo(ms);

    return File(ms.ToArray(), "application/pdf");
}
micah
  • 838
  • 7
  • 21