Run SSRS report from code to PDF file

For sure you've received the request to run a report in silent mode (just click on a button) and output it as a PDF file. The code to do this is quite straightforward, and there are also some places in AX that are also implementing this.

For ease of use and recall, here is the implementation I'm currently using:

(as always when doing copy pastes of code from here, if the code seems wrongs when you paste it in AX, just move it through a Word document, it will look much better)

void runReport(Common _record, ClassId _controllerClassId, SRSReportName _reportName, MethodName _parmRecIdMethodName, FilePath _filePath)
{
    DictClass                   dictController;
    SrsReportRunController      controller;
    SrsReportRunInterface       reportRun;
    SrsReportDataContract       dataContract;
    Object                      rdpContract;
    SRSPrintDestinationSettings printSettings;
    SRSReportExecutionInfo      executionInfo;
    DictTable                   dictTable;
    fieldId                     fieldId;
    int                         line;
   
    /* testing sequence
    select * from table;
    _record = table;
   
    _controllerClassId = classNum(YourController);
    _reportName = ssrsReportStr(YourReport, Design);
    _parmRecIdMethodName = methodStr(YourContract, parmRefRecId);
    _filePath = "C:\\YourReport.pdf";
    */
   
    dictController = new DictClass(_controllerClassId);
   
    controller = dictController.makeObject();
   
    if (controller != null && controller is SrsReportRunController)
    {
        controller.parmReportName(_reportName);
        controller.parmShowDialog(false);
       
        dataContract = controller.parmReportContract();
       
        if (dataContract != null)
        {
            rdpContract = dataContract.parmRdpContract();
           
            if (rdpContract != null)
            {
                dictController.callObject(_parmRecIdMethodName, rdpContract, _record.RecId);

                reportRun = new SrsReportRunImpl(dataContract.parmReportName());

                reportRun.parmReportContract(dataContract);

                if (reportRun.parmReportContract().parmReportExecutionInfo() == null)
                {
                    executionInfo = new SRSReportExecutionInfo();
                    reportRun.parmReportContract().parmReportExecutionInfo(executionInfo);
                }

                printSettings = dataContract.parmPrintSettings();
                printSettings.printMediumType(SRSPrintMediumType::File);
                printSettings.fileFormat(SRSReportFileFormat::PDF);
                printSettings.fileName(_filePath);
                printSettings.overwriteFile(true);

                line = Global::infologLine();
                reportRun.runReport();

                infolog.clear(line);
            }
        }
    }
}

No comments:

Post a Comment