ActiveReports 12
Custom HTML Outputter
ActiveReports 12 > ActiveReports User Guide > Samples and Walkthroughs > Walkthroughs > Section Report Walkthroughs > Export > Custom HTML Outputter

You can create a custom HTML outputter for your ActiveReports ASP.NET Web Application.

Note: You cannot create a custom HTML outputter for a page report because the html rendering extension does not support the custom output formatter.

This walkthrough is split up into the following activities:

To create a public class for the HTML outputter

  1. In the Solution Explorer window, right-click on your project name and select Add, then New Item.
  2. In the Add New Item dialog that appears, select Class.
  3. Change the name of the class to MyCustomHtmlOutputter and click the Add button.
  4. This opens the code view of the class file where you can add the code needed to create the public class.
  5. For C# code, add the IOutputHtml interface to MyCustomHtmlOutputter class.
    C# code.
    Copy Code
    public class MyCustomHtmlOutputter: IOutputHtml
    

The following example shows what the complete code for the method looks like.

To write the code in Visual Basic.NET

Visual Basic.NET code. Paste JUST ABOVE the class.
Copy Code
Imports System 
Imports System.IO 
Imports System.Web 
Imports System.Text
Imports GrapeCity.ActiveReports 
Imports GrapeCity.ActiveReports.Export.Html
Visual Basic.NET code. Paste INSIDE the class.
Copy Code
Implements IOutputHtml
'The http context of the request.
Private context As System.Web.HttpContext = Nothing
'The directory in which to save filename--this ensures that the filename
'is unique.
Private dirToSave As System.IO.DirectoryInfo = Nothing
Public mainPage As String = ""
Public Sub New(ByVal context As System.Web.HttpContext)
If context Is Nothing Then
Throw New ArgumentNullException("context")
End If
Me.context = context
Dim dirName As String = context.Server.MapPath("ReportOutput")
Me.dirToSave = New DirectoryInfo(dirName)
End Sub
#Region "Implementation of IOutputHtml"
Public Function OutputHtmlData(ByVal info As HtmlOutputInfoArgs) As String Implements IOutputHtml.OutputHtmlData
Dim temp As String = ""
Select Case info.OutputKind
Case HtmlOutputKind.BookmarksHtml
Case HtmlOutputKind.FramesetHtml
temp = Me.GenUniqueFileNameWithExtension(".html")
Dim fs As New FileStream(temp, FileMode.CreateNew)
Me.WriteStreamToStream(info.OutputStream, fs)
fs.Close()
Return temp
Case HtmlOutputKind.HtmlPage
'Store the name of the main page so we can redirect the
'browser to it
Me.mainPage = Me.GenUniqueFileNameWithExtension(".html")
Dim fs As New FileStream(Me.mainPage, FileMode.CreateNew)
Me.WriteStreamToStream(info.OutputStream, fs)
fs.Close()
Return Me.mainPage
Case HtmlOutputKind.ImageJpg
'Create a file with a .jpg extension:
temp = Me.GenUniqueFileNameWithExtension(".jpg")
Dim fs As New FileStream(temp, FileMode.CreateNew)
fs = File.Create(temp)
Me.WriteStreamToStream(info.OutputStream, fs)
fs.Close()
Return temp
Case HtmlOutputKind.ImagePng
'Create a file with a .png extension:
temp = Me.GenUniqueFileNameWithExtension(".png")
Dim fs As New FileStream(temp, FileMode.CreateNew)
Me.WriteStreamToStream(info.OutputStream, fs)
fs.Close()
Return temp
Case Else
'Default to html:
temp = Me.GenUniqueFileNameWithExtension(".html")
Dim fs As New FileStream(temp, FileMode.CreateNew)
Me.WriteStreamToStream(info.OutputStream, fs)
fs.Close()
Return temp
End Select
End Function Public Sub Finish() Implements IOutputHtml.Finish
End Sub
#End Region
Private Sub WriteStreamToStream(ByVal sourceStream As Stream, ByVal targetStream As Stream)
'Find the size of the source stream:
Dim size As Integer = CType(sourceStream.Length, Integer)
'Create a buffer that same size
Dim buffer(size) As Byte
'Move the source stream to the beginning
sourceStream.Seek(0, SeekOrigin.Begin)
'Copy the sourceStream into our buffer
sourceStream.Read(buffer, 0, size)
'Write out the buffer to the target stream
targetStream.Write(buffer, 0, size)
End Sub
Private Function GenUniqueFileNameWithExtension(ByVal extensionWithDot As String) As String
Dim r As New System.Random()
Dim unique As Boolean = False
Dim filePath As String = ""
Dim iRandom As Integer = 0
'Generate a random name until it's unique
While Not unique
iRandom = r.Next()
'Build the full filename
Dim sb = New StringBuilder()
sb.Append(Me.dirToSave.FullName)
sb.Append(Path.DirectorySeparatorChar)
sb.Append(iRandom.ToString())
sb.Append(extensionWithDot)
filePath = sb.ToString()
If File.Exists(filePath) = False Then
unique = True
Else
unique = False
End If
End While
Return filePath
End Function
End Class

