Export and Print Report from Code

This sample project shows how to export and 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 exporting and printing. These methods take the input of all the necessary parameters to configure exporting and printing the report.

The special StiReportResponse class contains methods to export report in any format and print report to PDF and HTML. For example, implementing it for one report in order to compare them. Add two links for each print mode and three links for various export formats.

<div class="row">
    <div class="col-md-4">
        <h2>Print to PDF</h2>
        <p>@Html.ActionLink("Print", "PrintPdf")</p>
    </div>
    <div class="col-md-4">
        <h2>Print to HTML</h2>
        <p>@Html.ActionLink("Print", "PrintHtml")</p>
    </div>
</div>
<hr />
<div class="row">
    <div class="col-md-4">
        <h2>Export to PDF</h2>
        <p>@Html.ActionLink("Export", "ExportPdf")</p>
    </div>
    <div class="col-md-4">
        <h2>Export to HTML</h2>
        <p>@Html.ActionLink("Export", "ExportHtml")</p>
    </div>
    <div class="col-md-4">
        <h2>Export to Excel</h2>
        <p>@Html.ActionLink("Export", "ExportXls")</p>
    </div>
</div>


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("~/Content/Reports/TwoSimpleLists.mrt");
var report = new StiReport();
report.Load(reportPath);

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

return report;
}


Now we need to determine the actions that will be invoked when clicking on links. For printing we will use two action methods - PrintPdf and PrintHtml.

public ActionResult PrintPdf()
{
StiReport report = this.GetReport();
StiReportResponse.PrintAsPdf(report);
return View();
}

public ActionResult PrintHtml()
{
StiReport report = this.GetReport();
StiReportResponse.PrintAsHtml(report);
return View();
}


For printing, we will use three action methods - ExportPdf, ExportHtml, and ExportXls. These export formats are taken for example. Also, the methods of exporting a report (and printing) can take, as input, export settings and other necessary parameters.

public ActionResult ExportPdf()
{
StiReport report = this.GetReport();
StiReportResponse.ResponseAsPdf(report);
return View();
}

public ActionResult ExportHtml()
{
StiReport report = this.GetReport();
StiReportResponse.ResponseAsHtml(report);
return View();
}

public ActionResult ExportXls()
{
StiReport report = this.GetReport();
StiReportResponse.ResponseAsXls(report);
return View();
}


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

Export and Print Report from Code