Jasinski Technical Wiki

Navigation

Home Page
Index
All Pages

Quick Search
»
Advanced Search »

Contributor Links

Create a new Page
Administration
File Management
Login/Logout
Your Profile

Other Wiki Sections

Software

PoweredBy

PDF Generation via RDLC Report File

RSS
Modified on Mon, Jul 17, 2017, 9:19 AM by Administrator Categorized as ASP·NET Web Forms, SSRS (SQL Server Reporting Services)

.NET 2.0

public static void FromRdlcFile(string rdlcFileName, string dataSourceName, DataTable inputData, 
    HttpResponse response)
{
    //- Initialize Report Viewer Control ------------------------------------------------------
    ReportViewer rv = new ReportViewer();
    LocalReport r = rv.LocalReport;
    r.EnableExternalImages = true;
    r.ReportPath = "Reports/" + rdlcFileName;
    r.DataSources.Clear();
    ReportDataSource rds = new ReportDataSource(dataSourceName, inputData);
    r.DataSources.Add(rds);

    //- Render Report in PDF ------------------------------------------------------------------
    Warning[] warnings;
    string mimeType, encoding, fileNameExtension;
    string[] streams;

    byte[] bytes = r.Render("PDF", "", out mimeType, out encoding, out fileNameExtension, out 
                            streams, out warnings);

    int size = bytes.GetUpperBound(0) + 1;

    char[] c = new char[size];

    bytes.CopyTo(c, 0);

    //- Write PDF Contents to HTTP Response ---------------------------------------------------
    //response.Clear();
    response.ContentType = "Application/pdf";
    response.Write(c, 0, size);
    response.End();
}

.NET 4.0

Local Report Processing

private void RenderAsPdf(string rdlcFileName, string dataSourceName, DataTable 
    inputData, HttpResponse response)
{
    //- Initialize Report Viewer Control --------------------------------------------------
    ReportViewer rv = new ReportViewer();
    LocalReport r = rv.LocalReport;
    r.EnableExternalImages = true;
    r.ReportPath = "Reports/" + rdlcFileName + ".rdlc";
    r.DataSources.Clear();
    ReportDataSource rds = new ReportDataSource(dataSourceName, inputData);
    r.DataSources.Add(rds);

    //- Render Report in PDF --------------------------------------------------------------
    Warning[] warnings;
    string mimeType, encoding, fileNameExtension;
    string[] streams;

    byte[] bytes = r.Render("PDF", null, out mimeType, out encoding, out fileNameExtension,  
                            out streams, out warnings);

    int size = bytes.GetUpperBound(0) + 1;

    char[] c = new char[size];

    bytes.CopyTo(c, 0);

    //- Write PDF Contents to HTTP Response -----------------------------------------------
    response.Buffer = true;
    response.Clear();
    response.ContentType = mimeType;
    response.AddHeader("content-disposition", "attachment; filename=" + rdlcFileName + "." 
        + fileNameExtension);
    response.BinaryWrite(bytes);
    response.Flush();
    response.End();
}

Server Report Processing

Note: the following code can be a controller method.

public void GetMyReportPdf(int id)
{
    //- Inits -----------------------------------------------------------------------------
    var orderID = id;
    var reportName = "Order";
    var rv = new ReportViewer();
    var rpt = rv.ServerReport;

    //- Configure ReportViewer Control ----------------------------------------------------
    rv.ShowCredentialPrompts = false;
    rv.ProcessingMode = Microsoft.Reporting.WebForms.ProcessingMode.Remote;

    //- Configure ServerReport ------------------------------------------------------------
    var config = Acme.Configuration.AcmeConfiguration.Settings.Ssrs;

    if (!config.DefaultCredentials)
        rpt.ReportServerCredentials = new ReportServerCredentials(config);

    rpt.ReportServerUrl = config.ReportServerUrl; /* URL of SSRS web service*/
    rpt.ReportPath = config.RootPathWithSlashes + reportName;

    //- Set LoginName Parameter (?) -------------------------------------------------------
    var p = rpt.GetParameters()["OrderID"];

    if (p != null)
    {
        var p2 = new ReportParameter("OrderID", orderID.ToString());
        rpt.SetParameters(p2);
    }

    //- Render Report in PDF --------------------------------------------------------------
    Warning[] warnings;
    string mimeType, encoding, fileNameExtension;
    string[] streams;

    byte[] bytes = rpt.Render("PDF", null, out mimeType, out encoding, out fileNameExtension,
                            out streams, out warnings);

    int size = bytes.GetUpperBound(0) + 1;

    char[] c = new char[size];

    bytes.CopyTo(c, 0);

    //- Write PDF Contents to HTTP Response -----------------------------------------------
    var response = System.Web.HttpContext.Current.Response;
    response.Buffer = true;
    response.Clear();
    response.ContentType = mimeType;
    response.AddHeader("content-disposition", "attachment; filename=" + reportName + "."
        + fileNameExtension);
    response.BinaryWrite(bytes);
    response.Flush();
    response.End();

}

.NET Core

Since .NET Core doesn't support the Report Viewer control, an SSRS instance is required. The task then becomes properly negotiating security, as shown in this code sample. The NetworkCredentials need to have the Domain field set to the SSRS server name. (Thanks to Jim Ownby for this code sample!)

public static async Task<Stream> ClientExportAsync(string reportUrl, System.Net.NetworkCredential clientCredentials, ExportFormat format, ILogger logger)
{
    Stream _file = null;
    try
    {
        var _credCache = new CredentialCache();
        _credCache.Add(new Uri(reportUrl), "NTLM", clientCredentials);
        using (var _client = new HttpClient(new HttpClientHandler() { Credentials = _credCache, AllowAutoRedirect = true, AutomaticDecompression = DecompressionMethods.Deflate, PreAuthenticate=true }))
        {
            
            _file = await _client.GetStreamAsync(new Uri(reportUrl));
        }
    }
    catch (AggregateException aex)
    {
        aex.Handle(ex => { logger.LogError(ex.Message, ex.Data.Values); return true; });
    }

    return _file;

}

ScrewTurn Wiki version 3.0.1.400. Some of the icons created by FamFamFam. Except where noted, all contents Copyright © 1999-2018, Patrick Jasinski.