European ASP.NET MVC 4 and MVC 5 Hosting

BLOG about ASP.NET MVC 3, ASP.NET MVC 4, and ASP.NET MVC 5 Hosting and Its Technology - Dedicated to European Windows Hosting Customer

ASP.NET MVC Hosting - HostForLIFE.eu :: PDF Generation in ASP.NET Core MVC using Puppeteer Sharp

clock August 22, 2025 09:06 by author Peter

In today’s digital world, internet activities are a vital part of our everyday life. Web-based applications are becoming more and more necessary as a result of this. The capacity to create PDFs from HTML is a common need of many web-based programs. Online ticketing, certifications, online purchase invoices, and many more are examples of everyday use cases.


Although utilities like DinkToPdf and iTextSharp can convert HTML to PDF, they frequently have trouble rendering in current CSS and JavaScript. This is Puppeteer Sharp's strong suit.

Puppeteer Sharp provides browser-quality PDFs, supports dynamic content, and integrates seamlessly into .NET apps, making it a significant improvement over traditional PDF generation libraries for web content.

Puppeteer Sharp is a .NET port of Google’s Puppeteer, a Node.js library for controlling Chrome or Chromium. It allows developers to.

  • Render HTML just like a browser would.
  • Apply advanced CSS styling.
  • Run JavaScript before capturing.
  • Export the rendered page to a PDF.

Benefits of using Puppeteer Sharp

  • Accurate Rendering: It uses the Chromium browser engine to maintain the accuracy of rendering.
  • Modern CSS and JavaScript Support: It can handle dynamic pages and animations.
  • Custom Layouts: Paper sizes, margins, headers and footers can be customized.
  • Automation Ready: It can be used in background tasks.


Installing Puppeteer Sharp

  • Using Visual Studio (NuGet Package Manager UI)
    • Right-click on your project in Solution Explorer.
    • Select Manage NuGet Packages for Solution.
    • Go to the Browse tab.
    • Search for PuppeteerSharp.
    • Select the latest stable version.
    • Click Install.

Using Package Manager Console: Open Tools > NuGet Package Manager > Package Manager Console, then run.

Install-Package PuppeteerSharp

Using .NET CLI: If you prefer the terminal/command line, run.

dotnet add package PuppeteerSharp

Generating a PDF from a Web page
Generate Invoice Example.
    [HttpPost]
    [Route("generate-invoice-pdf")]
    public async Task<IActionResult> GenerateInvoicePdf()
    {
        // Downloads Chromium if it's not already available
        await new BrowserFetcher().DownloadAsync();

        // Launch headless Chromium
        await using var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true });

        // Open a new page
        await using var page = await browser.NewPageAsync();

        // Navigate to a URL (can also be a local MVC view)
        var url = $"{Request.Scheme}://{Request.Host}/pdf";
        await page.GoToAsync(url, WaitUntilNavigation.Networkidle0);

        // Generate PDF
        var pdfBytes = await page.PdfDataAsync(new PdfOptions
        {
            Format = PaperFormat.A4,
            PrintBackground = true,
            MarginOptions = new MarginOptions
            {
                Top = "20px",
                Bottom = "20px",
                Left = "20px",
                Right = "20px"
            }
        });

        // Close the browser
        await browser.CloseAsync();

        // Returns downloadable file
        var fileName = $"PDF_{DateTime.Now:yyyyMMdd_HHmm}.pdf";
        return File(pdfBytes, "application/pdf", fileName);
    }


Generate an External Web Page as a PDF.
[HttpPost]
[Route("generate-html-pdf")]
public async Task<IActionResult> GenerateHtmlPdf()
{
    // Downloads Chromium if it's not already available
    await new BrowserFetcher().DownloadAsync();

    // Launch headless Chromium
    await using var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true });

    // Open a new page
    await using var page = await browser.NewPageAsync();

    // Navigate to a URL (can also be a local MVC view)
    var url = "https://www.google.com/";
    await page.GoToAsync(url, WaitUntilNavigation.Networkidle0);

    // Generate PDF
    var pdfBytes = await page.PdfDataAsync(new PdfOptions
    {
        Format = PaperFormat.A4,
        PrintBackground = true,
        MarginOptions = new MarginOptions
        {
            Top = "20px",
            Bottom = "20px",
            Left = "20px",
            Right = "20px"
        }
    });

    // Close the browser
    await browser.CloseAsync();

    // Returns downloadable file
    var fileName = $"PDF_{DateTime.Now:yyyyMMdd_HHmm}.pdf";
    return File(pdfBytes, "application/pdf", fileName);
}

