VahidN / PdfReport.Core

PdfReport.Core is a code first reporting engine, which is built on top of the iTextSharp.LGPLv2.Core and EPPlus.Core libraries

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Null.Reference.Exception on generate PDF

ashkanRmk opened this issue · comments

Summary of the issue

I use PdfRpt.Core to generate PDF from data source, but it returns null reference exception.

I remove extra prefrences and want to just make a test PDF.

Environment

The in-use version:PdfRpt.Core Version="1.2.0"
Operating system: linux 64-bit ubuntu 16.0.4
IDE:  Visual Studio Code

Example code/Steps to reproduce:

string webRootPath = _hostingEnvironment.WebRootPath;


            var dataSourceList = new List<InvoicePdfViewModel>();
            dataSourceList.Add(new InvoicePdfViewModel { Status = "پرداخت کننده", Details = "sdfsddssdf"});
            dataSourceList.Add(new InvoicePdfViewModel { Status = "توضیح پرداخت", Details = "thhtrhrh" });
            dataSourceList.Add(new InvoicePdfViewModel { Status = "دریافت کننده(فروشنده)", Details = "name" });
            dataSourceList.Add(new InvoicePdfViewModel { Status = "کد خرید", Details = "payment.Code" });
            dataSourceList.Add(new InvoicePdfViewModel { Status = "تاریخ پرداخت", Details = "hjghjgh" });
            dataSourceList.Add(new InvoicePdfViewModel { Status = "شماره پرداخت", Details = "kukuuuuuuuuuuuuu" });
            dataSourceList.Add(new InvoicePdfViewModel
            {
                Status = "مبلغ",
                Details =
                $"{2545450:#,0} تومان".ToPersianNumbers()
            });


            var resultByte = new PdfReport()
               .DefaultFonts(fonts =>
               {
                      fonts.Path(webRootPath + "/IRANSansWeb.ttf", webRootPath + "/IRANSansWeb.ttf");
                //    fonts.Path("/home/smn/Desktop/PayPing/FileManager/src/PayPing.FileManager/wwwroot/IRANSansWeb.ttf", "/home/smn/Desktop/PayPing/FileManager/src/PayPing.FileManager/wwwroot/IRANSansWeb.ttf");
                   fonts.Size(9);
               })

               .MainTableDataSource(dataSource =>
               {

                   dataSource.StronglyTypedList(dataSourceList);
               })
                .GenerateAsByteArray();

Output:

Exception message:
Full Stack trace:

