Commit 7df94e62 authored by Alexey Goikolov's avatar Alexey Goikolov

Добавил библиотеку PdfSharp. Написал экшен для генерации файлов pdf.Добавил…

Добавил библиотеку PdfSharp. Написал экшен для генерации файлов pdf.Добавил ссылку на скачивание pdf в представление Index контроллера Users
parent 827c744c
using System.Linq;
using System.IO;
using System.Linq;
using Lesson49.Models;
using Lesson49.Models.Data;
using Microsoft.AspNetCore.Mvc;
using PdfSharpCore.Drawing;
using PdfSharpCore.Drawing.Layout;
using PdfSharpCore.Pdf;
namespace Lesson49.Controllers
{
......@@ -32,5 +37,44 @@ namespace Lesson49.Controllers
_db.SaveChanges();
return RedirectToAction("Index");
}
// public IActionResult GetPdf(int id)
// {
// User user = _db.Users.FirstOrDefault(u => u.Id == id);
// PdfDocument document = new PdfDocument();
// PdfPage page = document.Pages.Add();
// PdfGraphics graphics = page.Graphics;
// PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 20);
// graphics.DrawString(user.ToString(), font, PdfBrushes.Black, new PointF(0, 0));
// MemoryStream stream = new MemoryStream();
// document.Save(stream);
// stream.Position = 0;
// FileStreamResult fileStreamResult = new FileStreamResult(stream, "application/pdf");
// fileStreamResult.FileDownloadName = "MyFirstPDF.pdf";
// return fileStreamResult;
//
// }
public IActionResult GetPdf(int id)
{
User user = _db.Users.FirstOrDefault(u => u.Id == id);
PdfDocument document = new PdfDocument();
document.Info.Title = "My second Pdf";
PdfPage page = document.AddPage();
XGraphics gfx = XGraphics.FromPdfPage(page);
XFont font = new XFont("Verdana", 20, XFontStyle.BoldItalic);
XTextFormatter formatter = new XTextFormatter(gfx);
XRect rect = new XRect(10, 10, 540, 700);
gfx.DrawRectangle(XBrushes.Aquamarine, rect);
formatter.DrawString(user.ToString(), font, XBrushes.Black,
rect, XStringFormats.TopLeft);
MemoryStream stream = new MemoryStream();
document.Save(stream);
stream.Position = 0;
FileStreamResult fileStreamResult = new FileStreamResult(stream, "application/pdf");
fileStreamResult.FileDownloadName = $"{user.Name}.pdf";
return fileStreamResult;
}
}
}
\ No newline at end of file
......@@ -11,6 +11,7 @@
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="3.1.13" />
<PackageReference Include="PdfSharpCore" Version="1.2.16" />
</ItemGroup>
<ItemGroup>
......
......@@ -9,7 +9,7 @@
<a asp-action="Create" asp-controller="Users">Добавить пользователя</a>
@foreach (var user in Model)
{
<p>Имя - @user.Name</p>
<p>Имя - @user.Name | <a asp-action="GetPdf" asp-controller="Users" asp-route-id="@user.Id">Скачать в PDF</a></p>
<p>Фамилия - @user.Surname</p>
<p>Возраст - @user.Age</p>
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment