C# export list<T> in pdf via iTextSharp, include pdf header title and logo, footer with current page of total pages

Install-Package iTextSharp;
Install-Package System.Drawing.Common;

 

 

using iTextSharp.text;
using iTextSharp.text.pdf;
using System.Diagnostics;
using Document = iTextSharp.text.Document;
using Font = iTextSharp.text.Font;
using Image = iTextSharp.text.Image;

namespace ConsoleApp30
{
    internal class Program
    {
        static void Main(string[] args)
        {
            string pdfFile = $"Finance_{DateTime.Now.ToString("yyyyMMddHHmmssffff")}.pdf";
            var booksList = InitBooksList();
            ExportAnalysisPDFUtility.ExportToPDF(pdfFile, "Finance Report", $"{DateTime.Now.ToString("yyyyMMddHHmmssffff")}",
                $"Finance_{DateTime.Now.ToString("yyyyMMddHHmmssffff")}",
                $"Date_{DateTime.Now.ToString("yyyyMMddHHmmssffff")}",
                $"Exported Finance", "Fred", booksList);

            var proc = new Process()
            {
                StartInfo = new ProcessStartInfo()
                {
                    FileName= pdfFile,
                    UseShellExecute = true
                }
            };
            proc.Start();
        }

        private static List<Book> InitBooksList()
        {
            List<Book> booksList = new List<Book>();
            int idx = 0;
            for (int i = 0; i<1000; i++)
            {
                ++idx;
                booksList.Add(new Book()
                {
                    Id=idx,
                    Name=$"Name_{idx}",
                    Author=$"Author_{idx}",
                    Abstract=$"Abstract_{idx}",
                    Chapter=$"Chapter_{idx}",
                    Title=$"Title_{idx}",
                    Topic=$"Topic_{idx}",
                    Summary=$"Summary_{idx}",
                    ISBN=$"ISBN_{idx}_{Guid.NewGuid().ToString("N")}"
                });
            }
            return booksList;
        }
    }

    public static class ExportAnalysisPDFUtility
    {
        static Font normalFont = FontFactory.GetFont(FontFactory.HELVETICA, 15f, Font.NORMAL);
        public static void ExportToPDF<T>(string pdfFileName, string title = "Finance Report", string reportID = "Finance2025080416",
            string analysisName = "Finance20250804", string reportDate = "2025-08-04",
            string description = "Finance Comment", string analyzedBy = "SystemEngineer", List<T> dataList = null) where T : class
        {
            //color new rgba(64, 128, 128, 255)
            if (File.Exists(pdfFileName))
            {
                File.Delete(pdfFileName);
            }
            Document doc = new Document(PageSize.A4, 36f, 36f, 100f, 72f);

            PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(pdfFileName, FileMode.Create));
            string iconPath = @"../../../Images/logo.png";
            var pageEvents = new PdfHeaderFooter(title, iconPath);
            writer.PageEvent = pageEvents;
            doc.Open();

            //Report ID,Analysis Name,Date Of Report
            Paragraph spacer = new Paragraph(new Chunk(" ", new Font()));
            spacer.SpacingBefore = 5f;
            doc.Add(spacer);
            PdfPTable table = new PdfPTable(6);
            //table.SpacingBefore=50f;
            table.WidthPercentage = 100; // Use full page width
            table.DefaultCell.Border = Rectangle.NO_BORDER;
            table.SetWidths(new float[] { 0.05f, 0.25f, 0.08f, 0.3f, 0.08f, 0.26f });
            var tbkFont = FontFactory.GetFont(FontFactory.HELVETICA, 10f, Font.BOLD);

            var tbk = new Paragraph("ID:", tbkFont);
            tbk.SpacingBefore = 50;
            table.AddCell(tbk);
            tbk = new Paragraph(reportID, tbkFont);
            tbk.Alignment = Element.ALIGN_LEFT;
            table.AddCell(tbk);