To write the code in C#

C# code. Paste JUST ABOVE the class.
Copy Code
using System; 
using System.IO; 
using System.Web; 
using System.Text; 
using GrapeCity.ActiveReports; 
using GrapeCity.ActiveReports.Export.Html;
C# code. Paste INSIDE the class.
Copy Code
   //The http context of the request
   private System.Web.HttpContext context = null;
    //The directory in which to save filename--this ensures that the filename  
    //is unique.
   private System.IO.DirectoryInfo dirToSave = null;
   public string mainPage = "";
   public MyCustomHtmlOutputter(System.Web.HttpContext context)
   {
      if(context == null)
      {         
        throw new ArgumentNullException("context");
          }     
        this.context = context;
        string dirName = context.Server.MapPath("ReportOutput");
        this.dirToSave = new DirectoryInfo(dirName);      
    }
    
#region Implementation of IOutputHtml
public string OutputHtmlData(HtmlOutputInfoArgs info)
{
   string temp = "";
   switch(info.OutputKind)
   {
      case HtmlOutputKind.BookmarksHtml:
      case HtmlOutputKind.FramesetHtml:
      {
        temp = this.GenUniqueFileNameWithExtension(".html");
        FileStream fs = File.Create(temp);
        this.WriteStreamToStream(info.OutputStream, fs);
        fs.Close();
        return temp;
      }
                
      case HtmlOutputKind.HtmlPage:
      {
         //Store the name of the main page so we can
         //redirect the browser to it
        this.mainPage = this.GenUniqueFileNameWithExtension(".html");
        FileStream fs = File.Create(this.mainPage);
        this.WriteStreamToStream(info.OutputStream, fs);
        fs.Close();
        return this.mainPage;
      }
                
      case HtmlOutputKind.ImageJpg:
      {
         // Create a file with a .jpg extension:
         temp = this.GenUniqueFileNameWithExtension(".jpg");
        FileStream fs = File.Create(temp);
        this.WriteStreamToStream(info.OutputStream, fs);
        fs.Close();
        return temp;
      }
                
      case HtmlOutputKind.ImagePng:
      {
        //Create a file with a .png extension:
        temp = this.GenUniqueFileNameWithExtension(".png");
        FileStream fs = File.Create(temp);
        this.WriteStreamToStream(info.OutputStream, fs);
        fs.Close();
        return temp;
      }
                
      default:
      {
        //Default to html:
        temp = this.GenUniqueFileNameWithExtension(".html");
        FileStream fs = File.Create(temp);
        this.WriteStreamToStream(info.OutputStream, fs);
        fs.Close();
        return temp;
      }
   }
}
    
public void Finish()
{
}
#endregion
    
private void WriteStreamToStream(Stream sourceStream, Stream targetStream)
{
   //Find the size of the source stream
   int size = (int)sourceStream.Length;
       
   //Create a buffer that same size
   byte[] buffer = new byte[size];
       
   //Move the source stream to the beginning
   sourceStream.Seek(0, SeekOrigin.Begin);
       
   //Copy the sourceStream into our buffer
   sourceStream.Read(buffer, 0, size);
       
   //Write out the buffer to the target stream
   targetStream.Write(buffer, 0, size);
}
     
