简体   繁体   中英

open PDF in new tab C#

i want to open the PDF file in new tab when i display it on the web. but without clicking just a function that open the file in a new tab. this is my display function:

private void DisplayPage()
    {        
        string path = CanvasWritingStepImages._pdfName;
        WebClient client = new WebClient();
        Byte[] buffer = client.DownloadData(path);

        if (buffer != null)
        {
            Response.ContentType = "application/pdf";
            Response.AddHeader("Content-Disposition", "inline; filename=Formulike.pdf");
            Response.AddHeader("content-length", buffer.Length.ToString());
            Response.BinaryWrite(buffer);
        }
        else
        {
            logger.Error("Buffer was Null!");
            throw new Exception("PDF ERROR");
        }
    }

i'm using "iTextSharp" to work with the PDF file. it's important that the PDF file will be open on a new tab without any clicking just by the function. i just found with button click that open a new tab.

i tried this: How to open PDF file in a new tab or window instead of downloading it (using asp.net)?

I had a very similar issue... see my question here .

Put your pdf creation code in the form load event of a new page. Then use the code below to open that page in a new tab.

string url = "myPDFpage.aspx";
string openWindowScript = string.Format("window.open({0}, '_blank');", url);         
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), Guid.NewGuid().ToString(), openWindowScript, true);         

If you're not using a ScriptManager you can replace the last line with the following:

Page.ClientScript.RegisterStartupScript(this.GetType(), Guid.NewGuid().ToString(), openWindowScript, true);

If your pdf needs variables to be created, pass them through a query string or store them in a session variable so the new page will have access to them.

The new tab/window will be blocked unless the user allows popups from your site or has their blocker turned off.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM