c# 数据保存为PDF(二) (Aspose pdf篇)
文章目录
- 前言
- 关于Aspose PDF
- 使用Aspose.Pdf
- 常用的命名空间和类库
- 1 创建简单的PDF文档
- 2 美化PDF样式
- 2.1 创建测试数据
- 2.2 项目头部样式
- 2.3 全部代码
- 小结
- 附录参考
前言
项目中需要将数据导出存为PDF格式,试了一下Aspose组件,仅以此记录一下使用感受。
关于Aspose PDF
Aspose于2002年3月在澳大利亚悉尼创建,一直致力于成为全球最大的.NET组件提供商。
Aspose.Pdf是一个PDF文档创建组件,可以帮助用户无需使用Adobe Acrobat即可读写和操作PDF文件。Aspose.Pdf功能丰富:有PDF文档压缩选项,表格创建与操作,插入图表、图像功能,丰富的超链接功能,图章和水印任务,扩展的安全性组件以及自定义字体处理。
Aspose.PDF for .NET
支持流行的文件格式,例如PDF,XFA,TXT,HTML,PCL,XPS,EPUB,TEX和图像格式,并允许直接通过API或XML模板创建PDF文档,并且可以创建表单或管理文档中嵌入的表单字段。
使用Aspose.Pdf
Aspose的组件是收费的,但是网上也能收到很多破解版本,且去掉页眉和水印之类的限制。
常用的命名空间和类库
使用Aspose.Pdf
组件时,常用的命名空间和类库如下,可根据自己的实际需求增添:
命名空间:
using Aspose.Pdf;
using Aspose.Pdf.Devices;
using Aspose.Pdf.Text;
using Aspose.Cells;
类 | 说明 |
Aspose.Pdf.Document | PDF文档 |
Aspose.Pdf.Page | PDF页面 |
Aspose.Pdf.HeaderFooter | 页眉页脚 |
Aspose.Pdf.MarginInfo | 页边距 |
Aspose.Pdf.Table | 表格 |
Aspose.Pdf.Row | 行 |
Aspose.Pdf.TextFragment | 文本段落 |
1 创建简单的PDF文档
创建一个带页眉页脚的PDF文档Document
。首先是创建HeaderFooter
页眉页脚,然后在页眉页脚中插入Table
表格,在表格的行中单元中填充TextFragment
文本段落。Page
页面内容也是一样的套路。
/// <summary>
/// 创建简单PDF
/// </summary>
public static void CreatePdf1()
{//Evaluation Only. Created with Aspose.PDF. Copyright 2002-2019 Aspose Pty Lt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yZT5wSkpjQndRdnYxV1NxZ1kyOHFJYUFKSysvTFFVWWRrQ2x5THE2RUNLU0xDQ3dMNkEwMkJFTnh5L3JzQ1V3UExXbjV2bTl0TDRQRXE1aFAzY2s0WnhEejFiK1JIWTBuQkh1SEhBY01TL1BSeEJES0NGbWg1QVFZRTlrT0FxSzM5NVBSWmJRSGowOUNGTElVUzBMdnRmVkp5cUhjblJvU3dPQnVqT1oyeDc4WFE9PC9TaWduYXR1cmU+CjwvTGljZW5zZT4=")));
//创建PDF文档对象
Aspose.Pdf.Document doc = new Document();
//添加页面
Page page = doc.Pages.Add();
//设置页边距
MarginInfo marginInfo = new MarginInfo();
marginInfo.Top = 90;
marginInfo.Bottom = 50;
marginInfo.Left = 50;
marginInfo.Right = 50;
//更新页面的页边距
page.PageInfo.Margin = marginInfo;
//页眉
HeaderFooter hfFirst = new HeaderFooter();
page.Header = hfFirst;
hfFirst.Margin.Left = 50;
hfFirst.Margin.Right = 50;
// 在页眉处写入文本段落
TextFragment t1 = new TextFragment("report title 页眉");
t1.TextState.Font = FontRepository.FindFont("Arial");
t1.TextState.FontSize = 16;
t1.TextState.ForegroundColor = Aspose.Pdf.Color.Black;
t1.TextState.FontStyle = FontStyles.Bold;
t1.TextState.HorizontalAlignment = Aspose.Pdf.HorizontalAlignment.Center;
t1.TextState.LineSpacing = 5f;
hfFirst.Paragraphs.Add(t1);
TextFragment t2 = new TextFragment("Report_Name");
t2.TextState.Font = FontRepository.FindFont("Arial");
t2.TextState.ForegroundColor = Aspose.Pdf.Color.Black;
t2.TextState.HorizontalAlignment = Aspose.Pdf.HorizontalAlignment.Center;
t2.TextState.LineSpacing = 5f;
t2.TextState.FontSize = 12;
hfFirst.Paragraphs.Add(t2);
// 为每一页创建页脚
HeaderFooter hfFoot = new HeaderFooter();
page.Footer = hfFoot;
hfFoot.Margin.Left = 50;
hfFoot.Margin.Right = 50;
// 页脚文字段落设置,包含生成日期 名称 和 页码
TextFragment t3 = new TextFragment(DateTime.Now.ToString("yyyy/MM/dd HH:mm"));
TextFragment t4 = new TextFragment("唠嗑一夏 ");
TextFragment t5 = new TextFragment("Page $p of $P");
// 实例化表格对象
Table tab2 = new Table();
// 在页脚中添加表格
hfFoot.Paragraphs.Add(tab2);
// 设置表格宽度 使用空格隔开
tab2.ColumnWidths = "165 172 165";
// 创建行,并在行中添加单元格
Aspose.Pdf.Row row3 = tab2.Rows.Add();
row3.Cells.Add();
row3.Cells.Add();
row3.Cells.Add();
//设置单元格的对齐方式
row3.Cells[0].Alignment = Aspose.Pdf.HorizontalAlignment.Left;
row3.Cells[1].Alignment = Aspose.Pdf.HorizontalAlignment.Center;
row3.Cells[2].Alignment = Aspose.Pdf.HorizontalAlignment.Right;
//使用文本段落填充单元格内容
row3.Cells[0].Paragraphs.Add(t3);
row3.Cells[1].Paragraphs.Add(t4);
row3.Cells[2].Paragraphs.Add(t5);
//再次创建表格对象
Table table = new Table();
//设置列宽和边距
table.ColumnWidths = "33% 33% 34%";
table.DefaultCellPadding = new MarginInfo();
table.DefaultCellPadding.Top = 10;
table.DefaultCellPadding.Bottom = 10;
// 在页面中插入表格
page.Paragraphs.Add(table);
// 设置表格默认的边框
table.DefaultCellBorder = new BorderInfo(BorderSide.All, 0.1f);
// 设置表格边框
table.Border = new BorderInfo(BorderSide.All, 1f);
table.RepeatingRowsCount = 1;
// 在表中创建行,在行中添加单元格
Aspose.Pdf.Row row1 = table.Rows.Add();
row1.Cells.Add("col1");
row1.Cells.Add("col2");
row1.Cells.Add("col3");
const string CRLF = "\r\n";
for (int i = 0; i <= 30; i++)
{
//创建新行
Aspose.Pdf.Row row = table.Rows.Add();
//换行
row.IsRowBroken = true;
for (int c = 0; c <= 2; c++)
{
Aspose.Pdf.Cell c1;
if (c == 2)
c1 = row.Cells.Add("Aspose.Total for Java is a compilation of every Java component offered by Aspose. It is compiled on a" + CRLF + "daily basis to ensure it contains the most up to date versions of each of our Java components. " + CRLF + "daily basis to ensure it contains the most up to date versions of each of our Java components. " + CRLF + "Using Aspose.Total for Java developers can create a wide range of applications.");
else
c1 = row.Cells.Add("item1" + c);
c1.Margin = new MarginInfo();
c1.Margin.Left = 30;
c1.Margin.Top = 10;
c1.Margin.Bottom = 10;
}
}
string dataDir = @"D:\Demo.pdf";
//保存
doc.Save(dataDir);
}
效果图:
2 美化PDF样式
根据下面(Spire pdf创建的PDF)图片中的样式,用Aspose.Pdf实现。
原文在:c# 数据保存为PDF (spire pdf篇)https://blog.csdn.net/weixin_40314351/article/details/130406659?spm=1001.2014.3001.5501
2.1 创建测试数据
使用DataTable存储我们自己随机产生的100 (行)* 5(列)的数据,该数据仅作演示使用哈。
/// <summary>
/// 数据表格
/// </summary>
/// <returns></returns>
private static DataTable CreateData()
{
DataTable dt = new DataTable();
DataColumn col1 = new DataColumn("Num", typeof(string));
DataColumn col2 = new DataColumn("Name", typeof(string));
DataColumn col3 = new DataColumn("Val", typeof(string));
DataColumn col4 = new DataColumn("Des", typeof(string));
DataColumn col5 = new DataColumn("Set", typeof(string));
dt.Columns.Add(col1);
dt.Columns.Add(col2);
dt.Columns.Add(col3);
dt.Columns.Add(col4);
dt.Columns.Add(col5);
Random random = new Random();
List<string> nameList = new List<string>
{
"A", "BB", "CCC", "D",
"E", "F", "G","H","II",
"JJ", "LL", "M"
};
List<string> tempList = new List<string>
{
"dsd", "sdfdgvre", "Hello", "Gilrs",
"Today", "YYYY", "dfgre","GSD","fdgfer",
"Wesd", "DLG", "fsdahfi;o"
};
for (int i = 0; i < 10; i++)
{
for (int j = 0; j < 10; j++)
{
DataRow dr = dt.NewRow();
dr[0] = "KK" + i.ToString("d2") + "." + j.ToString("d2");
dr[1] = nameList[j];
if (j % 3 == 0)
{
dr[2] = random.NextDouble().ToString("f3");
}
else
{
dr[2] = i * j - random.Next(0, 30);
}
dr[3] = tempList[j];
dr[4] = random.NextDouble().ToString("f2");
//添加新行
dt.Rows.Add(dr);
}
}
return dt;
}
2.2 项目头部样式
设计一下项目头部样式,这里是使用单独函数实现的,后面调用就可以了。
实际上是一个表格,表格中有5行,设置行高、单元格内容以及单元格样式,就可以实现了。最后将表格添加到Page的段落中即可。
/// <summary>
/// 项目的头
/// </summary>
/// <param name="page"></param>
private static void AddPDFProgramTitle(Page page)
{
Table tab1 = new Table();
tab1.ColumnWidths = "80% 20%";
Aspose.Pdf.Row row1 = tab1.Rows.Add();
row1.Cells.Add("Parameter Settings Report(Program)");
row1.Cells[0].DefaultCellTextState.FontSize = 14;
row1.Cells.Add(DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"));
row1.Cells[1].DefaultCellTextState.FontSize = 11;
row1.MinRowHeight = 35;
row1.DefaultCellTextState.FontStyle = FontStyles.Bold;
Aspose.Pdf.Row emptyRow1 = tab1.Rows.Add();
emptyRow1.Cells.Add(" ");
emptyRow1.Cells.Add(" ");
emptyRow1.MinRowHeight = 1;
emptyRow1.DefaultCellTextState.FontSize = 7;
emptyRow1.DefaultCellBorder = new BorderInfo(BorderSide.Top, 0.1f);
Aspose.Pdf.Row row2 = tab1.Rows.Add();
row2.Cells.Add("Program (Drive Selected / Connected):");
row2.Cells.Add("");
row2.BackgroundColor = Color.LightCyan;
row2.MinRowHeight = 20;
row2.Cells[0].DefaultCellTextState.FontSize = 12;
row2.DefaultCellTextState.FontStyle = FontStyles.Bold;
Aspose.Pdf.Row row3 = tab1.Rows.Add();
row3.Cells.Add("Drive Type / Model:");
row3.Cells.Add("");
// row3.DefaultCellBorder = new BorderInfo(BorderSide.Bottom, 0.1f);
row3.BackgroundColor = Color.LightCyan;
row3.MinRowHeight = 20;
row3.Cells[0].DefaultCellTextState.FontSize = 13;
Aspose.Pdf.Row emptyRow2 = tab1.Rows.Add();
emptyRow2.Cells.Add("");
emptyRow2.Cells.Add("");
emptyRow2.MinRowHeight = 2;
emptyRow2.DefaultCellBorder = new BorderInfo(BorderSide.Bottom, 0.1f);
Aspose.Pdf.Row row4 = tab1.Rows.Add();
row4.Cells.Add("Project:");
row4.Cells.Add("");
// row4.DefaultCellBorder = new BorderInfo(BorderSide.Bottom, 0.1f);
row4.MinRowHeight = 30;
row4.Cells[0].DefaultCellTextState.FontSize = 12;
row4.Cells[0].DefaultCellTextState.FontStyle = FontStyles.Bold;
Aspose.Pdf.Row emptyRow3 = tab1.Rows.Add();
emptyRow3.Cells.Add("");
emptyRow3.Cells.Add("");
emptyRow3.MinRowHeight = 1;
emptyRow3.DefaultCellBorder = new BorderInfo(BorderSide.Bottom, 0.1f);
Aspose.Pdf.Row row5 = tab1.Rows.Add();
row5.Cells.Add("Information");
row5.Cells.Add("");
row5.MinRowHeight = 80;
row5.Cells[0].DefaultCellTextState.FontSize = 11;
row5.DefaultCellTextState.FontStyle = FontStyles.Bold;
row5.VerticalAlignment = VerticalAlignment.Top;
row5.DefaultCellPadding = new MarginInfo(0,0,0,10);
page.Paragraphs.Add(tab1);
}
2.3 全部代码
将测试数据,项目头部信息,以及数据内容全部整合在一起,生成PDF。
/// <summary>
/// 制作Aspose PDF
/// </summary>
/// <param name="binary"></param>
/// <returns></returns>
public static void MakeAsposePDF()
{
//获取测试数据
DataTable dataTable = CreateData();
//去除水印
new Aspose.Pdf.License().SetLicense(new MemoryStream(Convert.FromBase64String("PExpY2Vuc2U+CiAgPERhdGE+CiAgICA8TGljZW5zZWRUbz5TdXpob3UgQXVuYm94IFNvZnR3YXJlIENvLiwgTHRkLjwvTGljZW5zZWRUbz4KICAgIDxFbWFpbFRvPnNhbGVzQGF1bnRlYy5jb208L0VtYWlsVG8+CiAgICA8TGljZW5zZVR5cGU+RGV2ZWxvcGVyIE9FTTwvTGljZW5zZVR5cGU+CiAgICA8TGljZW5zZU5vdGU+TGltaXRlZCB0byAxIGRldmVsb3BlciwgdW5saW1pdGVkIHBoeXNpY2FsIGxvY2F0aW9uczwvTGljZW5zZU5vdGU+CiAgICA8T3JkZXJJRD4yMDA2MDIwMTI2MzM8L09yZGVySUQ+CiAgICA8VXNlcklEPjEzNDk3NjAwNjwvVXNlcklEPgogICAgPE9FTT5UaGlzIGlzIGEgcmVkaXN0cmlidXRhYmxlIGxpY2Vuc2U8L09FTT4KICAgIDxQcm9kdWN0cz4KICAgICAgPFByb2R1Y3Q+QXNwb3NlLlRvdGFsIGZvciAuTkVUPC9Qcm9kdWN0PgogICAgPC9Qcm9kdWN0cz4KICAgIDxFZGl0aW9uVHlwZT5FbnRlcnByaXNlPC9FZGl0aW9uVHlwZT4KICAgIDxTZXJpYWxOdW1iZXI+OTM2ZTVmZDEtODY2Mi00YWJmLTk1YmQtYzhkYzBmNTNhZmE2PC9TZXJpYWxOdW1iZXI+CiAgICA8U3Vic2NyaXB0aW9uRXhwaXJ5PjIwMjEwODI3PC9TdWJzY3JpcHRpb25FeHBpcnk+CiAgICA8TGljZW5zZVZlcnNpb24+My4wPC9MaWNlbnNlVmVyc2lvbj4KICAgIDxMaWNlbnNlSW5zdHJ1Y3Rpb25zPmh0dHBzOi8vcHVyY2hhc2UuYXNwb3NlLmNvbS9wb2xpY2llcy91c2UtbGljZW5zZTwvTGljZW5zZUluc3RydWN0aW9ucz4KICA8L0RhdGE+CiAgPFNpZ25hdHVyZT5wSkpjQndRdnYxV1NxZ1kyOHFJYUFKSysvTFFVWWRrQ2x5THE2RUNLU0xDQ3dMNkEwMkJFTnh5L3JzQ1V3UExXbjV2bTl0TDRQRXE1aFAzY2s0WnhEejFiK1JIWTBuQkh1SEhBY01TL1BSeEJES0NGbWg1QVFZRTlrT0FxSzM5NVBSWmJRSGowOUNGTElVUzBMdnRmVkp5cUhjblJvU3dPQnVqT1oyeDc4WFE9PC9TaWduYXR1cmU+CjwvTGljZW5zZT4=")));
Aspose.Pdf.Text.Font font = FontRepository.FindFont("Arial");
//创建文档对象
Aspose.Pdf.Document doc = new Document();
Page page = doc.Pages.Add();
MarginInfo marginInfo = new MarginInfo();
marginInfo.Top = 30;
marginInfo.Bottom = 30;
marginInfo.Left = 20;
marginInfo.Right = 20;
// 设置页面边距
page.PageInfo.Margin = marginInfo;
// 创建页脚
HeaderFooter hfFoot = new HeaderFooter();
// 设置页脚边距
page.Footer = hfFoot;
hfFoot.Margin.Left = 20;
hfFoot.Margin.Right = 20;
// 设置页脚的文本内容
string footerText = "Test for Windows(C) by 唠嗑一夏 Electric Corporation";
TextFragment t3 = new TextFragment(footerText);
TextFragment t5 = new TextFragment("$p/$P");
// 创建表格实例
Table hftable = new Table();
// 在页脚的段落中添加表格
hfFoot.Paragraphs.Add(hftable);
// 设置表格列宽
hftable.ColumnWidths = "90% 10%";
// 创建行
Aspose.Pdf.Row row3 = hftable.Rows.Add();
//行中添加单元格
row3.Cells.Add();
row3.Cells.Add();
// 设置单元格对齐方式
row3.Cells[0].Alignment = Aspose.Pdf.HorizontalAlignment.Left;
row3.Cells[1].Alignment = Aspose.Pdf.HorizontalAlignment.Right;
//单元格段落中填充文本段落
row3.Cells[0].Paragraphs.Add(t3);
row3.Cells[1].Paragraphs.Add(t5);
row3.DefaultCellPadding = new MarginInfo(0, 0, 0, 5);
row3.Border = new BorderInfo(BorderSide.Top, 0.6f, Color.Black);
//添加大标题
AddPDFProgramTitle(page);
//创建内容表格
Table contentTable = new Table();
//设置表的列宽 以百分比
contentTable.ColumnWidths = "30% 15% 40% 15%";
// 页面段落中添加表格
page.Paragraphs.Add(contentTable);
contentTable.RepeatingRowsCount = 1;
// 表格中创建行
Aspose.Pdf.Row row1 = contentTable.Rows.Add();
//设置文本样式
TextState tsTitle = new TextState();
tsTitle.FontSize = 10;
tsTitle.FontStyle = FontStyles.Bold;
tsTitle.Font = font;
row1.Cells.Add(" Parameter");
row1.Cells.Add("Value");
row1.Cells.Add("Information");
row1.Cells.Add("Default Setting");
row1.DefaultCellTextState = tsTitle;
row1.Border = new BorderInfo(BorderSide.All, 0.1f, Color.LightGray);
row1.BackgroundColor = Color.LightCyan;
row1.MinRowHeight = 30;
int count = dataTable.Rows.Count;
string str = "";
string strBak = "";
int j = 0;
//加粗样式
TextState tsBold = new TextState();
tsBold.FontSize = 8;
tsBold.FontStyle = FontStyles.Bold;
tsBold.Font = font;
//正常样式
TextState tsRegular = new TextState();
tsRegular.FontSize = 8;
tsRegular.Font = font;
for (int i = 0; i < count; i++)
{//遍历行
DataRow dataRow = dataTable.Rows[i];
//添加新行
Aspose.Pdf.Row row = contentTable.Rows.Add();
//设置换行
row.IsRowBroken = true;
//设置单元格内边距
row.DefaultCellPadding = new MarginInfo(0, 0, 0, 5);
//截取字符串
strBak = dataRow[0].ToString().Substring(0, 4);
if (strBak != str)
{//绘制组别,添加下划线
str = strBak;
string converStr = strBak;
row.Cells.Add(converStr);
row.Cells[0].DefaultCellTextState = tsBold;
row.Cells[0].VerticalAlignment = VerticalAlignment.Bottom;
row.Cells[0].Border = new BorderInfo(BorderSide.Bottom, 0.1f, Color.Black);
j++;
}
{//绘制组中内容
string tempStr = dataRow[0].ToString() + " " + dataRow[1].ToString();
row.DefaultCellTextState = tsRegular;
row.Cells.Add(tempStr);
row.Cells.Add(dataRow[2].ToString());
row.Cells.Add(dataRow[3].ToString());
row.Cells.Add(dataRow[4].ToString());
}
}
//保存文档
doc.Save(@"D:\Aspose.pdf");
}
效果:
小结
Aspose.Pdf很容易上手,都是面向对象编程,想要什么就创建相应的实体类即可。不过需要自己找破解版的资源,破解版可能也不是当前最新版本。
相比c# 数据保存为PDF (spire pdf篇) Spire.PDF
还是Aspose.Pdf
更简单容易上手。
附录参考
1、c# 数据保存为PDF (spire pdf篇)https://blog.csdn.net/weixin_40314351/article/details/130406659?spm=1001.2014.3001.5501
2、Aspose.PDF for .NET相关案例使用Demo https://www.evget.com/product/565/resource
3、Aspose.Pdf官网 https://releases.aspose.com/pdf/