How to open PDF file in a new tab or window instead of downloading it (using asp.net)?
Asked Answered
P

7

20

This is the code for downloading the file.

System.IO.FileStream fs = new System.IO.FileStream(Path+"\\"+fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
byte[] ar = new byte[(int)fs.Length];
fs.Read(ar, 0, (int)fs.Length);
fs.Close();

Response.AddHeader("content-disposition", "attachment;filename=" + AccNo+".pdf");
Response.ContentType = "application/octectstream";
Response.BinaryWrite(ar);
Response.End();

When this code is executed, it will ask user to open or save the file. Instead of this I need to open a new tab or window and display the file. How can I achieve this?

NOTE:

File won't necessary be located in the website folder. It might be located in an other folder.

Plyler answered 28/11, 2011 at 9:50 Comment(2)
You could try content-disposition: inline instead of attachment - See this articleExposed
this article might help you aspalliance.com/…Jenijenica
K
27
Response.ContentType = contentType;
HttpContext.Current.Response.AddHeader("Content-Disposition", "inline; filename=" + fileName);
Response.BinaryWrite(fileContent);

And

<asp:LinkButton OnClientClick="openInNewTab();" OnClick="CodeBehindMethod".../>

In javaScript:

<script type="text/javascript">
    function openInNewTab() {
        window.document.forms[0].target = '_blank'; 
        setTimeout(function () { window.document.forms[0].target = ''; }, 0);
    }
</script>

Take care to reset target, otherwise all other calls like Response.Redirect will open in a new tab, which might be not what you want.

Kirkcudbright answered 18/11, 2016 at 17:10 Comment(1)
Here I used this javascript, still my pdf is downloading in same tab, If I comment //setTimeout(function () { window.document.forms[0].target = ''; }, 0); then pdf is being downloaded in new tab, however now other calls are getting opened in new tab as mentioned above, Is there any workaround for this?Curvature
C
20

Instead of loading a stream into a byte array and writing it to the response stream, you should have a look at HttpResponse.TransmitFile

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

If you want the PDF to open in a new window you would have to open the downloading page in a new window, for example like this:

<a href="viewpdf.aspx" target="_blank">View PDF</a>
Century answered 28/11, 2011 at 10:8 Comment(5)
The first step im interested to know more. The second step is not practical in my program. bcz i cannot sent the original path to it. Using the first step can i redirect the file to another window?Plyler
You can not open a new window from server side. You will have to open the download page in a new window, and in that window use TransmitFile to return the file to the user.Century
what does your link look like? Why can't you add a target to it? You can add it with JavaScript if for some reason you can't change the a tag's source (e.g. it's generated for you)Juryrigged
You can serverside like this. Hyperlink hyper = new HyperLink();hyper.NavigateUrl="PDFViewer.aspx"; hyper.Attributes.Add("target","_blank");Husserl
Unfortunately, this only works if you have an actual file stored somewhere. If you have a byte array that has been generated for example, there is no 'path' - rendering Response.TransmitFile useless. At least that's what I'm running into.Fernandafernande
D
2

this may help

Response.Write("<script>");
Response.Write("window.open('../Inventory/pages/printableads.pdf', '_newtab');");
Response.Write("</script>");
Doridoria answered 28/11, 2011 at 9:55 Comment(3)
How will i call that downloading file into this?? that's my problem.Plyler
I should create it for reading and later it can be saved too. The problem is i cannot give the original name of the file or path too with the file. So i must do the above step to download it and then open it with another name.Plyler
Can you make a temp copy on the server?Bogard
M
1

You have to create either another page or generic handler with the code to generate your pdf. Then that event gets triggered and the person is redirected to that page.

Mouthful answered 25/3, 2015 at 14:23 Comment(0)
D
1

Here I am using iTextSharp dll for generating PDF file. I want to open PDF file instead of downloading it. So I am using below code which is working fine for me. Now pdf file is opening in browser ,now dowloading

        Document pdfDoc = new Document(PageSize.A4, 25, 10, 25, 10);
        PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
        pdfDoc.Open();
        Paragraph Text = new Paragraph("Hi , This is Test Content");
        pdfDoc.Add(Text);
        pdfWriter.CloseStream = false;
        pdfDoc.Close();
        Response.Buffer = true;
        Response.ContentType = "application/pdf";
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.End();

If you want to download file, add below line, after this Response.ContentType = "application/pdf";

Response.AddHeader("content-disposition", "attachment;filename=Example.pdf");   
Drennan answered 17/3, 2018 at 15:26 Comment(0)
L
0

you can return a FileResult from your MVC action.

*********************MVC action************

    public FileResult OpenPDF(parameters)
    {
       //code to fetch your pdf byte array
       return File(pdfBytes, "application/pdf");
    }

**************js**************

Use formpost to post your data to action

    var inputTag = '<input name="paramName" type="text" value="' + payloadString + '">';
    var form = document.createElement("form");
    jQuery(form).attr("id", "pdf-form").attr("name", "pdf-form").attr("class", "pdf-form").attr("target", "_blank");
    jQuery(form).attr("action", "/Controller/OpenPDF").attr("method", "post").attr("enctype", "multipart/form-data");
    jQuery(form).append(inputTag);
    document.body.appendChild(form);
    form.submit();
    document.body.removeChild(form);
    return false;

You need to create a form to post your data, append it your dom, post your data and remove the form your document body.

However, form post wouldn't post data to new tab only on EDGE browser. But a get request works as it's just opening new tab with a url containing query string for your action parameters.

Lavoie answered 27/7, 2017 at 5:32 Comment(0)
L
-5

Use this code. This works like a champ.

Process process = new Process();
process.StartInfo.UseShellExecute = true;
process.StartInfo.FileName = outputPdfFile;
process.Start();
Lytle answered 26/2, 2013 at 18:56 Comment(3)
I tried this method and it works really well, thanks :)Carolacarolan
Your C# code runs on the server. Therefore, Process.Start starts a process on the server, not your computer. It is fundamentally impossible for you to start a process directly on the client.Auntie
Thanks, Works for me.Depreciable

© 2022 - 2024 — McMap. All rights reserved.