How to implement rotativa package to my asp.net core mvc?

MiKhel Navarra 20 Reputation points
2024-03-11T01:52:27.5133333+00:00

How to implement rotative package for print functionalities in my mvc project? How to implement methods to my controller, repository, interface and to my view?

This is my controller:
public async Task<IActionResult> PrintFoodItem(string item, string quantity, string unit, string amount, string remarks)

{

try

{

    // Parse quantity and amount to integers

    int parsedQuantity = int.Parse(quantity);

    int parsedAmount = int.Parse(amount);

    // Call repository method with parsed integers

    var records = await _unitOfWork.GetFoodItems(item, parsedQuantity, unit, parsedAmount, remarks);

    // Check if records are null or empty

    if (records == null || !records.Any())

    {

        // Handle the case when no records are found

        return View("NoRecordsFound");

    }

    // Convert records to a list

    var foodItemList = records.ToList();

    // Create view model

    FoodItemIndexViewModel model = new FoodItemIndexViewModel

    {

        Item = item,

        Quantity = quantity,

        Unit = unit,

        Amount = amount,

        Remarks = remarks,

        FoodItemList = (IEnumerable<ViewModels.FoodItemModel>)foodItemList

    };

    // Generate PDF view

    var pdfBytes = await new ViewAsPdf("PrintIP", model)

    {

        PageSize = Rotativa.AspNetCore.Options.Size.Legal,

        PageMargins = { Left = 10, Bottom = 5, Right = 10, Top = 5 },

    }.BuildFile(ControllerContext);

    // Save PDF to a temporary file

    var tempFilePath = Path.GetTempFileName();

    await System.IO.File.WriteAllBytesAsync(tempFilePath, pdfBytes);

    // Return JSON response with URL to the generated PDF

    return Json(new { url = tempFilePath });

}

catch (Exception ex)

{

    // Log the exception or handle it appropriately

    Console.WriteLine($"An error occurred: {ex.Message}");

    return Json(new { error = ex.Message });

}

}

This is in my Interface:
using CDSWD_Inventory_System.Models;

using CDSWD_Inventory_System.ViewModels;

namespace CDSWD_Inventory_System.Repositories.Interfaces

{

public interface IUnitOfWork

{

    IFoodItemRepository FoodItem { get; }

    INonFoodItemRepository NonFoodItem { get; }

    IRegisterInfoRepository RegisterInfo { get; }

    IDepartmentRepository Department { get; }

    Task<IEnumerable<FoodItem>> GetFoodItems(string item, int quantity, string unit, int amount, string remarks);

    void Save();

}

}

This is in my Repository:
public async Task<IEnumerable<FoodItem>> GetFoodItems(string item, int quantity, string unit, int amount, string remarks)

{

// Implement your logic to fetch food items based on parameters

// For example:

return await _db.FoodItems

    .Where(f =>

        f.Item == item &&

        f.Quantity == quantity &&

        f.Unit.Contains(unit) &&

        f.Amount == amount &&

        f.Remarks.Contains(remarks))

    .ToListAsync();

}

and lastly this is in my Index in my FoodItem view:
<div class="container">

<div class="card shadow border-0 my-4">

    <div class="card-header bg-primary bg-gradient py-3 d-flex justify-content-between align-items-center">

        <div class="text-center">

            <h2 class="text-white py-2">Food Items List</h2>

        </div>

        <div class="text-end">

            <a href="https://localhost:44338/Home/Index" class="btn btn-secondary btn-sm mb-2">Back to Homepage</a>

            <a asp-controller="FoodItem" asp-action="Upsert" class="btn btn-custom mb-2">

                <i class="bi bi-plus-circle"></i> Create New Food Items

            </a>

            <button id="printButton" class="btn btn-info btn-sm mb-2"><i class="bi bi-printer"></i> Print Report</button>

        </div>

    </div>

    <div class="card-body p-0">

        <div class="table-responsive">

            <!-- Make the table responsive -->

            <div class="mt-3 mb-3">

                <!-- Add margin to the top and bottom of the search bar and "Show entries" dropdown -->

                <!-- Your search bar and "Show entries" dropdown code here -->

            </div>

            <table id="tblData" class="table table-bordered table-striped mb-0">

                <thead>

                    <tr>

                        <th>Item</th>

                        <th>Quantity</th>

                        <th>Unit</th>

                        <th>Amount</th>

                        <th>Remarks</th>

                        <th></th>

                    </tr>

                </thead>

                <!-- Table body content here -->

            </table>

        </div>

    </div>

</div>

</div>

@section Scripts{

<script src="~/js/fooditem.js"></script>

<script>

    $(document).ready(function () {

        $('#printButton').on('click', function () {

            // Perform AJAX request to PrintFoodItem action

            $.ajax({

                url: '@Url.Action("PrintFoodItem", "FoodItem")',

                type: 'GET',

                data: {

                    item: 'your item value',

                    quantity: 'your quantity value',

                    unit: 'your unit value',

                    amount: 'your amount value',

                    remarks: 'your remarks value'

                },

                success: function (response) {

                    // Open the generated PDF in a new tab

                    window.open(response.url, '_blank');

                },

                error: function (xhr, status, error) {

                    // Handle errors

                    console.error(error);

                }

            });

        });

    });

</script>

}

<style>

.btn-custom {

    background-color: #335699;

    border-color: #335699;

    color: #fff;

}

    .btn-custom:hover {

        background-color: #2a487e;

        border-color: #2a487e;

        color: #fff;

    }

</style>

When i click the print button,
<th>Item</th>

<th>Quantity</th>

<th>Unit</th>

<th>Amount</th>

<th>Remarks</th>

this list of items are the only to be printed out to PDF Format and also downloadable.Screenshot 2024-03-08 094810

Screenshot 2024-03-08 094840

Screenshot 2024-03-08 094900

Screenshot 2024-03-08 094915

Screenshot 2024-03-08 094932

Screenshot 2024-03-08 094952

Screenshot 2024-03-08 095001

ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,803 questions
{count} votes

10 answers

Sort by: Most helpful
  1. MiKhel Navarra 20 Reputation points
    2024-03-12T07:28:54.2566667+00:00

    Good afternoon sir, I am currently using on Rotativa.AspNetCoreScreenshot 2024-03-12 152654

    0 comments No comments

  2. MiKhel Navarra 20 Reputation points
    2024-03-12T13:17:27.2833333+00:00

    Good evening sir.. no im not following a tutorial, i am learning on my own and try new things to improve myself.. still have a lot to discover and to learn, and yes i am having difficulty on which is which and hope you could be way of any help that i would understand.. hopefully, thank you.


  3. MiKhel Navarra 20 Reputation points
    2024-03-13T00:42:43.51+00:00

    Goodmorning sir, what i am trying to print is these parameters to the PrintFoodItem action. But I am having difficulty on trying to implement print report .Screenshot 2024-03-13 084010


  4. MiKhel Navarra 20 Reputation points
    2024-03-13T05:45:14.1866667+00:00

    Good afternoon sir, what do you mean missing code related to PrintIP?


  5. MiKhel Navarra 20 Reputation points
    2024-03-13T06:12:18.1666667+00:00

    I'm sorry for what I disclosed regarding my code, I think it is PrintFoodItem, sorry for the misinformation i shared.. Still learning. Thank you sir.
    Screenshot 2024-03-13 140902


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.