.net core to create PDF documents using Rotativa

First, download Rotaiva

    Tools => NuGet Package Manager => NuGet management solution package

    In the page that opens search Rotativa.AspNetCore below:

   

    Select the red box of records, you will be left to solve all the projects in the program, select the item you want to add click installation, the version number will appear behind the project after the installation is complete, as shown below:

   

Second, the configuration Rotaiva

    Add the following in Rotaiva method Startup.cs in:  

RotativaConfiguration.Setup(env);

    The complete code is as follows:  

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
    }
    RotativaConfiguration.Setup(env);//RotativaConfiguration 转PDF 功能
    app.UseStaticFiles();
    app.UseCookiePolicy();

    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
        });
    }
}

    Add PDF conversion tool

    Add Rotativa directory under the wwwroot directory, then copied into wkhtmltoimage.exe and wkhtmltopdf.exe,

    This two files in this website: https: //github.com/webgio/Rotativa.AspNetCore

    As shown below:

   

Third, begin to build a static PDF file

     Action at the establishment of a HomeController, as shown below:

   

[HttpGet]
public IActionResult Pdf()
{
    return new ViewAsPdf("Pdf");
}

    Then establish cshtml

   

@{
    ViewData["Title"] = "Pdf";
}

<h2>Pdf</h2>

    Start the project, the printed page, you can see the download page pdf, final PDF is as follows:

   

Fourth, create dynamic PDF files

    Establish Controller  

[HttpGet]
public IActionResult PdfDemo()
{
    List<tbl_page> pageList = new List<tbl_page>();
    pageList.Add(new tbl_page() 
{ page_name
="1", page_no="1" }); pageList.Add(new tbl_page() { page_name = "2", page_no = "2" }); pageList.Add(new tbl_page() { page_name = "3", page_no = "3" }); return new ViewAsPdf(pageList); }

    Generate cshtml  

@model IEnumerable<NetCoreApiDemo.Model.tbl_page>
@{
    ViewData["Title"] = "PdfDemo";
}

<h2>PdfDemo</h2>
<table class="table table-bordered">
    <thead>
        <tr>
            <th>page_no</th>
            <th>page_name</th>
        </tr>
    </thead>
    <tbody>
        @foreach (var item in Model)
        {
            <tr>
                <td>@item.page_no</td>
                <td>@item.page_name</td>
            </tr>
        }
    </tbody>
</table>

    The final PDF is generated as follows:

   

Guess you like

Origin www.cnblogs.com/zbspace/p/11617725.html