private string GenUniqueFileNameWithExtension(string extensionWithDot)
{
    System.Random r = new Random();
    bool unique = false;
    string filePath = "";
    int iRandom = 0;
    //Generate a random name until it's unique
    while(!unique)
    {
       iRandom = r.Next();
       //Buld the full filename
       System.Text.StringBuilder sb = new System.Text.StringBuilder();
       sb.Append(this.dirToSave.FullName);
       sb.Append(Path.DirectorySeparatorChar);
       sb.Append(iRandom.ToString());
       sb.Append(extensionWithDot);
       filePath = sb.ToString();
       unique = !File.Exists(filePath);
     }
     return filePath;
  }

To add code to the Web Form to export to HTML

  1. Add an Section Report (Code-based) to the project, and name it rptCustHTML.
  2. Now add a Web form and double-click on the design view of the ASPX. This creates an event-handling method for the Web Form's Page Load event.
  3. Add the following code to the Page Load event.

The following example shows what the code for the method looks like.

To write the code in Visual Basic.NET

Visual Basic.NET code. Paste INSIDE the Page Load event.
Copy Code
Dim rpt As New rptCustHTML()
Try
rpt.Run(False)
Catch eRunReport As Exception
'If the report fails to run, report the error to the user
Response.Clear()
Response.Write("<h1>Error running report:</h1>")
Response.Write(eRunReport.ToString())
Return
End Try
'Buffer this page's output until the report output is ready.
Response.Buffer = True
'Clear any part of this page that might have already been buffered for output.
Response.ClearContent()
'Clear any headers that might have already been buffered (such as the content type 
'for an HTML page)
Response.ClearHeaders()
'Tell the browser and the "network" that the resulting data of this page should be 
'cached since this could be a dynamic report that changes upon each request.
Response.Cache.SetCacheability(HttpCacheability.NoCache)
'Tell the browser this is an Html document so it will use an appropriate viewer.
Response.ContentType = "text/HTML"
'Create the Html export object
Dim HtmlExport1 As New GrapeCity.ActiveReports.Export.Html.Section.HtmlExport()
Dim outputter As New MyCustomHtmlOutputter(Me.Context)
HtmlExport1.Export(rpt.Document, outputter, "")
Response.Redirect("ReportOutput" + "/" + System.IO.Path.GetFileName(outputter.mainPage))

To write the code in C#

C# code. Paste INSIDE the Page Load event.
Copy Code
   rptCustHTML rpt = new rptCustHTML();
   try
   {
      rpt.Run(false);
   }
   catch (Exception eRunReport)
   {
      //If the report fails to run, report the error to the user
      Response.Clear();
      Response.Write("<h1>Error running report:</h1>");
      Response.Write(eRunReport.ToString());
      return;
   }
   //Buffer this page's output until the report output is ready.
   Response.Buffer = true;
        
   //Clear any part of this page that might have already been buffered for output.
   Response.ClearContent();

   //Clear any headers that might have already been buffered (such as the content 
   //type for an HTML page)
   Response.ClearHeaders();
    
   //Tell the browser and the "network" that the resulting data of this page should 
   //be cached since this could be a dynamic report that changes upon each request.
   Response.Cache.SetCacheability(HttpCacheability.NoCache);
    
   //Tell the browser this is an Html document so it will use an appropriate viewer.
   Response.ContentType = "text/html";
    
   //Create the HTML export object
   GrapeCity.ActiveReports.Export.Html.Section.HtmlExport htmlExport1 = new GrapeCity.ActiveReports.Export.Html.Section.HtmlExport();
   
       
   //Export the report to HTML in this session's webcache
   MyCustomHtmlOutputter outputter = new MyCustomHtmlOutputter(this.Context);
   htmlExport1.Export(rpt.Document, outputter, "");
   Response.Redirect("ReportOutput" + "/" + System.IO.Path.GetFileName(outputter.mainPage));

To add a folder to the project for report output

  1. In the Solution Explorer, right-click your solution and select Add, then New Folder.
  2. Name the folder ReportOutput.
  3. Ensure that you have write permissions for this folder.
  4. To view the results in your Web browser, run the project.
See Also