            tbk = new Paragraph("Name:", tbkFont);
            tbk.SpacingBefore = 10;
            table.AddCell(tbk);
            tbk = new Paragraph(analysisName, tbkFont);
            tbk.SpacingBefore = 10;
            tbk.Alignment = Element.ALIGN_LEFT;
            table.AddCell(tbk);

            tbk = new Paragraph("Date:", tbkFont);
            tbk.SpacingBefore = 10;
            table.AddCell(tbk);
            tbk = new Paragraph(reportDate, tbkFont);
            tbk.Alignment = Element.ALIGN_LEFT;
            table.AddCell(tbk);
            doc.Add(table);

            //Description,Analyzed By
            table = new PdfPTable(4);
            table.SpacingBefore = 5f;
            table.WidthPercentage = 100; // Use full page width
            table.DefaultCell.Border = Rectangle.NO_BORDER;
            table.SetWidths(new float[] { 1.3f, 6.2f, 1.5f, 1.8f });
            tbk = new Paragraph("Description:", tbkFont);
            tbk.Alignment = Element.ALIGN_LEFT;
            table.AddCell(tbk);
            tbk = new Paragraph(description, tbkFont);
            tbk.Alignment = Element.ALIGN_LEFT;
            table.AddCell(tbk);

            tbk = new Paragraph("Analyzed By:", tbkFont);
            tbk.Alignment = Element.ALIGN_LEFT;
            table.AddCell(tbk);
            tbk = new Paragraph(analyzedBy, tbkFont);
            tbk.Alignment = Element.ALIGN_LEFT;
            table.AddCell(tbk);
            doc.Add(table);

            if (dataList != null && dataList.Any())
            {
                tbkFont = FontFactory.GetFont(FontFactory.HELVETICA, 10f, Font.BOLD);

                var props = typeof(T).GetProperties();
                int propsCount = props.Count();
                table=new PdfPTable(propsCount);
                table.SpacingBefore = 5f;
                table.WidthPercentage = 100;
                //columns
                foreach (var prop in props)
                {
                    tbk = new Paragraph(prop.Name, tbkFont);
                    table.AddCell(tbk);
                }
                doc.Add(table);

                //rows
                foreach (var item in dataList)
                {
                    table=new PdfPTable(propsCount);
                    table.WidthPercentage = 100;
                    foreach (var prop in props)
                    {
                        string cellValue = prop.GetValue(item)?.ToString()??"";
                        tbk = new Paragraph($"{cellValue}", tbkFont);
                        tbk.Alignment=Element.ALIGN_CENTER;
                        table.AddCell(tbk);
                    }
                    doc.Add(table);
                }
            }
            doc.Close();
        }
    }

    public class PdfHeaderFooter : PdfPageEventHelper
    {
        private PdfTemplate totalPages;
        private BaseFont baseFont;
        private string logoPath;
        private BaseColor baseColor = new BaseColor(64, 128, 128, 255);
        private string title;
        public PdfHeaderFooter(string titleValue,string logoPathValue)
        {
            title= titleValue;
            this.logoPath = logoPathValue;            
        }

        public override void OnOpenDocument(PdfWriter writer, Document document)
        {
            baseFont = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, false);
            totalPages = writer.DirectContent.CreateTemplate(50, 50);
        }

        public override void OnEndPage(PdfWriter writer, Document document)
        {
            var cb = writer.DirectContent;

            // --- HEADER ---
            float leftMargin = document.LeftMargin;
            float rightMargin = document.RightMargin;
            float pageWidth = document.PageSize.Width;
            float usableWidth = pageWidth - leftMargin - rightMargin;

            // Draw title
            ColumnText.ShowTextAligned(cb, Element.ALIGN_LEFT,
                new Phrase(title, new Font(Font.FontFamily.HELVETICA, 30, Font.BOLD, baseColor)),
                document.LeftMargin, document.Top + 30, 0);

            // Draw logo (right aligned)
            if (File.Exists(logoPath))
            {
                var logoImg = Image.GetInstance(logoPath);
                logoImg.ScaleToFit(70, 70);
                logoImg.SetAbsolutePosition(pageWidth - rightMargin - logoImg.ScaledWidth, document.Top + 10);
                cb.AddImage(logoImg);
            }

            // Line below header
            cb.SetLineWidth(10f);
            cb.SetColorStroke(baseColor);
            cb.MoveTo(leftMargin, document.Top);
            cb.LineTo(pageWidth - rightMargin, document.Top);
            cb.Stroke();

            // --- FOOTER ---
            float footerY = document.Bottom - 40;

            // Line above footer
            cb.SetLineWidth(10f);
            cb.SetColorStroke(baseColor);
            cb.MoveTo(leftMargin, footerY + 30);
            cb.LineTo(pageWidth - rightMargin, footerY + 30);
            cb.Stroke();


            // Page number: X/Y
            string text = "" + writer.PageNumber + "/";
            float len = baseFont.GetWidthPoint(text, 12);

            cb.BeginText();
            cb.SetFontAndSize(baseFont, 12);
            cb.SetTextMatrix(pageWidth / 2 - 30, footerY);
            cb.ShowText(text);
            cb.EndText();

            cb.AddTemplate(totalPages, pageWidth / 2 - 30 + len, footerY);
        }

        public override void OnCloseDocument(PdfWriter writer, Document document)
        {
            totalPages.BeginText();
            totalPages.SetFontAndSize(baseFont, 12);
            totalPages.SetTextMatrix(0, 0);
            totalPages.ShowText("" + (writer.PageNumber));
            totalPages.EndText();
        }
    }


    public class Book
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Abstract { get; set; }
        public string Author { get; set; }
        public string Chapter { get; set; }
        public string Title { get; set; }
        public string Topic { get; set; }
        public string Summary { get; set; }
        public string ISBN { get; set; }
    }
}

 

 

 

 

