Wednesday, 30 June 2010

Convert ASPX Pages to Word Document

We will discuss how to convert an ASPX page to word document and send it to the client. We will create an HttpModule which use the Application_BeginRequest event to check if a specific query string parameter exists to render the page into a word file.
First of all, Create a new class library project "WordConverter", Rename the class into "Converter" and let it implement IhttpModule interface which exists in System.Web namespace (you need to add it to your references before being able to add it to your namespace collection)

public class Converter : IHttpModule

After this stage, use the Init() to register for the Application_BeginRequest event.

public void Init(HttpApplication app)
{
app.BeginRequest += new EventHandler(app_BeginRequest);
}
void app_BeginRequest(object sender, EventArgs e)
{
}
// Dispose should be added
public void Dispose()
{
}

In the app_BeginRequest event you will need to write the below code

HttpContext.Current.Response.Clear();
// Check if ToWord exists in the query string parameters
if(HttpContext.Current.Request.QueryString["ToWord"]!=null)
{
// Set the buffer to true
HttpContext.Current.Response.Buffer = true;
// Create a new HttpWebRequest to the same url
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(HttpContext.Current.Request.Url.ToString().Split('?')[0]);
// Set the credentials to default credentials: used if you are under proxy server
webRequest.Credentials = CredentialCache.DefaultCredentials;
// Get the response as stream
Stream stream = webRequest.GetResponse().GetResponseStream();
// Set the content type of the response on msword
HttpContext.Current.Response.ContentType = "application/msword";
// Read the response as string
string pageHTML = new StreamReader(stream).ReadToEnd();
// Write it to the response
HttpContext.Current.Response.Write(pageHTML.ToString());
// Complete the Request
((HttpApplication)sender).CompleteRequest();
// End the response.
HttpContext.Current.Response.End();
}
P.S: Make sure you added the below namespaces
using System.Net;
using System.Web;
using System.IO;

After finishing implementing the code, compile your project. Now you need to add this module to your web application by adding it to your references and add the below code into the web.config to register the module.





You can find the Module solution attached to this blog post.

Hope this helps,

1 comment:

  1. I need to convert an ASPX to word and retain format. Can you assist?

    ReplyDelete