Hi,
Is there an option to write the viewed page to a file on the server?
I have an asp.net page that produce a report according to a user
information. I want to add a button that when clicked the page will be saved
to a file on the server. Is that possible?
Yes, it is possible. The idea is to use a self-created HtmlTextWriter
(which is just a specialized TextWriter), and to pass this writer to all
the controls.
Something like that:
// In Page.Render
if ( Request.QueryString != null
&& Request.QueryString[ "static" ] == "1" )
{
this.RenderStatic( this.Request.ContentEncoding );
// Send a basic response
writer.WriteLine( "Static file saved" );
return;
}
// With:
public void RenderStatic( Encoding oEncoding )
{
HtmlTextWriter writer = null;
try
{
writer = new HtmlTextWriter( @"c:\temp\report.html" );
foreach ( Control child in this.Controls )
{
child.RenderControl( writer );
}
}
catch ( Exception ex )
{
throw ex;
}
finally
{
if ( writer != null )
{
writer.Close();
}
}
}
A few notes:
- The process is triggered by a URL like this:
http://www.domain.com/page.aspx?static=1
- If the Render method directly writes HTML as text to the
HtmlTextWriter, then you must also write this HTML as text to your
"static" writer.
- Once the controls have been rendered to a writer, they cannot be
rendered a second time. This is why I send back a basic response to the
client instead of attempting to render the normal page. If you don't
want to display this basic text in the browser, you can use AJAX
(XmlHttpRequest) to send the request to the URL above, and ignore the
answer.
Feel free to ask if something is not clear.
Greetings,
Laurent
--
Laurent Bugnion, GalaSoft
Software engineering:
http://www.galasoft-LB.ch
Private/Malaysia:
http://mypage.bluewin.ch/lbugnion
Support children in Calcutta:
http://www.calcutta-espoir.ch