Search code examples
.netasp.net-core.net-coreitextitext7

Convert datatable to pdf with custom header and footer in .net core 6 mvc using itextsharp 5.5.13.3?


I want to generate pdf with data from Datatable and set custom header and footer.

private void ProcessEMICalendarDocument(DocumentGenerationRequestModel item, List<MemoryStream> templateStreams, string userCode)
{
    var dataTable = dao.GetDataforEMICalendar(item.LoanAccountNo, connectionString);

    if (dataTable != null && dataTable.Rows.Count > 0)
    {
       // Create a new MemoryStream for each document
          using (MemoryStream memoryStream = new MemoryStream())
          {
              using (Document document = new Document())
              {
                PdfWriter writer = PdfWriter.GetInstance(document, memoryStream);

                // Create the event handler
                HeaderFooter eventhelper = new HeaderFooter();
                        writer.PageEvent = eventHelper;

               document.Open();
               PdfPTable table = CreatePdfPTable(dataTable, 10);

               if (table.Rows.Count > 0)
               {
                  // Add the table
                  document.Add(table);//here my code is breaking and stoping visual studio
                  document.Close();

                  // Create a new MemoryStream using the existing one's data
                  MemoryStream clonedMemoryStream = new MemoryStream(memoryStream.ToArray());
                  // Reset the position of the cloned MemoryStream to the beginning
                  clonedMemoryStream.Position = 0;
                  // Add the cloned MemoryStream to templateStreams
                            templateStreams.Add(clonedMemoryStream);
                        }
                        else
                        {
                            Console.WriteLine("The PdfPTable has no rows.");
                        }
                    }
                }
            }
            else
            {
                Console.WriteLine("The DataTable is null or empty.");
            }
        }

Event Handler class

public class HeaderFooter : PdfPageEventHelper
    {
        private bool addHeader = true;
        private bool addFooter = true;

        public override void OnStartPage(PdfWriter writer, Document document)
        {
            if (addHeader)
            {
                PdfPTable header = new PdfPTable(1);
                header.TotalWidth = document.PageSize.Width;
                header.DefaultCell.Border = 0;
                header.AddCell(new Phrase("Your Header Content Here", new Font(Font.FontFamily.HELVETICA, 12, Font.NORMAL)));
                document.Add(header);
            }
        }

        public override void OnEndPage(PdfWriter writer, Document document)
        {
            if (addFooter)
            {
                PdfPTable footer = new PdfPTable(1);
                footer.TotalWidth = document.PageSize.Width;
                footer.DefaultCell.Border = 0;
                footer.AddCell(new Phrase("Your Footer Content Here", new Font(Font.FontFamily.HELVETICA, 12, Font.NORMAL)));
                document.Add(footer);
            }
        }

    }

Above code is working when I comment below event handler code.

HeaderFooter eventhelper = new HeaderFooter();
writer.PageEvent = eventHelper;

It will generate pdf with data in datatable. But When I uncomment event handler code to add header & footer and run the application. debugger hangs for few seconds and then stops visual studio on below line

 document.Add(table);//here debugger gets hanged  and stops visual studio 

The only thing I was trying to get is to set header & footer in pdf. In Header I want to add Company logo and in footer I want add Company Address.

Any help will be appreciated...

Thanks In Advance.


Solution

  • You are facing this issue you are facing hang with visual studio it might be because how you are adding content to the pdf document. OnStartPage and OnEndPage these methods are being called recursively because the document.Add(header) and document.Add(footer) inside them trigger additional page events, which in turn call OnStartPage and OnEndPage again. This recursive call stack is likely causing the overflow or hang in Visual Studio. To avoid Infinite Recursion you could use ColumnText or direct content addition methods (PdfContentByte) instead of adding directly to the Document.

    You could try below code:

    public class HeaderFooter : PdfPageEventHelper
    {
        private Image logo;
    
        public HeaderFooter(string logoPath)
        {
            try
            {
                logo = Image.GetInstance(logoPath);
                logo.ScalePercent(50);
                logo.Alignment = Image.ALIGN_CENTER;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: " + ex.Message);
            }
        }
    
        public override void OnEndPage(PdfWriter writer, Document document)
        {
            Rectangle pageSize = document.PageSize;
    
            if (logo != null)
            {
                logo.SetAbsolutePosition(pageSize.GetLeft(40), pageSize.GetTop(40) - logo.ScaledHeight);
                writer.DirectContent.AddImage(logo);
            }
    
            ColumnText.ShowTextAligned(writer.DirectContent, Element.ALIGN_CENTER, 
                new Phrase("Address", new Font(Font.FontFamily.HELVETICA, 10)), 
                pageSize.Width / 2, pageSize.GetBottom(30), 0);
        }
    }
    

    code to add header footer while creating pdf. make sure to add logo path:

    HeaderFooter eventHelper = new HeaderFooter("path/logo.jpg");
    writer.PageEvent = eventHelper;