How to Open a PDF File in ASP

by Susan Hare

The Portable Document Format (PDF) is popular on the Web to display data and files to end users, because it is a standard format that is not browser-specific. Most browsers support in-line display of PDF files, and the creators of the format, Adobe Systems, offer free PDF Reader applications. To open a PDF file in ASP, you have to use a scripting language. The default language in ASP is VBScript, which is Microsoft's server side scripting language. The only time this language can be used on the client side is in Microsoft Internet Explorer.

1

Create a new file in Notepad or your favorite programming interface. Name the file \"openPDF.asp\" and save it with your website.

2

Add code to your ASP file to create the body and HTML structure. Copy the code below to accomplish this:

<html> <body> <% <!-- Your VBScript code will go here --> %> </body> </html>

3

Create a variable for your file name and add it to the code section of your ASP file. Copy the example below:

Dim strPDF strPDF= \"C:\myDocument.pdf\"

4

Create a file stream object and load the file into it. The VBScript example below shows how to do this:

Set oFileStream = Server.CreateObject(\"ADODB.Stream\") oFileStream.Open oFileStream.Type = 1 'Binary oFileStream.LoadFromFile strPDF

5

Set the content type of the file to PDF and write the file to the browser. Use the following code to do these tasks:

Response.ContentType = \"application/pdf\" Response.AddHeader(\"Content-Disposition\", \"inline; filename=\" + strPDF) Response.BinaryWrite(oFileStream.Read)

6

Close your file stream and release the memory:

oFileStream.Close Set oFileStream= Nothing

Tip

  • check If you want your users to be able to save the PDF instead of open it, change the header from \"inline\" to \"attachment.\"

About the Author

Susan Hare began writing professionally in 2009. Many of her articles have been published on eHow. She writes on a varieity of topics including software, programming and home improvement. Hare is a professional consultant with a Bachelor of Science in computer science and software engineering from Rose-Hulman in Indiana.

Photo Credits

  • photo_camera code image by charles taylor from Fotolia.com