find and solve || findandsolve.com
Please wait.....

Create or Generate PDF file in ASP.NET Core 5

Create or Generate PDF file in ASP.NET Core 5

In this post, I'll show you how to generate a PDF using SelectPdf third party dll  file from .NET Core 5  MVC. Creating .NET Core PDF file  like as student Marksheet.Working with PDFs in .NET 5 MVC projects, as well as converting  pure html views.It’s common use case to want to generate PDF’s using C# code in .NET Core, either to serve directly to a user or to save locally.

Download Source Code : https://findandsolve.com/source-code/code-code-generate-pdf-document-in-asp-dot-net-core-5-source-code-example

By the end of this post, we will learn the following:

  1. Install SelectPdf for .NET core from NuGet package.
  2. Pass data in .html page from .NET Core ViewModel.
  3. Use IWebHostEnvironment in .NET core.
  4. How to use ReadAllText in .net core.
  5. HtmlToPdf/PdfDocument

Create new project in .NET Core 5 Create New Project in .NET 5.


Install SelectPdf for .NET core from NuGet package

To install the package, just right click on the project and then select Manage NuGet package. The below dialog of the NuGet Package Manager will pop up.In the pop up browse tab,search the type of “Select.HtmToPdf.NetCore” in the search box and just click on the Install button.


Select.HtmToPdf.NetCore



After install “Select.HtmToPdf.NetCore” 


Right click on wwwroot folder and select Add >> New Item.An “Add New Item” dialog box will open. Select ASP.NET -> Web->Content from the left panel, then select “HTML Page” from templates panel and put the name as DemoPDF.html. Press OK.




After adding DemoPDF.html


Open DemoPDF.html and put the code in this DemoPDF.html and pas this code as given below.     

CSS

<style type="text/css">
        body {
            width: 100%;
        }
        .page[size="A4"] {
            background: white;
            width: 100%;
            height: 29.7cm;
            display: block;
            margin: 0 auto;
            margin-bottom: 0.5cm;
        }
        .schoolDetails span {
            font-family: 'Times New Roman';
            font-weight: bold;
            letter-spacing: 1px;
            color: #054069;
        }
        .name {
            font-size: 20px;
        }
        .location {
            font-size: 20px;
        }
        .phone {
            margin-left: 50px;
        }
    </style>

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous"> </head>
<body>
    <div class="page" size="A6">
        <div style="margin-top:100px;">
            <div class="row schoolDetails">
                <div class="col-md-12" style="text-align:center;">
                    <div class="col-md-2">
                        <img src="https://www.findandsolve.com/images/fns/logo.png" style="float:left !important;border-radius:50px;" width="300" />                     </div>
                    <div class="col-md-10">
                        <div class="">
                            <span class="name">schoolName</span><br />
                            <span class="location">schoolAddress</span>
                            <br />
                            <span class="" style="font-size: 15px;">
                                Email :email
                            </span>
                            <br />
                        </div>
                    </div>
                </div>
            </div>
            <div style="margin-left:10%;margin-right:10%">
                <table class="" border="1" style="margin-top:100px;width:100%;">
                    <tbody>
                        <tr>
                            <th>Subject Name</th>
                            <th>Marks</th>
                        </tr>
                    </tbody>
                    <tbody>
                        <tr>
                            <td>subjectSQL</td>
                            <td>sqlMarks</td>
                        </tr>
                        <tr>
                            <td>subjectC</td>
                            <td>cMarks</td>
                        </tr>                         <tr>
                            <td>subjectEnglish</td>
                            <td>englishMarks</td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    </div>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
</body>
</html>


Create new StudentMarksheet.cs VewModel class under Model folder.



After Adding New StudentMarksheetViewModel.cs and past this code as give below.

      public class StudentMarksheetViewModel
        {
            //start school information
            public string SchoolName { get; set; }
            public string SchoolAddress { get; set; }
            public string Email { get; set; }
            //end school information
            //start student subject and marks
            public string SubjectSQL { get; set; }
            public decimal SQLMarks { get; set; }
            public string SubjectEnglish { get; set; }
            public decimal EnglishMarks { get; set; }
            public string SubjectC { get; set; }
            public decimal CMarks { get; set; }
            //end student subject and marks
        }

Open HomeController.cs and put this code as given below.

using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using PDFExample.Models;
using SelectPdf;
namespace PDFExample.Controllers
{
    public class HomeController : Controller
    {         IWebHostEnvironment _env;
        private readonly ILogger<HomeController> _logger;
        public HomeController(ILogger<HomeController> logger, IWebHostEnvironment env)
        {
            _logger = logger;
            _env = env;
        }
        public IActionResult Index()
        {
            HtmlToPdf pdf = new HtmlToPdf();
            string markSheet = string.Empty;
            markSheet = System.IO.File.ReadAllText(_env.WebRootPath + @"\DemoPDF.html");
            //create viewmodel object first
            StudentMarksheetViewModel model = new StudentMarksheetViewModel();
            // assing values in viewmodel as
            //school short infromation
            model.SchoolName = "Find and Solve Higher Secondary School";
            model.SchoolAddress = "New Baneshwor Kathamdnu";
            model.Email = "[email protected]";
            //end school short information
            //subject and marks
            model.SubjectSQL = "SQL Server";
            model.SQLMarks = 90;
            model.SubjectC = "C Programming";
            model.CMarks = 80;
            model.SubjectEnglish = "Compalsory English";
            model.EnglishMarks = 95;
            //now assign values in html page like as
              markSheet = markSheet.Replace("schoolName", model.SchoolName)
                .Replace("schoolAddress", model.SchoolAddress)
                .Replace("email", model.Email)
                .Replace("subjectSQL", model.SubjectSQL)
                .Replace("sqlMarks", model.SQLMarks.ToString())
                .Replace("subjectC", model.SubjectC)
                .Replace("cMarks", model.CMarks.ToString())
                .Replace("subjectEnglish", model.SubjectEnglish)
                .Replace("englishMarks", model.EnglishMarks.ToString());
             PdfDocument doc = pdf.ConvertHtmlString(markSheet);
            var bytes = doc.Save();
            return File(bytes, "application/pdf", "StudentMarksheet.pdf");
        }
    }
}

Conclusion

In this article, we have used the SelectPdf library to create PDF documents while working with the .NET 5 Core application. We have created StudentMarksheet PDF.

Selena  Kandakar

Selena Kandakar

I like working on projects with a team that cares about creating beautiful and usable interfaces.

Comments



Report Response