Emo pdf report

This commit is contained in:
Илья Федотов 2024-08-01 15:04:29 +04:00
parent c12b242073
commit 12188b768d
10 changed files with 240 additions and 4 deletions

View File

@ -19,16 +19,19 @@ namespace ElectronicsShopBusinessLogic.BusinessLogic
private readonly IProductStorage _productStorage;
private readonly IPaymeantStorage _paymeantStorage;
private readonly IOrderStorage _orderStorage;
private readonly AbstractSaveToPdfEmployee _saveToPdf;
private readonly AbstractSaveToWordEmployee _saveToWord;
private readonly AbstractSaveToExcelEmployee _saveToExcel;
public ReportEmployeeLogic(AbstractSaveToExcelEmployee abstractSaveToExcelEmployee, AbstractSaveToWordEmployee abstractSaveToWordEmployee,
IProductStorage productStorage, IPaymeantStorage paymeantStorage, IOrderStorage orderStorage) {
AbstractSaveToPdfEmployee abstractSaveToPdfEmployee ,IProductStorage productStorage,
IPaymeantStorage paymeantStorage, IOrderStorage orderStorage) {
_productStorage = productStorage;
_paymeantStorage = paymeantStorage;
_orderStorage = orderStorage;
_saveToExcel = abstractSaveToExcelEmployee;
_saveToWord = abstractSaveToWordEmployee;
_saveToPdf = abstractSaveToPdfEmployee;
}
public List<ReportProductInPaymeantsViewModel> GetProducts(ReportProductBindingModel model)
{
@ -82,13 +85,28 @@ namespace ElectronicsShopBusinessLogic.BusinessLogic
{
var document = _saveToExcel.CreateReport(new ExcelInfoEmployee
{
Title = "Список продуктов",
Title = "Список оплат электротоваров",
ListProduct = GetProducts(model),
});
return document;
}
public byte[]? SaveProductsToWordFile(ReportProductBindingModel model)
public byte[]? SaveProductsToPdfFile(ReportProductBindingModel model) {
var document = _saveToPdf.CreateDoc(new PdfInfoEmployee {
Title = "Список оплат электротоваров",
DateFrom = model.DateFrom,
DateTo = model.DateTo,
ListProduct = GetProducts(model),
FileName = "Report"
});
MemoryStream stream = new MemoryStream();
document.Save(stream, true);
byte[] data = stream.ToArray();
return data;
}
public byte[]? SaveProductsToWordFile(ReportProductBindingModel model)
{
var document = _saveToWord.CreateDoc(new WordInfoEmployee {
Title = "Список оплат электротоваров",

View File

@ -20,7 +20,7 @@ namespace ElectronicsShopBusinessLogic.OfficePackage
alignmentType = PdfParagraphAlignmentType.Center,
});
CreateParagraph(new PdfParagraph {
Text = $"c {info.DateFrom.ToShortDateString()} по {info.DateTo.ToShortDateString()}",
Text = $"C {info.DateFrom.ToShortDateString()} по {info.DateTo.ToShortDateString()}",
Style = "Normal",
alignmentType = PdfParagraphAlignmentType.Right
});

View File

@ -0,0 +1,78 @@
using ElectronicsShopBusinessLogic.OfficePackage.HelperEnums;
using ElectronicsShopBusinessLogic.OfficePackage.HelperModels;
using PdfSharp.Pdf;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ElectronicsShopBusinessLogic.OfficePackage {
public abstract class AbstractSaveToPdfEmployee {
public PdfDocument CreateDoc (PdfInfoEmployee info) {
CreatePdf(info);
CreateParagraph(new PdfParagraph {
Text = info.Title,
Style = "NormalTitle",
alignmentType = PdfParagraphAlignmentType.Center,
});
CreateParagraph(new PdfParagraph {
Text = $"C {info.DateFrom.ToShortDateString()} по {info.DateTo.ToShortDateString()}",
Style = "Normal",
alignmentType = PdfParagraphAlignmentType.Right
});
foreach (var product in info.ListProduct) {
CreateParagraph(new PdfParagraph {
Text = product.ProductName,
Style = "Normal",
alignmentType = PdfParagraphAlignmentType.Left,
});
CreateTable(new List<string> { "2cm", "4cm", "4cm", "4cm" });
CreateRow(new PdfRowParameters {
Text = new List<string> { "Оплата №", "Статус", "Количество товара", "Сумма" },
Style = "NormalTittle",
alignmentType = PdfParagraphAlignmentType.Center,
});
foreach (var paymeant in product.Values) {
CreateRow(new PdfRowParameters {
Text = new List<string> {
paymeant.PaymeantID.ToString(),
paymeant.PaymeantStatus.ToString(),
paymeant.ProducCount.ToString(),
paymeant.ProductSum.ToString()
},
Style = "Normal",
alignmentType= PdfParagraphAlignmentType.Left,
});
}
CreateParagraph(new PdfParagraph {
Text = $"Итого: {product.Total}\t",
Style = "Normal",
alignmentType = PdfParagraphAlignmentType.Right
});
}
var document = SavePdf(info);
return document;
}
// Создание файла
protected abstract void CreatePdf(PdfInfoEmployee info);
// Создание параграфа с текстом
protected abstract void CreateParagraph(PdfParagraph paragraph);
// Создание таблицы
protected abstract void CreateTable(List<string> columns);
// Создание и заполнение строки
protected abstract void CreateRow(PdfRowParameters rowParameters);
// Сохранение файла
protected abstract PdfDocument SavePdf(PdfInfoEmployee info);
}
}

View File

@ -0,0 +1,16 @@
using ElectronicsShopContracts.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ElectronicsShopBusinessLogic.OfficePackage.HelperModels {
public class PdfInfoEmployee {
public string FileName { get; set; } = string.Empty;
public string Title { get; set; } = string.Empty;
public DateTime DateFrom { get; set; }
public DateTime DateTo { get; set; }
public List<ReportProductInPaymeantsViewModel> ListProduct { get; set; } = new();
}
}

View File

@ -0,0 +1,96 @@
using ElectronicsShopBusinessLogic.OfficePackage.HelperEnums;
using ElectronicsShopBusinessLogic.OfficePackage.HelperModels;
using MigraDoc.DocumentObjectModel;
using MigraDoc.DocumentObjectModel.Tables;
using MigraDoc.Rendering;
using PdfSharp.Pdf;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ElectronicsShopBusinessLogic.OfficePackage.Implements {
public class SaveToPdfEmployee : AbstractSaveToPdfEmployee {
private Document? _document;
private Section? _section;
private Table? _table;
// Типы выравнивания
private static ParagraphAlignment GetParagraphAlignment(PdfParagraphAlignmentType type) {
return type switch {
PdfParagraphAlignmentType.Center => ParagraphAlignment.Center,
PdfParagraphAlignmentType.Left => ParagraphAlignment.Left,
PdfParagraphAlignmentType.Right => ParagraphAlignment.Right,
_ => ParagraphAlignment.Justify
};
}
private static void DefineStyle(Document document) {
var style = document.Styles["Normal"];
style.Font.Name = "Times New Roman";
style.Font.Size = 14;
style = document.Styles.AddStyle("NormalTitle", "Normal");
style.Font.Bold = true;
}
protected override void CreateParagraph(PdfParagraph pdfParagraph) {
if (_section == null) {
return;
}
var paragraph = _section.AddParagraph(pdfParagraph.Text);
paragraph.Format.SpaceAfter = "1cm";
paragraph.Format.Alignment = GetParagraphAlignment(pdfParagraph.alignmentType);
paragraph.Style = pdfParagraph.Style;
}
protected override void CreatePdf(PdfInfoEmployee info) {
_document = new Document();
DefineStyle(_document);
// Ссылка на первую секцию
_section = _document.AddSection();
}
protected override void CreateRow(PdfRowParameters rowParameters) {
if (_table == null) {
return;
}
var row = _table.AddRow();
for (int i = 0; i < rowParameters.Text.Count; ++i) {
// заполнение ячейки (добавление параграфа в ячейку)
row.Cells[i].AddParagraph(rowParameters.Text[i]);
if (!string.IsNullOrEmpty(rowParameters.Style)) {
row.Cells[i].Style = rowParameters.Style;
}
Unit borderWidth = 0.5;
row.Cells[i].Borders.Left.Width = borderWidth;
row.Cells[i].Borders.Right.Width = borderWidth;
row.Cells[i].Borders.Top.Width = borderWidth;
row.Cells[i].Borders.Bottom.Width = borderWidth;
row.Cells[i].Format.Alignment = GetParagraphAlignment(rowParameters.alignmentType);
row.Cells[i].VerticalAlignment = VerticalAlignment.Center;
}
}
protected override void CreateTable(List<string> columns) {
if (_document == null) {
return;
}
_table = _document.LastSection.AddTable();
foreach (var elem in columns) {
_table.AddColumn(elem);
}
}
protected override PdfDocument SavePdf(PdfInfoEmployee info) {
var renderer = new PdfDocumentRenderer(true) {
Document = _document,
};
renderer.RenderDocument();
renderer.PdfDocument.Save(info.FileName);
return renderer.PdfDocument;
}
}
}

View File

@ -13,5 +13,6 @@ namespace ElectronicsShopContracts.BusinessLogicContracts
List<ReportProductInPaymeantsViewModel> GetProducts(ReportProductBindingModel model);
byte[]? SaveProductsToWordFile(ReportProductBindingModel model);
byte[]? SaveProductsToExcelFile(ReportProductBindingModel model);
byte[]? SaveProductsToPdfFile(ReportProductBindingModel model);
}
}

