Let's Talk About .NET, Java, and Various File Formats!

Posts tagged ‘Response’

Rendering PDF Files to Browser using .NET Code

In the .NET applications, we some times need to render the PDF files to the browser using our code — C# or VB.NET etc. It’s not a big deal! You only need to use Response object to send the file to the browser. The only thing you need to take care of is the use of proper methods and attributes.

First of all, we need to save the PDF document to a MemoryStream object. For example, we have a MemoryStream object named outStream and we need to render it to the browser. The following code snippet can be used to render the file:

//create new MemoryStream object and add PDF file’s content to outStream.
MemoryStream outStream = new MemoryStream();

//specify the duration of time before a page cached on a browser expires
Response.Expires = 0;

//specify the property to buffer the output page
Response.Buffer = true;

//erase any buffered HTML output
Response.ClearContent();

//add a new HTML header and value to the Response sent to the client
Response.AddHeader(“content-disposition”, “inline; filename=” + “output.pdf”);

//specify the HTTP content type for Response as Pdf
Response.ContentType = “application/pdf”;

//write specified information of current HTTP output to Byte array
Response.BinaryWrite(outStream.ToArray());

//close the output stream
outStream.Close();

//end the processing of the current page to ensure that no other HTML content is sent
Response.End();

You need to use AddHeader method of Response object to add header and value to the response sent to the client. Content-Disposition response header field is used to convey additional information about how to process the response, and also to attach additional metadata, such as filename. The PDF will be viewed in the PDF viewer plugin installed for the browser. You can see a practical example of rendering the PDF file to browser in Aspose.Pdf Demo. In order to view the source code, please click on the Source tab.