PdfSharp
/// <summary>
/// PdfSharp 创建一个简单的PDF
/// </summary>
public static async Task ExportPDFAsync(string title = null)
{
// 创建PDF文档
PdfDocument document = new PdfDocument();
document.Info.Title = "PdfSharp Table Example";
// 添加页面
PdfPage page = document.AddPage();
XGraphics gfx = XGraphics.FromPdfPage(page);
// 设置字体
XFont font = new XFont("Verdana", 10);
// 设置表格数据
string[,] tableData = new string[,]
{
{ "Name", "Age", "City","Name", "Age", "City","Na111111111111111111111111me", "Age", "City","Name", "Age", "City" },
{"Alice", "30", "New York", "Alice", "30", "New York", "Alice", "30", "New York", "Alice", "30", "New York"},
{"Bob", "25", "Los Angeles", "Bob", "25", "Los Angeles", "Bob", "25", "Los Angeles", "Bob", "25", "Los Angeles"},
{"Charlie", "35", "Chicago", "Charlie", "35", "Chicago", "Charlie", "35", "Chicago", "Charlie", "35", "Chicago"}
};
// 表格的起始位置和单元格大小
double startX = 20;
double startY = 50;
double cellWidth = 550 / 12;
double cellHeight = 30;
// 绘制表格
for (int row = 0; row < tableData.GetLength(0); row++)
{
for (int col = 0; col < tableData.GetLength(1); col++)
{
// 绘制文本
gfx.DrawString(tableData[row, col], font, XBrushes.Black, new XRect(startX + col * cellWidth, startY + row * cellHeight, cellWidth, cellHeight), XStringFormats.Center);
}
gfx.DrawLine(XPens.LightGray, startX, startY + (row + 1) * cellHeight, startX + 550, startY + (row + 1) * cellHeight); // 只绘制底部
}
var dialog = new SaveFileDialog()
{
Filter = "(*.pdf)|*.pdf|(*.pdf)|*.pdf",
Title = title ?? "导出".Localize(),
InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments),
};
if (dialog.ShowDialog() != true) return;
document.Save(dialog.FileName);
Process.Start(dialog.FileName); // 打开生成的PDF文件
}