View File

@ -363,5 +363,16 @@ namespace ElectronicsShopEmployeeApp.Controllers {
return File(fileMemStream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Report.xlsx");
}
[HttpGet]
public IActionResult CreatePdfReport(string DateFrom, string DateTo) {
var fileMemStream = APIEmployee.GetRequset<byte[]>($"api/Employee/CreatePdfReport?from={DateFrom}&to={DateTo}");
if (fileMemStream == null) {
throw new Exception("Îøèáêà ñîçäàíèÿ îò÷åòà");
}
return File(fileMemStream, "application/pdf", "Report.pdf");
}
}
}

View File

@ -180,5 +180,20 @@ namespace ElectronicsShopRestAPI.Controllers {
throw;
}
}
[HttpGet]
public byte[]? CreatePdfReport(string from, string to) {
try {
var document = _reportEmployeeLogic.SaveProductsToPdfFile(new ReportProductBindingModel {
DateFrom = DateTime.Parse(from),
DateTo = DateTime.Parse(to)
});
return document;
}
catch (Exception ex) {
_logger.LogError(ex, "Ошибка создания файла");
throw;
}
}
}
}

View File

@ -30,6 +30,7 @@ builder.Services.AddTransient<AbstractSaveToExcelEmployee, SaveToExcelEmployee>(
builder.Services.AddTransient<AbstractSaveToWordClient, SaveToWordClient>();
builder.Services.AddTransient<AbstractSaveToWordEmployee, SaveToWordEmployee>();
builder.Services.AddTransient<AbstractSaveToPdfClient, SaveToPdfClient>();
builder.Services.AddTransient<AbstractSaveToPdfEmployee, SaveToPdfEmployee>();
builder.Services.AddTransient<IClientLogic, ClientLogic>();
builder.Services.AddTransient<IEmployeeLogic, EmployeeLogic>();