Search code examples
acumaticaacumatica-kb

Generate Report Programmatically


Let's say that I have created a report using the Acumatica Report Designer and it is linked to the relevant DAC.

I also have a custom screen with an Action. When the user executes this action, I want to generate the report so that it the user downloads it as pdf.

What is the approach to generate the report as PDF programmatically through the Acumatica API?


Solution

  • Please refer to code snippet below for an example showing how to generate report programmatically as PDF file and show SaveFileDialog to download/save generated PDF:

    public PXAction<IOITInboundTestWorkOrder> GenerateReportAndRedirectToFile;
    [PXButton]
    [PXUIField(DisplayName = "Generate Report and Download as PDF")]
    protected void generateReportAndSaveToDB()
    {
        Actions.PressSave();
        PXLongOperation.StartOperation(this, () =>
        {
            PX.SM.FileInfo file = null;
            using (Report report = PXReportTools.LoadReport("SO641012", null))
            {
                var orderNbr = ITWO.Current.OrderNbr;
                if (report == null) throw new Exception("Unable to access Acumatica report writter for specified report : " + "SO641012");
                Dictionary<string, string> prams = new Dictionary<string, string>();
                prams["ITWONbr"] = orderNbr;
                PXReportTools.InitReportParameters(report, prams, PXSettingProvider.Instance.Default);
                ReportNode repNode = ReportProcessor.ProcessReport(report);
                IRenderFilter renderFilter = ReportProcessor.GetRenderer(ReportProcessor.FilterPdf);
    
                using (StreamManager streamMgr = new StreamManager())
                {
                    renderFilter.Render(repNode, null, streamMgr);
                    string fileName = string.Format("Inbound Test Work Order #{0}.pdf", orderNbr);
                    file = new PX.SM.FileInfo(fileName, null, streamMgr.MainStream.GetBytes());
                }
            }
            if (file != null)
            {
                throw new PXRedirectToFileException(file, true);
            }
        });
    }