In my ๐ฝ๐ฒ๐ฟ๐๐ผ๐ป๐ฎ๐น ๐ฝ๐ฟ๐ผ๐ท๐ฒ๐ฐ๐ โ ๐๐ ๐ฝ๐ฒ๐ป๐๐ฒ ๐ ๐ฎ๐ป๐ฎ๐ด๐ฒ๐บ๐ฒ๐ป๐ ๐ฆ๐๐๐๐ฒ๐บ, I wanted to generate an ๐ฒ๐ ๐ฝ๐ฒ๐ป๐๐ฒ ๐ฟ๐ฒ๐ฝ๐ผ๐ฟ๐ for a ๐๐ฝ๐ฒ๐ฐ๐ถ๐ณ๐ถ๐ฐ ๐๐๐ฒ๐ฟ for the ๐ฐ๐๐ฟ๐ฟ๐ฒ๐ป๐ ๐บ๐ผ๐ป๐๐ต. I explored ๐ถ๐ง๐ฒ๐ ๐๐ฆ๐ต๐ฎ๐ฟ๐ฝ, a free library for generating PDFs in C#. Hereโs how I implemented it! ๐
๐น ๐ฆ๐๐ฒ๐ฝ๐ ๐๐ผ ๐๐ฒ๐ป๐ฒ๐ฟ๐ฎ๐๐ฒ ๐๐ต๐ฒ ๐ฃ๐๐ ๐ฅ๐ฒ๐ฝ๐ผ๐ฟ๐
1๏ธโฃ ๐๐ถ๐น๐๐ฒ๐ฟ ๐๐
๐ฝ๐ฒ๐ป๐๐ฒ๐ ๐ณ๐ผ๐ฟ ๐๐ต๐ฒ ๐๐๐ฟ๐ฟ๐ฒ๐ป๐ ๐ ๐ผ๐ป๐๐ต
First, we fetch the ๐น๐ผ๐ด๐ด๐ฒ๐ฑ-๐ถ๐ป ๐๐๐ฒ๐ฟโ๐ ๐ฒ๐
๐ฝ๐ฒ๐ป๐๐ฒ๐ from the database for the current month.
var userId = "User123"; // Replace with the actual logged-in user ID
var currentMonth = DateTime.Now.Month;
var currentYear = DateTime.Now.Year;
var expenses = _context.Expenses
.Where(e => e.UserId == userId && e.Date.Month == currentMonth && e.Date.Year == currentYear)
.ToList();
2๏ธโฃ ๐๐ฟ๐ฒ๐ฎ๐๐ฒ ๐ฎ ๐ฃ๐๐ ๐๐ผ๐ฐ๐๐บ๐ฒ๐ป๐ ๐๐ถ๐๐ต ๐ถ๐ง๐ฒ๐
๐๐ฆ๐ต๐ฎ๐ฟ๐ฝ
Now, we create a ๐ฃ๐๐ ๐ณ๐ถ๐น๐ฒ and add expense details.
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.IO;
public IActionResult GenerateExpenseReport()
{
using (MemoryStream ms = new MemoryStream())
{
Document document = new Document();
PdfWriter.GetInstance(document, ms);
document.Open();
// Add title
document.Add(new Paragraph("Expense Report - " + DateTime.Now.ToString("MMMM yyyy")));
document.Add(new Paragraph("User ID: " + userId));
document.Add(new Paragraph("\n"));
// Add expenses in a table format
PdfPTable table = new PdfPTable(3);
table.AddCell("Date");
table.AddCell("Description");
table.AddCell("Amount");
foreach (var expense in expenses)
{
table.AddCell(expense.Date.ToShortDateString());
table.AddCell(expense.Description);
table.AddCell(expense.Amount.ToString("C"));
}
document.Add(table);
document.Close();
return File(ms.ToArray(), "application/pdf", "ExpenseReport.pdf");
}
}
3๏ธโฃ ๐๐ผ๐๐ป๐น๐ผ๐ฎ๐ฑ ๐๐ต๐ฒ ๐ฃ๐๐
The ๐ด๐ฒ๐ป๐ฒ๐ฟ๐ฎ๐๐ฒ๐ฑ ๐ฃ๐๐ will contain the ๐๐๐ฒ๐ฟโ๐ ๐ฒ๐
๐ฝ๐ฒ๐ป๐๐ฒ๐ ๐ณ๐ผ๐ฟ ๐๐ต๐ฒ ๐ฐ๐๐ฟ๐ฟ๐ฒ๐ป๐ ๐บ๐ผ๐ป๐๐ต and will be available for download.
๐น ๐ช๐ต๐ ๐ถ๐ง๐ฒ๐
๐๐ฆ๐ต๐ฎ๐ฟ๐ฝ?
โ
๐๐ถ๐ด๐ต๐๐๐ฒ๐ถ๐ด๐ต๐ & ๐ณ๐ฟ๐ฒ๐ฒ (great for small projects).
โ
๐ฆ๐ถ๐บ๐ฝ๐น๐ฒ ๐๐ผ ๐๐๐ฒ โ generate PDFs with just a few lines of code.
โ
๐๐๐๐๐ผ๐บ๐ถ๐๐ฎ๐ฏ๐น๐ฒ โ you can format the report as needed.
๐ง๐ต๐ถ๐ ๐ฎ๐ฝ๐ฝ๐ฟ๐ผ๐ฎ๐ฐ๐ต ๐ต๐ฒ๐น๐ฝ๐ฒ๐ฑ ๐บ๐ฒ ๐ด๐ฒ๐ป๐ฒ๐ฟ๐ฎ๐๐ฒ ๐บ๐ผ๐ป๐๐ต๐น๐ ๐ฟ๐ฒ๐ฝ๐ผ๐ฟ๐๐ ๐ถ๐ป ๐บ๐ ๐๐ ๐ฝ๐ฒ๐ป๐๐ฒ ๐ ๐ฎ๐ป๐ฎ๐ด๐ฒ๐บ๐ฒ๐ป๐ ๐ฆ๐๐๐๐ฒ๐บ. ๐ช๐ต๐ฎ๐ ๐ฑ๐ผ ๐๐ผ๐ ๐๐ต๐ถ๐ป๐ธ? ๐๐ฎ๐๐ฒ ๐๐ผ๐ ๐๐๐ฒ๐ฑ ๐ถ๐ง๐ฒ๐ ๐๐ฆ๐ต๐ฎ๐ฟ๐ฝ ๐ฏ๐ฒ๐ณ๐ผ๐ฟ๐ฒ? ๐๐ฒ๐โ๐ ๐ฑ๐ถ๐๐ฐ๐๐๐ ๐ถ๐ป ๐๐ต๐ฒ ๐ฐ๐ผ๐บ๐บ๐ฒ๐ป๐๐! ๐ฌ๐
Top comments (0)