Print Report from Code

This sample project shows how to print the report from code without using the report viewer. For this action, it is enough to use the special StiReportResponse class that implements the methods for report printing. These methods take the input of all the necessary parameters to configure export and print the report.

The special StiReportResponse class contains two modes for report printing: print as PDF and print as HTML. For example, implementing these modes for one report in order to compare them. Add two buttons for each print mode and add the click event handlers for these buttons.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Print_Report_from_Code.Default" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Print and Export Report from Code</title>
</head>
<body>
<form id="form1" runat="server">
<br /><br />
<asp:Button ID="ButtonPrintPDF" runat="server" Text="Print Report as PDF" OnClick="ButtonPrintPdf_Click" />
<br /><br />
<asp:Button ID="ButtonPrintHTML" runat="server" Text="Print Report as HTML" OnClick="ButtonPrintHtml_Click" />
<br /><br />
</form>
</body>
</html>


In the ButtonPrintPdf_Click event, it gets the report and calls the PrintAsPdf() static method of the StiReportResponse class. The report will be automatically generated, exported to PDF and sent for printing - the system print dialog will be displayed.

protected void ButtonPrintPdf_Click(object sender, EventArgs e)
{
StiReport report = this.GetReport();

StiReportResponse.PrintAsPdf(report);
}


In the ButtonPrintHtml_Click event, it gets the report and calls the PrintAsHtml() static method of the StiReportResponse class. The report will be automatically generated, exported to HTML and sent for printing - the system print dialog will be displayed.

protected void ButtonPrintHtml_Click(object sender, EventArgs e)
{
StiReport report = this.GetReport();

StiReportResponse.PrintAsHtml(report);
}


To get the report, the GetReport() method was used. This method loads the report template, loads the XML data file and registers this data for loaded report.

private StiReport GetReport()
{
string reportPath = Server.MapPath("Reports/SimpleList.mrt");
StiReport report = new StiReport();
report.Load(reportPath);

string dataPath = Server.MapPath("Data/Demo.xml");
DataSet data = new DataSet();
data.ReadXml(dataPath);
report.RegData(data);

return report;
}


In the screenshot below you can see the result of the sample code.

Print Report from Code