image

 

 

 

 

image

 

 

 

using iTextSharp.text;
using iTextSharp.text.pdf;
using System.Diagnostics;
using Document = iTextSharp.text.Document;
using Font = iTextSharp.text.Font;
using Image = iTextSharp.text.Image;

namespace ConsoleApp30
{
    internal class Program
    {
        static void Main(string[] args)
        {
            string pdfFile = $"Finance_{DateTime.Now.ToString("yyyyMMddHHmmssffff")}.pdf";
            var booksList = InitBooksList();
            ExportAnalysisPDFUtility.ExportToPDF(pdfFile, "Finance Report", $"{DateTime.Now.ToString("yyyyMMddHHmmssffff")}",
                $"Finance_{DateTime.Now.ToString("yyyyMMddHHmmssffff")}",
                $"Date_{DateTime.Now.ToString("yyyyMMddHHmmssffff")}",
                $"Exported Finance", "Fred", booksList);

            var proc = new Process()
            {
                StartInfo = new ProcessStartInfo()
                {
                    FileName= pdfFile,
                    UseShellExecute = true
                }
            };
            proc.Start();
        }

        private static List<Book> InitBooksList()
        {
            List<Book> booksList = new List<Book>();
            int idx = 0;
            for (int i = 0; i<100000; i++)
            {
                ++idx;
                booksList.Add(new Book()
                {
                    Id=idx,
                    Name=$"Name_{idx}",
                    Author=$"Author_{idx}",
                    Abstract=$"Abstract_{idx}",
                    Chapter=$"Chapter_{idx}",
                    Title=$"Title_{idx}",
                    Topic=$"Topic_{idx}",
                    Summary=$"Summary_{idx}",
                    ISBN=$"ISBN_{idx}"
                });
            }
            return booksList;
        }
    }

