【愚公系列】2022年10月 .NET CORE工具案例-.NET Core使用QuestPDF

2023-11-04 09:59

本文主要是介绍【愚公系列】2022年10月 .NET CORE工具案例-.NET Core使用QuestPDF,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

文章目录

  • 前言
  • 一、.NET Core使用QuestPDF
    • 1.Nuget安装包
    • 2.官方案例
    • 3.发票案例
      • 3.1 定义模型类InvoiceModel
      • 3.2 InvoiceDocumentDataSource数据生成
      • 3.3 InvoiceDocument 发票文档
      • 3.4 生成发票


前言

QuestPDF是一个用于生成PDF文档的open-source.NET库。

它提供了一个布局引擎,设计时考虑了完整的分页支持。文档由许多简单元素组成(例如边框、背景、图像、文本、填充、表格、网格等),这些元素组合在一起以创建更复杂的结构。这样,作为一名开发人员,您可以理解每个元素的行为,并满怀信心地使用它们。此外,文档及其所有元素都支持分页功能。例如,一个元素可以移动到下一页(如果没有足够的空间),甚至可以像表的行一样在页面之间拆分。

与其他库不同,它不依赖HTML-to-PDF转换,在许多情况下,这种转换不可靠。相反,它实现了自己的布局引擎,该引擎经过优化以覆盖所有paging-related需求。

github文档地址:https://github.com/QuestPDF/QuestPDF
在这里插入图片描述

API文档地址:https://www.questpdf.com/api-reference/index
在这里插入图片描述

一、.NET Core使用QuestPDF

1.Nuget安装包

Install-Package QuestPDF

在这里插入图片描述

2.官方案例

using QuestPDF.Fluent;
using QuestPDF.Helpers;
using QuestPDF.Infrastructure;// code in your main method
Document.Create(container =>
{container.Page(page =>{page.Size(PageSizes.A4);page.Margin(2, Unit.Centimetre);page.PageColor(Colors.White);page.DefaultTextStyle(x => x.FontSize(20));page.Header().Text("Hello PDF!").SemiBold().FontSize(36).FontColor(Colors.Blue.Medium);page.Content().PaddingVertical(1, Unit.Centimetre).Column(x =>{x.Spacing(20);x.Item().Text(Placeholders.LoremIpsum());x.Item().Image(Placeholders.Image(200, 100));});page.Footer().AlignCenter().Text(x =>{x.Span("Page ");x.CurrentPageNumber();});});
})
.GeneratePdf("hello.pdf");

在这里插入图片描述

3.发票案例

3.1 定义模型类InvoiceModel

//发票类
public class InvoiceModel
{//发票号public int InvoiceNumber { get; set; }//发布日期public DateTime IssueDate { get; set; }//到期日public DateTime DueDate { get; set; }//卖方地址public Address SellerAddress { get; set; }//顾客地址public Address CustomerAddress { get; set; }//订单项目public List<OrderItem> Items { get; set; }//评论public string Comments { get; set; }
}
//订单类
public class OrderItem
{//名称public string Name { get; set; }//价格public decimal Price { get; set; }//数量public int Quantity { get; set; }
}
//地址类
public class Address
{//公司地址public string CompanyName { get; set; }//街道public string Street { get; set; }//城市public string City { get; set; }//状态public string State { get; set; }//邮件public object Email { get; set; }//电话public string Phone { get; set; }
}

3.2 InvoiceDocumentDataSource数据生成

public static class InvoiceDocumentDataSource
{private static Random Random = new Random();public static InvoiceModel GetInvoiceDetails(){var items = Enumerable.Range(1, 25).Select(i => GenerateRandomOrderItem()).ToList();return new InvoiceModel{InvoiceNumber = Random.Next(1_000, 10_000),IssueDate = DateTime.Now,DueDate = DateTime.Now + TimeSpan.FromDays(14),SellerAddress = GenerateRandomAddress(),CustomerAddress = GenerateRandomAddress(),Items = items,Comments = Placeholders.Paragraph()};}private static OrderItem GenerateRandomOrderItem(){return new OrderItem{Name = Placeholders.Label(),Price = (decimal) Math.Round(Random.NextDouble() * 100, 2),Quantity = Random.Next(1, 10)};}private static Address GenerateRandomAddress(){return new Address{CompanyName = Placeholders.Name(),Street = Placeholders.Label(),City = Placeholders.Label(),State = Placeholders.Label(),Email = Placeholders.Email(),Phone = Placeholders.PhoneNumber() };}
}

3.3 InvoiceDocument 发票文档

