在.NET Core 中生成PDF文档的方法

  比如我们需要ASP.NET Core 中需要通过PDF来进行某些简单的报表开发,随着这并不难,但还是会手忙脚乱的去搜索一些资料,那么恭喜您,这篇帖子会帮助到您,我们就不会再去浪费一些宝贵的时间。

  在本文中我们将要使用DinkToPDF来处理我们在.NET Core Web 程序中进行构建PDF文档!就现在我们不多说,直接开始有趣的部分。

前言

  您可以通过创建PDF文档在我的仓库中,获取源代码,欢迎给个免费的Star...

  现在我们创建一个.NET Core 3.0 项目,至于是mvc、Api、这些我并不在意。创建项目后直接Nuget安装DinkToPDF。随后您需要下载我的代码仓库中的“NativeLibrary”文件夹,在其中,我们将找到两个文件32bit和64bit,因此我们需要为操作系统选择合适的库。我们将从64位文件夹中选择文件。

  最后,我们需要启动该库,并且IOC DinkToPDF。

<code>public void ConfigureServices(IServiceCollection services)
{
var context = new CustomAssemblyLoadContext();
context.LoadUnmanagedLibrary(Path.Combine(Directory.GetCurrentDirectory(), "libwkhtmltox.dll"));

services.AddSingleton(typeof(IConverter), new SynchronizedConverter(new PdfTools()));
services.AddControllers();
}/<code>

建立实体

在真实情况的项目中,我们可以从数据库中收集数据或从其他API接收数据。但是为了简单起见,我们将从本地存储中收集PDF文档的数据。随后,我们将创建一个HTML模板并将其存储在PDF文档中。

<code> public class Employee
{
public string Name { get; set; }
public string LastName { get; set; }
public int Age { get; set; }
public string Gender { get; set; }
}/<code>

再随后,我们要创建一个新的文件夹Services和里面两类文件 DataServices.cs 和 TemplateGenerator.cs 。完整的结构应如下所示:

<code>public class DataServices
{
public static List<employee> GetAllEmployess() =>
new List<employee>
{
new Employee { Name="Hao Zi Zhang", LastName="Turner", Age=35, Gender="Male"},
new Employee { Name="Yu Chen", LastName="Markus", Age=22, Gender="Female"},
new Employee { Name="Jian Zhi Chu", LastName="Martins", Age=40, Gender="Male"},
new Employee { Name="ElderJames", LastName="Packner", Age=30, Gender="Female"},
new Employee { Name="BlaZui", LastName="Doe", Age=45, Gender="Male"}
};
}/<employee>/<employee>/<code>

其中添加服务中返回了某些数据,用于模拟服务。我们要生成一个HTML模板,因此我们需要修改 TemplateGenerator.cs 文件:

<code>public class TempleGenertor
{
public static string GetHTMLString()
{
var employees = DataServices.GetAllEmployess();

var sb = new StringBuilder();
sb.Append(@"




This is the generated PDF report!!!


<table>

Name
LastName
Age
Gender
");

foreach (var emp in employees)
{
sb.AppendFormat(@"
{0}
{1}
{2}
{3}
", emp.Name, emp.LastName, emp.Age, emp.Gender);
}
sb.Append(@"
/<table>

");

return sb.ToString();
}
}/<code>

如果想要指定css样式,则可以创建某些文件夹,随后在API通过服务器路径来抉择配置。

<code>.header {
text-align: center;
color: green;
padding-bottom: 35px;
}

table {
width: 80%;
border-collapse: collapse;
}

td, th {
border: 1px solid gray;
padding: 15px;
font-size: 22px;
text-align: center;
}

table th {
background-color: green;
color: white;
}/<code>

  就是这样,我们有用于HTML创建的HTML模板。现在,我们可以继续执行Controller逻辑。

<code> [Route("api/PdfCreator")]
[ApiController]
public class PdfCreatorController : ControllerBase
{
private IConverter _converter;

public PdfCreatorController(IConverter converter)
{
_converter = converter;
}

[HttpGet]
public IActionResult CreatePDF()
{
var globalSettings = new GlobalSettings
{
ColorMode = ColorMode.Color,
Orientation = Orientation.Portrait,
PaperSize = PaperKind.A4,
Margins = new MarginSettings { Top = 10 },
DocumentTitle = "PDF Report"

};

var objectSettings = new ObjectSettings
{
PagesCount = true,
HtmlContent = TempleGenertor.GetHTMLString(),
WebSettings = { DefaultEncoding = "utf-8", UserStyleSheet = Path.Combine(Directory.GetCurrentDirectory(), "assets", "style.css") },
HeaderSettings = { FontName = "Arial", FontSize = 9, Right = "Page [page] of [toPage]", Line = true },
FooterSettings = { FontName = "Arial", FontSize = 9, Line = true, Center = "Report Footer" }
};

var pdf = new HtmlToPdfDocument()
{
GlobalSettings = globalSettings,
Objects = { objectSettings }
};

var file = _converter.Convert(pdf);
return File(file, "application/pdf");
}
}/<code>

代码说明

在上面的代码中,我们首先通过使用 IConverter 接口将注册的 Converter 与依赖注入注入到构造函数中。然后,我们创建两个对象 globalSettings , objectSettings 并将它们用作 HtmlToPdfDcoument 属性中的配置。


现在让我们来说说 GlobalSettings 和 ObjectSettings 类。

关于GlobalSettings类

它括了PDF文档的整体配置属性。我们仅使用其中的几个属性来设置颜色模式,方向,纸张尺寸,文档标题等…但它还有还多属性。

关于ObjectSettings类

ObjectSettings由相关的PDF文档的内容的属性。因此,我们可以配置页面计数器的可见性,页眉和页脚的格式,文档的正文内容(HtmlContent属性)或的Web设置。

HtmlContent属性是此类的非常重要的属性。它包含我们生成的HTML模板,并显示PDF文档的主体。

WebSettings也非常重要,尤其是如果我们有一个外部CSS文件来进行样式设置时。在此属性中,我们可以配置文档的编码并提供CSS文件的路径。如果我们检查此属性,我们将发现更多可以配置的设置,例如PDF文档的背景,文字大小 等等..

启动项目

通过路由定位到我们的API中,重定向PDF打印界面。

在.NET Core 中生成PDF文档的方法

 一切看起来都是那么完美,就这样我们就可以轻松的在ASP.NET Core中构建PDF文档并且还可以完美适配相关逻辑和某些文档设置!!


分享到:


相關文章: