отчет пдф

This commit is contained in:
Мк Игорь 2023-05-25 23:49:07 +04:00
parent 4e1d0b7b99
commit 916c25e2d0
8 changed files with 203 additions and 7 deletions

View File

@ -16,14 +16,16 @@ namespace CarServiceBusinessLogic.BusinessLogics
private readonly IWorkPaymentStorage _workPaymentStorage; private readonly IWorkPaymentStorage _workPaymentStorage;
private readonly AbstractSaveToWord _saveToWord; private readonly AbstractSaveToWord _saveToWord;
private readonly AbstractSaveToExcel _saveToExcel; private readonly AbstractSaveToExcel _saveToExcel;
private readonly AbstractSaveToPdf _saveToPdf;
public ReportLogic(ILogger<ReportLogic> logger, IWorkStorage workStorage, IWorkPaymentStorage workPaymentStorage, AbstractSaveToWord saveToWord, AbstractSaveToExcel saveToExcel) public ReportLogic(ILogger<ReportLogic> logger, IWorkStorage workStorage, IWorkPaymentStorage workPaymentStorage, AbstractSaveToWord saveToWord, AbstractSaveToExcel saveToExcel, AbstractSaveToPdf saveToPdf)
{ {
_logger = logger; _logger = logger;
_workStorage = workStorage; _workStorage = workStorage;
_workPaymentStorage = workPaymentStorage; _workPaymentStorage = workPaymentStorage;
_saveToWord = saveToWord; _saveToWord = saveToWord;
_saveToExcel = saveToExcel; _saveToExcel = saveToExcel;
_saveToPdf = saveToPdf;
} }
public List<ReportWorkWithRequestsViewModel> GetRequestsByWorks(ReportBindingModel model) public List<ReportWorkWithRequestsViewModel> GetRequestsByWorks(ReportBindingModel model)
{ {
@ -53,9 +55,16 @@ namespace CarServiceBusinessLogic.BusinessLogics
WorksWithRequests = GetRequestsByWorks(model) WorksWithRequests = GetRequestsByWorks(model)
}); });
} }
public void SaveOrdersToPdfFile(ReportBindingModel model) public void SavePaymentsToPdfFile(ReportBindingModel model)
{ {
throw new NotImplementedException(); _saveToPdf.CreateDoc(new PdfInfo
{
FileName = model.FileName,
Title = "Список оплат",
DateFrom = model.DateFrom!.Value,
DateTo = model.DateTo!.Value,
Payments = GetPayments(model)
});
} }
} }
} }

View File

@ -0,0 +1,68 @@
using BlacksmithWorkshopBusinessLogic.OfficePackage.HelperEnums;
using BlacksmithWorkshopBusinessLogic.OfficePackage.HelperModels;
namespace BlacksmithWorkshopBusinessLogic.OfficePackage
{
public abstract class AbstractSaveToPdf
{
public void CreateDoc(PdfInfo info)
{
CreatePdf(info);
CreateParagraph(new PdfParagraph
{
Text = info.Title,
Style = "NormalTitle",
ParagraphAlignment = PdfParagraphAlignmentType.Center
});
CreateParagraph(new PdfParagraph
{
Text = $"с { info.DateFrom.ToShortDateString() } по { info.DateTo.ToShortDateString() }", Style = "Normal",
ParagraphAlignment = PdfParagraphAlignmentType.Center
});
CreateTable(new List<string> { "3cm", "2,5cm", "2cm", "2,5cm", "2,5cm", "2,5cm", "3cm" });
CreateRow(new PdfRowParameters
{
Texts = new List<string> { "Дата оплаты", "Клиент", "Номер заявки", "Работа", "Сумма платежа", "Всего оплачено", "Осталось оплатить" },
Style = "NormalTitle",
ParagraphAlignment = PdfParagraphAlignmentType.Center
});
foreach (var payment in info.Payments)
{
CreateRow(new PdfRowParameters
{
Texts = new List<string> { payment.PaymentDate.ToShortDateString(), payment.CustomerName, payment.RepairRequestId.ToString(), payment.WorkName, payment.PaymentSum.ToString(), payment.Paid.ToString(), payment.NotPaid.ToString() },
Style = "Normal",
ParagraphAlignment = PdfParagraphAlignmentType.Left
});
}
SavePdf(info);
}
/// <summary>
/// Создание doc-файла
/// </summary>
/// <param name="info"></param>
protected abstract void CreatePdf(PdfInfo info);
/// <summary>
/// Создание параграфа с текстом
/// </summary>
/// <param name="title"></param>
/// <param name="style"></param>
protected abstract void CreateParagraph(PdfParagraph paragraph);
/// <summary>
/// Создание таблицы
/// </summary>
/// <param name="title"></param>
/// <param name="style"></param>
protected abstract void CreateTable(List<string> columns);
/// <summary>
/// Создание и заполнение строки
/// </summary>
/// <param name="rowParameters"></param>
protected abstract void CreateRow(PdfRowParameters rowParameters);
/// <summary>
/// Сохранение файла
/// </summary>
/// <param name="info"></param>
protected abstract void SavePdf(PdfInfo info);
}
}

View File