    public static class ExportAnalysisPDFUtility
    {
        static Font normalFont = FontFactory.GetFont(FontFactory.HELVETICA, 15f, Font.NORMAL);
        public static void ExportToPDF<T>(string pdfFileName, string title = "Finance Report", string reportID = "Finance2025080416",
            string analysisName = "Finance20250804", string reportDate = "2025-08-04",
            string description = "Finance Comment", string analyzedBy = "SystemEngineer", List<T> dataList = null) where T : class
        {
            //color new rgba(64, 128, 128, 255)
            if (File.Exists(pdfFileName))
            {
                File.Delete(pdfFileName);
            }
            Document doc = new Document(PageSize.A1, 36f, 36f, 100f, 72f);

            PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(pdfFileName, FileMode.Create));
            string iconPath = @"../../../Images/logo.png";
            var pageEvents = new PdfHeaderFooter(title, iconPath);
            writer.PageEvent = pageEvents;
            doc.Open();

            //Report ID,Analysis Name,Date Of Report
            Paragraph spacer = new Paragraph(new Chunk(" ", new Font()));
            spacer.SpacingBefore = 5f;
            doc.Add(spacer);
            PdfPTable table = new PdfPTable(6);
            //table.SpacingBefore=50f;
            table.WidthPercentage = 100; // Use full page width
            table.DefaultCell.Border = Rectangle.NO_BORDER;
            table.SetWidths(new float[] { 0.05f, 0.25f, 0.08f, 0.3f, 0.08f, 0.26f });
            var tbkFont = FontFactory.GetFont(FontFactory.HELVETICA, 20f, Font.BOLD);

            var tbk = new Paragraph("ID:", tbkFont);
            tbk.SpacingBefore = 50;
            table.AddCell(tbk);
            tbk = new Paragraph(reportID, tbkFont);
            tbk.Alignment = Element.ALIGN_LEFT;
            table.AddCell(tbk);

            tbk = new Paragraph("Name:", tbkFont);
            tbk.SpacingBefore = 10;
            table.AddCell(tbk);
            tbk = new Paragraph(analysisName, tbkFont);
            tbk.SpacingBefore = 10;
            tbk.Alignment = Element.ALIGN_LEFT;
            table.AddCell(tbk);

            tbk = new Paragraph("Date:", tbkFont);
            tbk.SpacingBefore = 10;
            table.AddCell(tbk);
            tbk = new Paragraph(reportDate, tbkFont);
            tbk.Alignment = Element.ALIGN_LEFT;
            table.AddCell(tbk);
            doc.Add(table);

            //Description,Analyzed By
            table = new PdfPTable(4);
            table.SpacingBefore = 5f;
            table.WidthPercentage = 100; // Use full page width
            table.DefaultCell.Border = Rectangle.NO_BORDER;
            table.SetWidths(new float[] { 1.3f, 6.2f, 1.5f, 1.8f });
            tbk = new Paragraph("Description:", tbkFont);
            tbk.Alignment = Element.ALIGN_LEFT;
            table.AddCell(tbk);
            tbk = new Paragraph(description, tbkFont);
            tbk.Alignment = Element.ALIGN_LEFT;
            table.AddCell(tbk);

            tbk = new Paragraph("Analyzed By:", tbkFont);
            tbk.Alignment = Element.ALIGN_LEFT;
            table.AddCell(tbk);
            tbk = new Paragraph(analyzedBy, tbkFont);
            tbk.Alignment = Element.ALIGN_LEFT;
            table.AddCell(tbk);
            doc.Add(table);