using System.Linq;
using QuestPDF.Drawing;
using QuestPDF.Fluent;
using QuestPDF.Helpers;
using QuestPDF.Infrastructure;namespace QuestPDF.ExampleInvoice
{public class InvoiceDocument : IDocument{public InvoiceModel Model { get; }public InvoiceDocument(InvoiceModel model){Model = model;}//定义文档的元数据(创建日期,修改日期,作者等)public DocumentMetadata GetMetadata() => DocumentMetadata.Default;//发票模板public void Compose(IDocumentContainer container){container.Page(page =>{//页面间距page.Margin(50);//页面头page.Header().Element(ComposeHeader);// 页面内容page.Content().Element(ComposeContent);//1 / 2page.Footer().AlignCenter().Text(text =>{//当前页数text.CurrentPageNumber();//分割text.Span(" / ");//总页数text.TotalPages();});});}//发票头void ComposeHeader(IContainer container){container.Row(row =>{//其实row相当于列,Column相当于行row.RelativeItem().Column(Column =>{Column.Item().Text($"Invoice #{Model.InvoiceNumber}").FontSize(20).SemiBold().FontColor(Colors.Blue.Medium);Column.Item().Text(text =>{text.Span("Issue date: ").SemiBold();text.Span($"{Model.IssueDate:d}");});Column.Item().Text(text =>{text.Span("Due date: ").SemiBold();text.Span($"{Model.DueDate:d}");});});//宽100,高50的图片row.ConstantItem(100).Height(50).Placeholder();});}//发票体void ComposeContent(IContainer container){//其实row相当于列,Column相当于行container.PaddingVertical(40).Column(column => {column.Spacing(20);//交易方信息column.Item().Row(row =>{row.RelativeItem().Component(new AddressComponent("From", Model.SellerAddress));row.ConstantItem(50);row.RelativeItem().Component(new AddressComponent("For", Model.CustomerAddress));});//表格column.Item().Element(ComposeTable);//价格汇总var totalPrice = Model.Items.Sum(x => x.Price * x.Quantity);column.Item().PaddingRight(5).AlignRight().Text($"Grand total: {totalPrice}$").SemiBold();if (!string.IsNullOrWhiteSpace(Model.Comments))column.Item().PaddingTop(25).Element(ComposeComments);});}//发票表格void ComposeTable(IContainer container){var headerStyle = TextStyle.Default.SemiBold();container.Table(table =>{table.ColumnsDefinition(columns =>{columns.ConstantColumn(25);columns.RelativeColumn(3);columns.RelativeColumn();columns.RelativeColumn();columns.RelativeColumn();});table.Header(header =>{header.Cell().Text("#");header.Cell().Text("Product").Style(headerStyle);header.Cell().AlignRight().Text("Unit price").Style(headerStyle);header.Cell().AlignRight().Text("Quantity").Style(headerStyle);header.Cell().AlignRight().Text("Total").Style(headerStyle);header.Cell().ColumnSpan(5).PaddingTop(5).BorderBottom(1).BorderColor(Colors.Black);});foreach (var item in Model.Items){table.Cell().Element(CellStyle).Text(Model.Items.IndexOf(item) + 1);table.Cell().Element(CellStyle).Text(item.Name);table.Cell().Element(CellStyle).AlignRight().Text($"{item.Price}$");table.Cell().Element(CellStyle).AlignRight().Text(item.Quantity);table.Cell().Element(CellStyle).AlignRight().Text($"{item.Price * item.Quantity}$");static IContainer CellStyle(IContainer container) => container.BorderBottom(1).BorderColor(Colors.Grey.Lighten2).PaddingVertical(5);}});}//发票评论void ComposeComments(IContainer container){container.ShowEntire().Background(Colors.Grey.Lighten3).Padding(10).Column(column => {column.Spacing(5);column.Item().Text("Comments").FontSize(14).SemiBold();column.Item().Text(Model.Comments);});}}//地址组件public class AddressComponent : IComponent{private string Title { get; }private Address Address { get; }public AddressComponent(string title, Address address){Title = title;Address = address;}public void Compose(IContainer container){container.ShowEntire().Column(column =>{column.Spacing(2);//公司方向(销售和客户)column.Item().Text(Title).SemiBold();//画线column.Item().PaddingBottom(5).LineHorizontal(1); //地址信息column.Item().Text(Address.CompanyName);column.Item().Text(Address.Street);column.Item().Text($"{Address.City}, {Address.State}");column.Item().Text(Address.Email);column.Item().Text(Address.Phone);});}}
}

3.4 生成发票

class Program
{static void Main(string[] args){var model = InvoiceDocumentDataSource.GetInvoiceDetails();var document = new InvoiceDocument(model);// 生成PDF文件并在默认查看器中显示GenerateDocumentAndShow(document);//或者nuget安装QuestPDF Previewer预览器并尝试文档的设计//在每次代码更改后,无需重新编译即可实时执行//document.ShowInPreviewer();}static void GenerateDocumentAndShow(InvoiceDocument document){const string filePath = "invoice.pdf";document.GeneratePdf(filePath);//执行进程查看发票var process = new Process{StartInfo = new ProcessStartInfo(filePath){UseShellExecute = true}};process.Start();}
}

在这里插入图片描述

这篇关于【愚公系列】2022年10月 .NET CORE工具案例-.NET Core使用QuestPDF的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/344984

相关文章

使用Python和OpenCV库实现实时颜色识别系统

《使用Python和OpenCV库实现实时颜色识别系统》:本文主要介绍使用Python和OpenCV库实现的实时颜色识别系统,这个系统能够通过摄像头捕捉视频流,并在视频中指定区域内识别主要颜色(红... 目录一、引言二、系统概述三、代码解析1. 导入库2. 颜色识别函数3. 主程序循环四、HSV色彩空间详解

SQLite3命令行工具最佳实践指南

《SQLite3命令行工具最佳实践指南》SQLite3是轻量级嵌入式数据库,无需服务器支持,具备ACID事务与跨平台特性,适用于小型项目和学习,sqlite3.exe作为命令行工具,支持SQL执行、数... 目录1. SQLite3简介和特点2. sqlite3.exe使用概述2.1 sqlite3.exe

Windows下C++使用SQLitede的操作过程

《Windows下C++使用SQLitede的操作过程》本文介绍了Windows下C++使用SQLite的安装配置、CppSQLite库封装优势、核心功能(如数据库连接、事务管理)、跨平台支持及性能优... 目录Windows下C++使用SQLite1、安装2、代码示例CppSQLite:C++轻松操作SQ

Python常用命令提示符使用方法详解

《Python常用命令提示符使用方法详解》在学习python的过程中,我们需要用到命令提示符(CMD)进行环境的配置,:本文主要介绍Python常用命令提示符使用方法的相关资料,文中通过代码介绍的... 目录一、python环境基础命令【Windows】1、检查Python是否安装2、 查看Python的安

Python并行处理实战之如何使用ProcessPoolExecutor加速计算

《Python并行处理实战之如何使用ProcessPoolExecutor加速计算》Python提供了多种并行处理的方式,其中concurrent.futures模块的ProcessPoolExecu... 目录简介完整代码示例代码解释1. 导入必要的模块2. 定义处理函数3. 主函数4. 生成数字列表5.

Python中help()和dir()函数的使用

《Python中help()和dir()函数的使用》我们经常需要查看某个对象(如模块、类、函数等)的属性和方法,Python提供了两个内置函数help()和dir(),它们可以帮助我们快速了解代... 目录1. 引言2. help() 函数2.1 作用2.2 使用方法2.3 示例(1) 查看内置函数的帮助(

Linux脚本(shell)的使用方式

《Linux脚本(shell)的使用方式》:本文主要介绍Linux脚本(shell)的使用方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录概述语法详解数学运算表达式Shell变量变量分类环境变量Shell内部变量自定义变量:定义、赋值自定义变量:引用、修改、删

基于Python实现一个Windows Tree命令工具

《基于Python实现一个WindowsTree命令工具》今天想要在Windows平台的CMD命令终端窗口中使用像Linux下的tree命令,打印一下目录结构层级树,然而还真有tree命令,但是发现... 目录引言实现代码使用说明可用选项示例用法功能特点添加到环境变量方法一:创建批处理文件并添加到PATH1

Java使用HttpClient实现图片下载与本地保存功能

《Java使用HttpClient实现图片下载与本地保存功能》在当今数字化时代,网络资源的获取与处理已成为软件开发中的常见需求,其中,图片作为网络上最常见的资源之一,其下载与保存功能在许多应用场景中都... 目录引言一、Apache HttpClient简介二、技术栈与环境准备三、实现图片下载与保存功能1.

Python中使用uv创建环境及原理举例详解

《Python中使用uv创建环境及原理举例详解》uv是Astral团队开发的高性能Python工具,整合包管理、虚拟环境、Python版本控制等功能,:本文主要介绍Python中使用uv创建环境及... 目录一、uv工具简介核心特点:二、安装uv1. 通过pip安装2. 通过脚本安装验证安装:配置镜像源(可