@ -0,0 +1,100 @@
using BlacksmithWorkshopBusinessLogic.OfficePackage.HelperEnums;
using BlacksmithWorkshopBusinessLogic.OfficePackage.HelperModels;
using MigraDoc.DocumentObjectModel;
using MigraDoc.DocumentObjectModel.Tables;
using MigraDoc.Rendering;
namespace BlacksmithWorkshopBusinessLogic.OfficePackage.Implements
{
public class SaveToPdf : AbstractSaveToPdf
{
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,
};
}
/// <summary>
/// Создание стилей для документа
/// </summary>
/// <param name="document"></param>
private static void DefineStyles(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 CreatePdf(PdfInfo info)
{
_document = new Document();
DefineStyles(_document);
_section = _document.AddSection();
}
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.ParagraphAlignment);
paragraph.Style = pdfParagraph.Style;
}
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 void CreateRow(PdfRowParameters rowParameters)
{
if (_table == null)
{
return;
}
var row = _table.AddRow();
for (int i = 0; i < rowParameters.Texts.Count; ++i)
{
row.Cells[i].AddParagraph(rowParameters.Texts[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.ParagraphAlignment);
row.Cells[i].VerticalAlignment = VerticalAlignment.Center;
}
}
protected override void SavePdf(PdfInfo info)
{
var renderer = new PdfDocumentRenderer(true)
{
Document = _document
};
renderer.RenderDocument();
renderer.PdfDocument.Save(info.FileName);
}
}
}

View File

@ -30,6 +30,6 @@ namespace CarServiceContracts.BusinessLogicsContracts
/// Сохранение заказов в файл-Pdf /// Сохранение заказов в файл-Pdf
/// </summary> /// </summary>
/// <param name="model"></param> /// <param name="model"></param>
void SaveOrdersToPdfFile(ReportBindingModel model); void SavePaymentsToPdfFile(ReportBindingModel model);
} }
} }

View File

@ -11,8 +11,10 @@ namespace CarServiceWebApp.Controllers
private readonly IReportLogic _reportLogic; private readonly IReportLogic _reportLogic;
private readonly IWorkLogic _workLogic; private readonly IWorkLogic _workLogic;
private static List<int> SelectedWorks = new(); private static List<int> SelectedWorks = new();
private static ReportBindingModel PaymentsModel = new(); private static ReportBindingModel PaymentsModel = new()
{
FileName = "C:\\Users\\igors\\source\\repos\\ISEbd-21_Melnikov_I.O._CarService\\CarService\\CarServiceWebApp\\Files\\ReportPdf.pdf"
};
public ReportController(IReportLogic reportLogic, IWorkLogic workLogic) public ReportController(IReportLogic reportLogic, IWorkLogic workLogic)
{ {
@ -67,7 +69,8 @@ namespace CarServiceWebApp.Controllers
[HttpPost] [HttpPost]
public IActionResult DateSelection(DateTime dateFrom, DateTime dateTo) public IActionResult DateSelection(DateTime dateFrom, DateTime dateTo)
{ {
PaymentsModel = new() { DateFrom = dateFrom, DateTo = dateTo }; PaymentsModel.DateFrom = dateFrom;
PaymentsModel.DateTo = dateTo;
return Redirect("~/Report/ReportPayments"); return Redirect("~/Report/ReportPayments");
} }
public IActionResult ReportPayments() public IActionResult ReportPayments()
@ -102,6 +105,20 @@ namespace CarServiceWebApp.Controllers
byte[] fileBytes = System.IO.File.ReadAllBytes(filePath); byte[] fileBytes = System.IO.File.ReadAllBytes(filePath);
return File(fileBytes, "application/force-download", fileName);
}
public IActionResult SaveToPdf()
{
_reportLogic.SavePaymentsToPdfFile(PaymentsModel);
return Redirect("~/Report/DownLoadPdf");
}
public IActionResult DownLoadPdf()
{
string filePath = "C:\\Users\\igors\\source\\repos\\ISEbd-21_Melnikov_I.O._CarService\\CarService\\CarServiceWebApp\\Files\\ReportPdf.pdf";
string fileName = "Отчет.pdf";
byte[] fileBytes = System.IO.File.ReadAllBytes(filePath);
return File(fileBytes, "application/force-download", fileName); return File(fileBytes, "application/force-download", fileName);
} }
} }

Binary file not shown.

View File

@ -29,6 +29,7 @@ builder.Services.AddTransient<IReportLogic, ReportLogic>();
builder.Services.AddTransient<AbstractSaveToWord, SaveToWord>(); builder.Services.AddTransient<AbstractSaveToWord, SaveToWord>();
builder.Services.AddTransient<AbstractSaveToExcel, SaveToExcel>(); builder.Services.AddTransient<AbstractSaveToExcel, SaveToExcel>();
builder.Services.AddTransient<AbstractSaveToPdf, SaveToPdf>();
var app = builder.Build(); var app = builder.Build();

View File

@ -57,4 +57,5 @@
{ {
<p>Нет оплат за указанный период</p> <p>Нет оплат за указанный период</p>
} }
<div><center><a asp-controller="Report" asp-action="SaveToPdf" class="btn btn-primary">Сохранить в пдф</a></center></div>
</div> </div>