How to Open a PDF File in a New Window in Aspnet

PDF files are read-only documents that websites publish for viewers and customers. PDF files can be opened through web application programming languages such as C# in ASP.NET. The file can be opened in a new browser window, or programmers can choose to keep the opened file in the current browser window. Opening a PDF file in ASP only takes a few lines of code.

Instructions

    • 1

      Turn off the buffer and set up the variables. In this example, the PDF is streamed, so the buffer is turned off so it shows in the reader's browser immediately. The following lines of code set up the variables:
      Context.Response.Buffer = false
      GO
      FileStream file = null
      GO
      byte[] mybuff = new byte[1024]
      GO
      long count;

    • 2

      Point the file variable to the location of the file. The following code sets the file variable to a PDF file located on the \"C\" drive:
      file = File.OpenRead(\"C:\\myPDF.pdf\");

    • 3

      Loop through the PDF file and print it to the screen. The following code writes the PDF to a browser window byte-by-byte:
      while ((count = file.Read(mybuff, 0, mybuff.Length)) > 0)

                 {
      if (Context.Response.IsClientConnected)
      {
      Context.Response.OutputStream.Write(mybuff, 0, mybuff.Length)

      GO

                         Context.Response.Flush()

      GO

                     }
      }
    • 4

      Place the code from Steps 1 through 3 into a function named \"OpenPDF\" and create a button on the form that calls it. The following is an example of an ASP.NET button that calls the function when clicked and displays the PDF:
      <asp:Button OnClick=\"OpenPDF\" Text=\"Open PDF\" runat=\"server\" />

Related Searches

References

You May Also Like

Related Ads

Watch Video

The 2014 Holiday Gadget Roundup