Razor View.
<h2>Generate PDF using Puppeteer Sharp</h2>

<div style="display: flex; justify-content: space-between; align-items: center; width: 33%; margin: 50px auto 0 auto;">
    <form asp-controller="Pdf" asp-action="GenerateInvoicePdf" method="post" style="margin: 0;">
        <button type="submit" class="btn btn-primary">Download Invoice PDF</button>
    </form>
    <form asp-controller="Pdf" asp-action="GenerateHtmlPdf" method="post" style="margin: 0;">
        <button type="submit" class="btn btn-primary">Download Web PDF</button>
    </form>
</div>


How does it work?

  • First BrowserFetcher downloads a compatible chromium browser if needed.
  • The LaunchAsync method starts a headless instance of Chromium
  • NewPageAsync opens a new tab in Chromium. If Headless is set to false then you will see the browser's window with tab.
  • GoToAsync navigates to the target URL
  • PDFDataAsync captures the page as a PDF in memory.
  • The PDF is returned as a downloadable file to the client

Additional Tips
For the first time the PDF generation is slow and it’s the common issue with Puppeteer Sharp. To solve this problem, pre-download Chromium. This way, you can avoid first-request delays.

// Pre-download Chromium at startup
var fetcher = new BrowserFetcher();
await fetcher.DownloadAsync();

Suppose you add the above lines of code to your Program.cs, Chromium is downloaded during the application initialization for the first time.

Conclusion

Puppeteer Sharp is one of the powerful tools for PDF generation with modern web compatibility. It brings the flexibility of Chromium automation into the .NET ecosystem. Whether you are adding a PDF export feature or generating screenshots for preview, Puppeteer Sharp is a robust choice in .NET. With just a few lines of code, you can easily automate complex HTML to PDF. Note. Project source code can be downloaded from GitHub



ASP.NET MVC Hosting - HostForLIFE.eu :: Email Notification Using Web API 2 in ASP.NET MVC 5

clock August 7, 2025 08:53 by author Peter

In this post, we'll build the Web API, use MVC 5 to access it, and use Web API 2 to send emails.


Let's begin gradually:

  • Work with a web application by creating an ASP.NET web application.
  • Including a model
  • Including a controller
  • Including a Helper class
  • Using JavaScript and JQuery to Call the Web Api (test web API)
  • To call the API and send an email notification, use the Rest client (Install Fiddler).
Create the project
Start Visual Studio 2013/2015 and from the File menu, select New, then Project.
Select the ASP.NET Web Application project template. Name the project Email Notification and click OK.

Select a template Web API.

Add a model class
A model is an object that represents the data in your application. In this case, the only model is a TeamA item.

Add a class file “TeamA.cs”.

Replace the generated code with:
    namespace EmailNotification.Models  
    {  
        public class TeamA  
        {  
            public int Id  
            {  
                get;  
                set;  
            }  
            public string Name  
            {  
                get;  
                set;  
            }  
            public string Type  
            {  
                get;  
                set;  
            }  
            public decimal Price  
            {  
                get;  
                set;  
            }  
        }  
    }  


Add a controller

In the Add Scaffold wizard, select the Web API 2 Empty Controller: Name it EmailNotifier.

In the Add Controller dialog, name the controller "EmailNotifierController " and click Add.

Replace code with the following controller.
    public class EmailNotifierController: ApiController  
    {  
        TeamGroupA[] teamA = new TeamGroupA[]  
        {  
            new TeamGroupA  
            {  
                Id = 1, Name = "zing", Type = "Cricket", Price = 1  
            },  
            new TeamGroupA  
            {  
                Id = 2, Name = "Yo-yo", Type = "Football", Price = 3.75 M  
            },  
            new TeamGroupA  
            {  
                Id = 3, Name = "soft", Type = "Software", Price = 16.99 M  
            }  
        };  
        // Run the application  
        public IEnumerable < TeamGroupA > GetAllTeams()  
        {  
            return teamA;  
        }  
    }  


To keep the example simple, TeamGroupA has stored in a fixed array inside the controller class. But, in a real application, you would get it from the Data access layer or use some other external data source.

