Yogesh Shinde
Yogesh Shinde

Reputation: 85

Create PDF file with fixed header, footer and dynamic content in every page in C# ASP.NET Core Web API

I need to create a .PDF file in ASP.NET Core Web API which will have a fixed header and footer on every page, and dynamic content as per the supplied data.

I'm using DinktoPDF for creating the PDF file, but not getting the exact PDF file I want.

The PDF file should show pages as per the size of the content and fixed header and footer in every page of the PDF file.

I need an open source library not a paid one like IronPDF, Aspose,etc

[HttpPost]
[Route("generatepdf")]
public IActionResult GeneratePdf([FromBody] PdfGenerationRequest request)
{
    try
    {
        var htmlContent = $@"
        <html>
        <head>
            <style>
                /* CSS for fixed header */
                .header {{
                    position: fixed;
                    top: 0;
                    left: 0;
                    right: 0;
                    background-color: #007bff;
                    color: white;
                    padding: 10px;
                    text-align: center;
                }}
                /* CSS for fixed footer */
                .footer {{
                    position: fixed;
                    bottom: 0;
                    left: 0;
                    right: 0;
                    background-color: #007bff;
                    color: white;
                    padding: 10px;
                    text-align: center;
                }}
                /* CSS for dynamic content */
                .content {{
                    margin-top: 100px; /* Adjust as per header height */
                    margin-bottom: 50px; /* Adjust as per footer height */
                }}
            </style>
        </head>
        <body>
            <div class='header'>Fixed Header</div>
            <div class='content'>{request.DynamicContent}</div>
            <div class='footer'>Fixed Footer</div>
        </body>
        </html>";

        var pdf = new HtmlToPdfDocument()
        {
            GlobalSettings = {
            ColorMode = ColorMode.Color,
            Orientation = Orientation.Portrait,
            PaperSize = PaperKind.A4,
        },
            Objects = {
            new ObjectSettings() {
                HtmlContent = htmlContent
            }
        }
        };

        var file = _converter.Convert(pdf);
        return File(file, "application/pdf", "output.pdf");
    }
    catch (Exception ex)
    {
        return StatusCode(500, $"An error occurred while generating the PDF: {ex.Message}");
    }
}

Upvotes: 1

Views: 248

Answers (0)

Related Questions