            if (dataList != null && dataList.Any())
            {
                tbkFont = FontFactory.GetFont(FontFactory.HELVETICA, 20f, Font.BOLD);

                var props = typeof(T).GetProperties();
                int propsCount = props.Count();
                table=new PdfPTable(propsCount);
                table.SpacingBefore = 5f;
                table.WidthPercentage = 100;
                //columns
                foreach (var prop in props)
                {
                    tbk = new Paragraph(prop.Name, tbkFont);
                    table.AddCell(tbk);
                }
                doc.Add(table);

                //rows
                foreach (var item in dataList)
                {
                    table=new PdfPTable(propsCount);
                    table.WidthPercentage = 100;
                    foreach (var prop in props)
                    {
                        string cellValue = prop.GetValue(item)?.ToString()??"";
                        tbk = new Paragraph($"{cellValue}", tbkFont);
                        tbk.Alignment=Element.ALIGN_CENTER;
                        table.AddCell(tbk);
                    }
                    doc.Add(table);
                }
            }
            doc.Close();
        }
    }

    public class PdfHeaderFooter : PdfPageEventHelper
    {
        private PdfTemplate totalPages;
        private BaseFont baseFont;
        private string logoPath;
        private BaseColor baseColor = new BaseColor(64, 128, 128, 255);
        private string title;
        public PdfHeaderFooter(string titleValue,string logoPathValue)
        {
            title= titleValue;
            this.logoPath = logoPathValue;            
        }

        public override void OnOpenDocument(PdfWriter writer, Document document)
        {
            baseFont = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, false);
            totalPages = writer.DirectContent.CreateTemplate(50, 50);
        }

        public override void OnEndPage(PdfWriter writer, Document document)
        {
            var cb = writer.DirectContent;

            // --- HEADER ---
            float leftMargin = document.LeftMargin;
            float rightMargin = document.RightMargin;
            float pageWidth = document.PageSize.Width;
            float usableWidth = pageWidth - leftMargin - rightMargin;

            // Draw title
            ColumnText.ShowTextAligned(cb, Element.ALIGN_LEFT,
                new Phrase(title, new Font(Font.FontFamily.HELVETICA, 30, Font.BOLD, baseColor)),
                document.LeftMargin, document.Top + 30, 0);

            // Draw logo (right aligned)
            if (File.Exists(logoPath))
            {
                var logoImg = Image.GetInstance(logoPath);
                logoImg.ScaleToFit(70, 70);
                logoImg.SetAbsolutePosition(pageWidth - rightMargin - logoImg.ScaledWidth, document.Top + 10);
                cb.AddImage(logoImg);
            }

            // Line below header
            cb.SetLineWidth(10f);
            cb.SetColorStroke(baseColor);
            cb.MoveTo(leftMargin, document.Top);
            cb.LineTo(pageWidth - rightMargin, document.Top);
            cb.Stroke();

            // --- FOOTER ---
            float footerY = document.Bottom - 40;

            // Line above footer
            cb.SetLineWidth(10f);
            cb.SetColorStroke(baseColor);
            cb.MoveTo(leftMargin, footerY + 30);
            cb.LineTo(pageWidth - rightMargin, footerY + 30);
            cb.Stroke();


            // Page number: X/Y
            string text = "" + writer.PageNumber + "/";
            float len = baseFont.GetWidthPoint(text, 12);

            cb.BeginText();
            cb.SetFontAndSize(baseFont, 12);
            cb.SetTextMatrix(pageWidth / 2 - 30, footerY);
            cb.ShowText(text);
            cb.EndText();

            cb.AddTemplate(totalPages, pageWidth / 2 - 30 + len, footerY);
        }

        public override void OnCloseDocument(PdfWriter writer, Document document)
        {
            totalPages.BeginText();
            totalPages.SetFontAndSize(baseFont, 12);
            totalPages.SetTextMatrix(0, 0);
            totalPages.ShowText("" + (writer.PageNumber));
            totalPages.EndText();
        }
    }


    public class Book
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Abstract { get; set; }
        public string Author { get; set; }
        public string Chapter { get; set; }
        public string Title { get; set; }
        public string Topic { get; set; }
        public string Summary { get; set; }
        public string ISBN { get; set; }
    }
}

 

 

 

 

image

 

 

 

 

 

 

 

 

 

 

 

 

 

image

 

posted @ 2025-09-05 21:14  FredGrit  阅读(7)  评论(0)    收藏  举报