The controller defines two methods that return products:
The GetAllTeams method returns the entire list of products as an IEnumerable<TeamGroupA> type.

As we are working with Web API it may contain one or more methods.

Now add new model for AdpaterResponsebase for another API method as SendEmailNotification.cs.

AdapterResponseBase.cs

Replace model code with the following code:
    using System;  
    using System.Collections.Generic;  
    namespace EmailNotification.Models  
    {  
        public class ResponseBase  
        {}  
        public class RequestBase  
        {}  
        public class RequestBase < T > : RequestBase  
        {  
            public RequestBase()  
            {}  
            public RequestBase(T data)  
            {  
                Data = data;  
            }  
            public T Data  
            {  
                get;  
                set;  
            }  
        }  
    }  


Add new Helper class file EMailHelper.cs to folder named Helpers.

    using System;  
    namespace EmailNotofication.Models  
    {  
        public class EmailInput  
        {  
            public string UserName  
            {  
                get;  
                set;  
            }  
            public string EmailId  
            {  
                get;  
                set;  
            }  
        }  
    }  

Now we will start with UI part.

Calling the Web API with Javascript and jQuery

Here we will add an HTML page that uses AJAX to call the web API. We'll use jQuery to make the AJAX calls and also to update the page with the results.
In Solution Explorer, right-click the project and select Add, then select New Item.

In the Add New Item dialog, select the Web node under Visual C#, and then select the HTML Page item. Name the page "index.html".


Replace everything in this file with the following:
    <!DOCTYPE html>  
    <html xmlns="http://www.w3.org/1999/xhtml">  
      
    <head>  
        <title>Notification App</title>  
    </head>  
      
    <body>  
        <div>  
            <h2>All Teams</h2>  
            <ul id="teams" /> </div>  
        <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>  
        <script>  
            var uri = 'api/EmailNotifier/GetAllTeams';  
            $(document).ready(function()  
            {  
                // Send an AJAX request  
                $.getJSON(uri).done(function(data)  
                {  
                    // On success, 'data' contains a list of teams.  
                    $.each(data, function(key, item)  
                    {  
                        // Add a list item for the teams.  
                        $('<li>',  
                        {  
                            text: formatItem(item)  
                        }).appendTo($('#teams'));  
                    });  
                });  
            });  
      
            function formatItem(item)  
            {  
                return item.Name + ': $' + item.Price;  
            }  
        </script>  
    </body>  
      
    </html>  


Getting a List of Teams
To get a list of teams, send an HTTP GET request to "/api/GetAllTeams".

Set index.html as start page:

Run the project,
Yippee! Here we got success for calling Web API using Ajax. Now let’s add method for Email Notification.

We will call SendEmailNotification API using RestClient.

Add the following method to controller:
    [HttpPost]  
    public async Task < IHttpActionResult > SendEmailNotification(EmailInput data)  
    {  
        ResponseBase updateResponse = new ResponseBase();  
        var updateRequest = new RequestBase < EmailInput > (data);  
        try  
        {  
            EMailHelper mailHelper = new EMailHelper(EMailHelper.EMAIL_SENDER, EMailHelper.EMAIL_CREDENTIALS, EMailHelper.SMTP_CLIENT);  
            var emailBody = String.Format(EMailHelper.EMAIL_BODY);  
            if(mailHelper.SendEMail(data.EmailId, EMailHelper.EMAIL_SUBJECT, emailBody))  
            {  
                //   
            }  
        }  
        catch(Exception ex)  
        {}  
        return Ok(updateResponse);  
    }  

You need to add extension for RestClient to your chrome browser to call API. Pass the parameter and do necessary changes to call API from rest client as in the following:

http://localhost:21084/api/EmailNotifier/SendEmailNotification

HTTPPOST
    Content-Type: application/json  
    {  
       "UserName": "xyz",  
       "EmailId" : "[email protected]",  
    }  

Once you click on send button, you can verify input parameter by adding debug point to API in controller

After successful execution we will get response as follows:

Note: To send email you need to add actual email id and credential so that it will work as expected.



About HostForLIFE.eu

HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes.

We have offered the latest Windows 2016 Hosting, ASP.NET Core 2.2.1 Hosting, ASP.NET MVC 6 Hosting and SQL 2017 Hosting.


Tag cloud

Sign in