An unhandled exception has occurred while executing the request.
System.NullReferenceException: Object reference not set to an instance of an object.
   at PdfRpt.Core.PdfTable.RenderMainTable.setColumnsVisibility()
   at PdfRpt.Core.PdfTable.RenderMainTable.initData()
   at PdfRpt.Core.PdfTable.RenderMainTable.AddToDocument()
   at PdfRpt.PdfReportDocument.createPdf()
   at PdfRpt.PdfReportDocument.GeneratePdf()
   at PayPing.FileManager.Controllers.UploadController.GetRequestPdfReport() in /home/smn/Desktop/PayPing/FileManager/src/PayPing.FileManager/Controllers/UploadController.cs:line 1048
   at Microsoft.AspNetCore.Mvc.Internal.ActionMethodExecutor.TaskOfIActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, Object controller, Object[] arguments)
   at System.Threading.Tasks.ValueTask`1.get_Result()
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeActionMethodAsync()
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeNextActionFilterAsync()
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Rethrow(ActionExecutedContext context)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeInnerFilterAsync()
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync()
   at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync()
   at Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(HttpContext httpContext)
   at Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.StaticFiles.StaticFileMiddleware.Invoke(HttpContext context)
   at Swashbuckle.AspNetCore.SwaggerUI.SwaggerUIIndexMiddleware.Invoke(HttpContext httpContext)
   at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

I remove extra prefrences and want to just make a test PDF.

Nothing here is an extra property. Those are required properties.

First I use with all properties, but because it returns null references I remove them.
this code is what I wrote with all properties:



        private static PdfGrid createHeader(PagesHeaderBuilder header)
        {
            var table = new PdfGrid(numColumns: 1)
            {
                WidthPercentage = 100,
                RunDirection = PdfWriter.RUN_DIRECTION_RTL,
                SpacingAfter = 7
            };

            var basefont = BaseFont.CreateFont("/home/smn/Desktop/PayPing/FileManager/src/PayPing.FileManager/wwwroot/IRANSansWeb.ttf", BaseFont.IDENTITY_H,
                BaseFont.EMBEDDED);
            var gillsans = new Font(basefont, 30, Font.BOLD, new BaseColor(ColorTranslator.FromHtml("#009cde").ToArgb()));

            FontSelector selector = new FontSelector();
            selector.AddFont(gillsans);

            var title = selector.Process("PayPing");

            var pdfCell = new PdfPCell(title)
            {

                RunDirection = PdfWriter.RUN_DIRECTION_RTL,
                BorderWidthLeft = 0,
                BorderWidthRight = 0,
                BorderWidthTop = 0,
                BorderWidthBottom = 1,
                PaddingBottom = 10,
                BorderColorBottom = new BaseColor(System.Drawing.Color.LightGray.ToArgb()),
                HorizontalAlignment = Element.ALIGN_CENTER
            };

            table.AddCell(pdfCell);
            return table;
        }

        [HttpGet]
        public async Task<IActionResult> GetRequestPdfReport()
        {
            dataSourceList.Add(new InvoicePdfViewModel { Status = "پرداخت کننده", Details = "sdfsddssdf"});
            dataSourceList.Add(new InvoicePdfViewModel { Status = "توضیح پرداخت", Details = "thhtrhrh" });
            dataSourceList.Add(new InvoicePdfViewModel { Status = "دریافت کننده(فروشنده)", Details = "name" });
            dataSourceList.Add(new InvoicePdfViewModel { Status = "کد خرید", Details = "payment.Code" });
            dataSourceList.Add(new InvoicePdfViewModel { Status = "تاریخ پرداخت", Details = "hjghjgh" });
            dataSourceList.Add(new InvoicePdfViewModel { Status = "شماره پرداخت", Details = "kukuuuuuuuuuuuuu" });
            dataSourceList.Add(new InvoicePdfViewModel
            {
                Status = "مبلغ",
                Details =
                $"{2545450:#,0} تومان".ToPersianNumbers()
            });

var resultByte = new PdfReport()
            .DocumentPreferences(doc =>
            {
                doc.RunDirection(PdfRunDirection.RightToLeft);
                doc.Orientation(PageOrientation.Portrait);
                doc.PageSize(PdfPageSize.A5);
                doc.DocumentMetadata(new DocumentMetadata
                {
                    Author = "PayPing",
                    Application = "PayPing",
                    Keywords = "پی پینگ",
                    Subject = "پی پینگ",
                    Title = "فاکتور فروش"
                });
                doc.Compression(new CompressionSettings
                {
                    EnableCompression = true,
                    EnableFullCompression = true
                });
                doc.PrintingPreferences(new PrintingPreferences
                {
                    ShowPrintDialogAutomatically = false
                });
            })
               .DefaultFonts(fonts =>
               {
                      fonts.Path(webRootPath + "/IRANSansWeb.ttf", webRootPath + "/IRANSansWeb.ttf");
                //    fonts.Path("/home/smn/Desktop/PayPing/FileManager/src/PayPing.FileManager/wwwroot/IRANSansWeb.ttf", "/home/smn/Desktop/PayPing/FileManager/src/PayPing.FileManager/wwwroot/IRANSansWeb.ttf");
                   fonts.Size(9);
               })
               .PagesFooter(footer =>
               {
                   footer.DefaultFooter("تاريخ: " + PersianDate.ToPersianDateTime(DateTime.Now, "/", true).FixWeakCharacters(),
                                    PdfRunDirection.RightToLeft);
               })
               .PagesHeader(header =>
               {
                   header.CacheHeader(cache: true);
                   header.InlineHeader(inlineHeader =>
                   {
                       inlineHeader.AddPageHeader(data => createHeader(header));
                   });

               })
               .MainTableTemplate(template =>
               {
                   template.CustomTemplate(new TransparentTemplate());
               })
               .MainTablePreferences(table =>
               {
                   table.ColumnsWidthsType(TableColumnWidthType.Relative);
                   table.SpacingAfter(0);
               })
               .MainTableDataSource(dataSource =>
               {

                   dataSource.StronglyTypedList(dataSourceList);
               })

               .MainTableColumns(columns =>
               {
                   columns.AddColumn(column =>
                   {
                       column.PropertyName("rowNo");
                       column.IsRowNumber(true);
                       column.CellsHorizontalAlignment(HorizontalAlignment.Center);
                       column.IsVisible(true);
                       column.Order(0);
                       column.Width(1);
                       column.FixedHeight(30);
                       column.HeaderCell("#");
                       column.AddHeadingCell("فاکتور پرداخت", mergeHeaderCell: true);
                   });

                   columns.AddColumn(column =>
                   {
                       column.PropertyName<InvoicePdfViewModel>(x => x.Status);
                       column.CellsHorizontalAlignment(HorizontalAlignment.Left);
                       column.IsVisible(true);
                       column.Order(1);
                       column.Width(6);
                       column.MinimumHeight(30);
                       column.HeaderCell("اطلاعات");
                       column.AddHeadingCell(string.Empty, mergeHeaderCell: true);
                   });

                   columns.AddColumn(column =>
                   {
                       column.PropertyName<InvoicePdfViewModel>(x => x.Details);
                       column.CellsHorizontalAlignment(HorizontalAlignment.Center);
                       column.IsVisible(true);
                       column.Order(2);
                       column.Width(5);
                       column.HeaderCell("جزئیات");
                       column.AddHeadingCell(string.Empty, mergeHeaderCell: true);
                   });
               })
               .MainTableEvents(events =>
               {
                   events.DataSourceIsEmpty(message: "رکوردی یافت نشد.");

                   events.MainTableAdded(args =>
                   {
                       var infoTable = new PdfGrid(numColumns: 1)
                       {
                           WidthPercentage = 100
                       };

                       infoTable.AddSimpleRow(
                            (cellData, properties) =>
                            {
                                cellData.Value = $"این فاکتور به منزله پرداخت شما به اشکان است.";
                                properties.PdfFont = events.PdfFont;
                                properties.FontColor = BaseColor.Gray;
                                properties.RunDirection = PdfRunDirection.RightToLeft;
                            });
                       infoTable.AddSimpleRow(
                            (cellData, properties) =>
                            {
                                cellData.Value = "هر گونه سوال در مورد خدمات یا محصول را با فروشنده در میان گذارید";
                                properties.PdfFont = events.PdfFont;
                                properties.FontColor = BaseColor.Gray;
                                properties.RunDirection = PdfRunDirection.RightToLeft;
                            });
                       args.PdfDoc.Add(infoTable.AddBorderToTable(borderColor: BaseColor.LightGray, spacingBefore: 1f));

                   });
               })
               .Export(export =>
               {
                    export.ToExcel();
               })
                .GenerateAsByteArray();
}

this code was fine in MVC...
I want to use it with PdfRpt.Core in dotnet core..
what should I do?

Fixed via #938a957
Try v1.2.1.

Thanks a lot.

commented

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related problems.