how to generate a PDF with dynamic header and footer

Mafiev Dev 1 Reputation point
2021-09-17T15:24:35.627+00:00

i need to create a PDF report doc and add to it a header with an image and add a footer with text and a page number on each page, can you recommend me the best library to do that?

ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,254 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,238 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Osjaetor 475 Reputation points
    2023-11-21T11:21:12.7566667+00:00

    Hi ,

    For generating PDFs with dynamic headers and footers in a Web Forms application, you can use a library that provides PDF generation capabilities. One popular and widely used library in the .NET ecosystem is iTextSharp.

    Install-Package itext7

    using System;
    using System.IO;
    using iText.Kernel.Pdf;
    using iText.Layout;
    using iText.Layout.Element;
    using iText.Layout.Properties;
    
    public class PdfGenerator
    {
        public static void GeneratePdf(string filePath)
        {
            using (var pdfWriter = new PdfWriter(filePath))
            {
                using (var pdf = new PdfDocument(pdfWriter))
                {
                    var document = new Document(pdf);
    
                    // Add header
                    AddHeader(document);
    
                    // Add content
                    AddContent(document);
    
                    // Add footer
                    AddFooter(document);
                }
            }
        }
    
        private static void AddHeader(Document document)
        {
            // Add header content, e.g., an image
            // Replace "path/to/header/image.png" with the actual path to your image
            var header = new Paragraph().Add(new Image(ImageDataFactory.Create("image.png")));
            document.Add(header);
        }
    
        private static void AddContent(Document document)
        {
            // Add your document content here
            var content = new Paragraph("Main Content.");
            document.Add(content);
        }
    
        private static void AddFooter(Document document)
        {
            // Add footer content, including page number
            var footer = new Paragraph()
                .Add("Page ")
                .Add(new PageNumber())
                .Add(" of ")
                .Add(new PageCount());
            document.Add(footer);
        }
    }
    

    Regards,

    0 comments No comments