C# export string,image, list<T> as table, Header with Title and logo, Footer with currentPage/TotalPagesCount via iTextSharp.LGPLv2.Core;

install-package iTextSharp.LGPLv2.Core;

 

 

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

namespace ConsoleApp18
{
    internal class Program
    {
        static void Main(string[] args)
        {
            var generator = new PdfGeneratorWithHeaderFooter();
            string outputPath = $"SmoothTech_Report.pdf_{DateTime.Now.ToString("yyyyMMddHHmmssffff")}";
            string logoPath = @"C:\C\ConsoleApp18\ConsoleApp18\Images\1.jpg";
            //string logoPath = @"../../../Images/1.jpg";
            string baseDirectory = AppContext.BaseDirectory;
            string relativePath = Path.GetRelativePath(baseDirectory, logoPath);
            Thread pdfThread = new Thread(() =>
            {
                generator.CreatePdfWithHeaderFooter(outputPath, logoPath);
            });

            pdfThread.Start();
            pdfThread.Join();

            Thread.Sleep(1000);
            OpenPdfFile(outputPath);
        }

        static void OpenPdfFile(string filePath)
        {
            if (File.Exists(filePath))
            {
                try
                {
                    var proc = new Process()
                    {
                        StartInfo = new ProcessStartInfo()
                        {
                            FileName = filePath,
                            UseShellExecute = true // This is important for opening files with default application
                        }
                    };
                    proc.Start();
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Error opening PDF: {ex.Message}");
                }
            }
            else
            {
                Console.WriteLine("PDF file not found!");
            }
        }
    }

    public class PdfGeneratorWithHeaderFooter
    {
        public void CreatePdfWithHeaderFooter(string outputPath, string logoPath)
        {
            if (!File.Exists(logoPath))
            {
                Console.WriteLine($"{logoPath} does not exist!");
            }

            BaseColor blueColor = new BaseColor(0, 0, 255);
            Font blueFont30 = new Font(Font.HELVETICA, 30, Font.NORMAL, blueColor);
            // Create document
            using (Document doc = new Document(PageSize.A3, 50, 50, 80, 50))// Extra top margin for header
            {
                try
                {
                    // Create PDF writer
                    PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(outputPath, FileMode.Create));

                    // Assign header/footer event handler
                    writer.PageEvent = new HeaderFooterEventHandler(logoPath);

                    doc.Open();

                    // Add some sample content
                    for (int i = 0; i < 5; i++)
                    {
                        //document.Add(new Paragraph($"Sample content line {i + 1}"));
                        doc.Add(new Paragraph($"{i+1}_{Guid.NewGuid().ToString("N")}", blueFont30));
                    }

                    AddImagesInPDF(doc);
                    AddListDataAsTableInPDF(doc);
                    doc.Close();
                }

                catch (Exception ex)
                {
                    Console.WriteLine($"Error creating PDF: {ex.Message}");
                }

                finally
                {
                }
            }
        }

        private void AddListDataAsTableInPDF(Document doc)
        {
            List<Book> booksList = new List<Book>();
            for (int i = 0; i<100; i++)
            {
                booksList.Add(new Book()
                {
                    Id=i+1,
                    Name=$"Name_{i+1}",
                    Author=$"Author_{i+1}",
                    Title=$"Title_{i+1}",
                    ISBN=$"ISBN_{i+1}_{Guid.NewGuid().ToString("N")}",
                    Summary=$"Summary_{i+1}",
                    Topic=$"Topic_{i+1}"
                });
            }

            doc.Add(new Paragraph("\n")); // spacing

            // Define table with 7 columns
            Table table = new Table(7);
            //table.SetWidths(UnitValue.CreatePercentValue(100));

            // Add headers
            string[] headers = { "Id", "Name", "Author", "ISBN", "Title", "Summary", "Topic" };
            foreach (var header in headers)
            {
                table.AddCell(new Cell(header));
            }

            table.SetWidths(new int[] { 1, 2, 2, 10, 2, 3, 2 });

            // Add book data
            foreach (var book in booksList)
            {
                table.AddCell(book.Id.ToString());
                table.AddCell(book.Name ?? "");
                table.AddCell(book.Author ?? "");
                table.AddCell(book.ISBN ?? "");
                table.AddCell(book.Title ?? "");
                table.AddCell(book.Summary ?? "");
                table.AddCell(book.Topic ?? "");
            }

            // Add table to document
            doc.Add(table);
        }

        private static void AddImagesInPDF(Document doc)
        {
            string dir = @"C:\C\ConsoleApp17\ConsoleApp17\Images\";
            if (Directory.Exists(dir))
            {
                var imgs = Directory.GetFiles(dir);
                if (imgs!=null && imgs.Any())
                {
                    foreach (var im in imgs)
                    {
                        Image img = Image.GetInstance(im);
                        float pageWidth = doc.PageSize.Width - doc.LeftMargin - doc.RightMargin;
                        float pageHeight = doc.PageSize.Height - doc.TopMargin - doc.BottomMargin;
                        float targetHeight = pageHeight / 2;

                        // Scale image to fit full page width while maintaining aspect ratio
                        img.ScaleToFit(pageWidth, targetHeight);
                        img.Alignment = Element.ALIGN_CENTER;
                        img.SpacingBefore = 10f;
                        img.SpacingAfter = 10f;
                        doc.Add(img);
                    }
                }
            }
        }
    }

    // Header and Footer event handler
    public class HeaderFooterEventHandler : PdfPageEventHelper
    {
        private readonly string logoPath;
        private PdfTemplate totalPages;
        private BaseFont baseFont;
        private BaseColor baseColor = new BaseColor(64, 128, 128, 255);
        public HeaderFooterEventHandler(string logoPath)
        {
            this.logoPath = logoPath;
        }

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

        public override void OnStartPage(PdfWriter writer, Document document)
        {
            //AddHeader(writer, document);
        }

        public override void OnEndPage(PdfWriter writer, Document document)
        {
            //AddFooter(writer, 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("SmoothTech", new Font(Font.HELVETICA, 50, 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);
            var pageCount = writer.PageNumber >=1 ? writer.PageNumber-1 : writer.PageNumber;
            totalPages.ShowText("" + (pageCount));
            totalPages.EndText();
        }
    }


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

 

 

 

image

 

 

 

 

 

 

 

 

 

 

image

 

 

image

 

posted @ 2025-08-24 14:38  FredGrit  阅读(11)  评论(0)    收藏  举报