using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using Spire.Pdf;
using Spire.Pdf.AutomaticFields;
using Spire.Pdf.Graphics;
using Spire.Pdf.Grid;
namespace PDFCreator
{
class PDF
{
public static void Create()
{
PdfDocument doc = CreateDocument("出现信息", "标题:张三");
PdfFontBase fontInfo = new PdfTrueTypeFont(new Font("宋体", 9f, FontStyle.Regular), true);
PdfFontBase fontSmallTitle = new PdfTrueTypeFont(new Font("宋体", 9f, FontStyle.Bold), true);
PdfFontBase fontBigTitle = new PdfTrueTypeFont(new Font("宋体", 15f, FontStyle.Bold), true);
List<PdfGrid> listGrids = new List<PdfGrid>();
Dictionary<PdfGridCell, PdfTextAlignment> dictCellAlignment = new Dictionary<PdfGridCell, PdfTextAlignment>();
Random random = new Random();
for (int num = 0; num < 10; num++)
{
PdfGrid grid = CreateGrid(7);
listGrids.Add(grid);
List<PdfGridRow> listRows = new List<PdfGridRow>();
PdfGridRow row1 = grid.Rows.Add();
PdfGridRow row2 = grid.Rows.Add();
listRows.Add(row1);
listRows.Add(row2);
row1.Cells[0].ColumnSpan = 2; //从0行合并行单元格
row1.Cells[0].RowSpan = 2; //从0行合并行单元格
PdfGridCellTextAndStyleList lst = new PdfGridCellTextAndStyleList();
PdfGridCellTextAndStyle pdfText = new PdfGridCellTextAndStyle();
pdfText.Text = "张三";
pdfText.Font = fontInfo;
pdfText.StringFormat = new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Top);
lst.List.Add(pdfText);
Image img = Properties.Resources.logo;
PdfGridCellTextAndStyle pdfImg = new PdfGridCellTextAndStyle();
pdfImg.Image = PdfImage.FromImage(img);
pdfImg.ImageNewline = true;
pdfImg.ImageSize = new SizeF(60, 45);
pdfImg.StringFormat = new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Bottom);
lst.List.Add(pdfImg);
row1.Cells[0].Value = lst;
row1.Cells[2].ColumnSpan = 5;
row1.Cells[2].Value = "籍贯:广东深圳";
row1.Cells[2].Style.Font = fontInfo;
dictCellAlignment[row1.Cells[2]] = PdfTextAlignment.Left;
row2.Cells[2].ColumnSpan = 3;
row2.Cells[2].Value = "性别:男";
row2.Cells[2].Style.Font = fontInfo;
row2.Cells[5].ColumnSpan = 2;
row2.Cells[5].Value = "年龄:30";
row2.Cells[5].Style.Font = fontInfo;
PdfGridRow rowHead = grid.Rows.Add();
rowHead.Cells[0].Value = "序号";
rowHead.Cells[1].Value = "地址";
rowHead.Cells[2].Value = "到达时间";
rowHead.Cells[3].Value = "到达方式";
rowHead.Cells[4].Value = "离开时间";
rowHead.Cells[5].Value = "离开方式";
rowHead.Cells[6].Value = "合计天数";
rowHead.Style.BackgroundBrush = PdfBrushes.Gainsboro;
rowHead.Style.Font = fontInfo;
listRows.Add(rowHead);
List<object[]> listValue = new List<object[]>();
int count = random.Next(25, 100);
for (int i = 0; i < count; i++)
{
listValue.Add(new object[] { i.ToString(), "广州", "2020-12-16", "高铁", "2020-12-18", "城际", "3" });
}
foreach (var objInfo in listValue)
{
PdfGridRow rowInfo = grid.Rows.Add();
listRows.Add(rowInfo);
rowInfo.Style.Font = fontInfo;
for (int i = 0; i < rowInfo.Cells.Count; i++)
{
rowInfo.Cells[i].Value = objInfo[i];
}
}
SetBorderStyle(listRows, dictCellAlignment);
}
AutoDrawGrid(doc, listGrids);
string fileName = DateTime.Now.ToString("HHmmssfff") + ".pdf";
//保存文档
doc.SaveToFile(fileName);
Process.Start(fileName);
}
#region PDF文档生成
/// <summary>
/// 创建PDF文档
/// </summary>
static PdfDocument CreateDocument(string title, string info, bool isLandscape = false)
{
PdfDocument doc = new PdfDocument();
doc.PageSettings.Margins.All = 0; //设置边距为0
doc.PageSettings.Size = PdfPageSize.A4; //指定页面大小
doc.PageSettings.Orientation = isLandscape ? PdfPageOrientation.Landscape : PdfPageOrientation.Portrait; //指定是横向显示还是纵向
PdfPageBase page = doc.Pages.Add();
doc.Pages.RemoveAt(0);//删除第一页,因为有水印
//将页边距设置为0
doc.PageSettings.Margins = new PdfMargins(0);
//创建PdfMargins对象,指定期望设置的页边距
PdfMargins margins = new PdfMargins(40, 60, 40, 60);
//在文档模板的顶部和底部应用页眉页脚模板
doc.Template.Top = CreateHeaderTemplate(doc, margins, title, info);
doc.Template.Bottom = CreateFooterTemplate(doc, margins);
//在文档模板的左右部分应用空白模板
doc.Template.Left = new PdfPageTemplateElement(margins.Left, doc.PageSettings.Size.Height);
doc.Template.Right = new PdfPageTemplateElement(margins.Right, doc.PageSettings.Size.Height);
return doc;
}
/// <summary>
/// 创建页眉模板
/// </summary>
static PdfPageTemplateElement CreateHeaderTemplate(PdfDocument doc, PdfMargins margins, string title, string info)
{
//获取页面大小
SizeF pageSize = doc.PageSettings.Size;
//创建PdfPageTemplateElement对象headerSpace,即作页眉模板
PdfPageTemplateElement headerSpace = new PdfPageTemplateElement(pageSize.Width, margins.Top);
headerSpace.Foreground = false;
//声明x,y两个float型变量
float x = margins.Left;
float y = 0;
//在headerSpace中绘制图片
PdfImage headerImage = PdfImage.FromImage(Properties.Resources.logo);
float width = headerImage.Width / 3;
float height = headerImage.Height / 3;
headerSpace.Graphics.DrawImage(headerImage, x, margins.Top - height - 2, width, height);
PdfTrueTypeFont fontTitle = new PdfTrueTypeFont(new Font("宋体", 20f, FontStyle.Regular), true);
PdfStringFormat formatTitle = new PdfStringFormat(PdfTextAlignment.Center, PdfVerticalAlignment.Middle);
RectangleF rectTitle = new RectangleF(0, 0 + 10, headerSpace.Width, headerSpace.Height);
headerSpace.Graphics.DrawString(title, fontTitle, PdfBrushes.Black, rectTitle, formatTitle);
PdfTrueTypeFont fontInfo = new PdfTrueTypeFont(new Font("宋体", 6f, FontStyle.Regular), true);
PdfStringFormat formatInfo = new PdfStringFormat(PdfTextAlignment.Left, PdfVerticalAlignment.Bottom);
SizeF sizeInfo = fontInfo.MeasureString(info);
RectangleF rectInfo = new RectangleF(headerSpace.Width - x - sizeInfo.Width - 10, y, sizeInfo.Width, headerSpace.Height - 5);
headerSpace.Graphics.DrawString(info, fontInfo, PdfBrushes.Black, rectInfo, formatInfo);
//在headerSpace中绘制线段
PdfPen pen = new PdfPen(PdfBrushes.Black, 0.5f);
headerSpace.Graphics.DrawLine(pen, 20, y + margins.Top - 2, pageSize.Width - 20, y + margins.Top - 2);
//返回headerSpace
return headerSpace;
}
/// <summary>
/// 创建页脚模板
/// </summary>
static PdfPageTemplateElement CreateFooterTemplate(PdfDocument doc, PdfMargins margins)
{
//获取页面大小
SizeF pageSize = doc.PageSettings.Size;
//创建PdfPageTemplateElement对象footerSpace,即页脚模板
PdfPageTemplateElement footerSpace = new PdfPageTemplateElement(pageSize.Width, margins.Bottom);
footerSpace.Foreground = false;
//声明x,y两个float型变量
float x = margins.Left;
float y = 0;
//在footerSpace中绘制线段
PdfPen pen = new PdfPen(PdfBrushes.Black, 0.5f);
footerSpace.Graphics.DrawLine(pen, 20, y, pageSize.Width - 20, y);
//在footerSpace中绘制文字
y = y + 5;
PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("黑体", 10f, FontStyle.Bold), true);
PdfStringFormat format = new PdfStringFormat(PdfTextAlignment.Left);
String footerText = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
footerSpace.Graphics.DrawString(footerText, font, PdfBrushes.Black, x, y, format);
//在footerSpace中绘制当前页码和总页码
PdfPageNumberField number = new PdfPageNumberField();
PdfPageCountField count = new PdfPageCountField();
PdfCompositeField compositeField = new PdfCompositeField(font, PdfBrushes.Black, "{0}/{1}", number, count);
compositeField.StringFormat = new PdfStringFormat(PdfTextAlignment.Right, PdfVerticalAlignment.Top);
SizeF size = font.MeasureString(compositeField.Text);
compositeField.Bounds = new RectangleF(pageSize.Width - x - size.Width, y, size.Width, size.Height);
compositeField.Draw(footerSpace.Graphics);
//返回footerSpace
return footerSpace;
}
/// <summary>
/// 创建设定列数的表格
/// </summary>
static PdfGrid CreateGrid(int columnCount)
{
//创建一个PdfGrid对象
PdfGrid grid = new PdfGrid();
grid.Style.CellPadding = new PdfPaddings(1, 1, 1, 1);
grid.Style.Font = new PdfTrueTypeFont(new Font("宋体", 9f, FontStyle.Regular), true);
grid.Columns.Add(columnCount);
return grid;
}
/// <summary>
/// 在表格中添加一个指定行高的空白行(没有边框)
/// </summary>
static void AddSpaceRow(PdfGrid grid, int height = 10)
{
//添加空白行
PdfGridRow rowEnd = grid.Rows.Add();
rowEnd.Height = height;
rowEnd.Cells[0].ColumnSpan = rowEnd.Cells.Count;
PdfBorders borderEnd = new PdfBorders();
borderEnd.All = new PdfPen(PdfBrushes.Transparent);
rowEnd.Cells[0].Style.Borders = borderEnd;
}
/// <summary>
/// 对表格中的每个行设置边框(外边框粗,内边框细,所有单元格居中)
/// </summary>
static void SetBorderStyle(List<PdfGridRow> listRows)
{
SetBorderStyle(listRows, new Dictionary<PdfGridCell, PdfTextAlignment>());
}
/// <summary>
/// 对表格中的每个行设置边框(外边框粗,内边框细,除指定外所有单元格居中)
/// </summary>
static void SetBorderStyle(List<PdfGridRow> listRows, Dictionary<PdfGridCell, PdfTextAlignment> dictCellAlignment)
{
//设置数据表边框
PdfBorders borders = new PdfBorders();
borders.All = new PdfPen(Color.Black, 0.1f);
PdfPen penOuter = new PdfPen(Color.Black, 1f);
PdfPen penInter = new PdfPen(Color.Gray, 0.1f);
for (int rowIndex = 0; rowIndex < listRows.Count; rowIndex++)
{
int colCount = listRows[rowIndex].Cells.Count;
for (int colIndex = 0; colIndex < colCount; colIndex++)
{
PdfGridCell pdfGridCell = listRows[rowIndex].Cells[colIndex];
pdfGridCell.StringFormat = new PdfStringFormat(dictCellAlignment.ContainsKey(pdfGridCell) ? dictCellAlignment[pdfGridCell] : PdfTextAlignment.Center, PdfVerticalAlignment.Middle);
pdfGridCell.Style.Borders.Top = rowIndex == 0 ? penOuter : penInter;
pdfGridCell.Style.Borders.Right = (colIndex == colCount - 1) | (colIndex + pdfGridCell.ColumnSpan == colCount) ? penOuter : penInter;
pdfGridCell.Style.Borders.Bottom = (rowIndex == listRows.Count - 1) | (rowIndex + pdfGridCell.RowSpan == listRows.Count) ? penOuter : penInter;
pdfGridCell.Style.Borders.Left = colIndex == 0 ? penOuter : penInter;
}
}
}
/// <summary>
/// 直接将每个表格单独画入单个的页中
/// </summary>
static void DirectDrawGrid(PdfDocument doc, List<PdfGrid> listGrid, float gridMargin = 15)
{
float firstMargin = 5;
foreach (PdfGrid grid in listGrid)
{
PdfPageBase page = doc.Pages.Add();
grid.Draw(page, new PointF(0, firstMargin));
}
}
/// <summary>
/// 将表格尝试画入页中,为了消除表格数据自动换行带来的行高的计算
/// </summary>
static void DockGrid(PdfDocument doc, PdfGrid grid)
{
int count = doc.Pages.Count;
PdfPageBase page1 = doc.Pages.Add();
grid.Draw(page1, new PointF(0, 0)); //只有将Grid画入文档中才能获取正确的行的高度
int nowCount = doc.Pages.Count;
for (int index = count; index < nowCount; index++)
{
doc.Pages.RemoveAt(count);
}
}
/// <summary>
/// 自动计算行高,合理的将表格依次画入页中
/// </summary>
static void AutoDrawGrid(PdfDocument doc, List<PdfGrid> listGrid, float gridMargin = 15)
{
float pageHeight = PageDocHeight(doc);
float firstMargin = 5;
float currBound = firstMargin;
PdfPageBase page = doc.Pages.Add();
foreach (PdfGrid grid in listGrid)
{
DockGrid(doc, grid); //获取正确的行的高度
float height = GridHeight(grid);
if (height > pageHeight)
{
if (currBound > pageHeight / 2)
{
page = doc.Pages.Add();
currBound = firstMargin;
}
grid.Draw(page, new PointF(0, currBound));
page = doc.Pages[doc.Pages.Count - 1];
currBound = GetOtherHeight(pageHeight, currBound, grid) + gridMargin;
}
else if (height + currBound > pageHeight)
{
page = doc.Pages.Add();
currBound = firstMargin;
grid.Draw(page, new PointF(0, currBound));
currBound += height + gridMargin;
}
else
{
grid.Draw(page, new PointF(0, currBound));
currBound += height + gridMargin;
}
}
}
/// <summary>
/// 获取该表格的总高度
/// </summary>
static float GridHeight(PdfGrid grid)
{
float currBound = 0f;
foreach (var row in grid.Rows)
{
currBound += row.Height + 0f; //获取Height后Grid就不会自动换行了
}
return currBound;
}
/// <summary>
/// 获取在该高度画入该表格时当前页剩余的高度
/// </summary>
static float GetOtherHeight(float pageHeight, float currHeight, PdfGrid grid)
{
float currBound = 0f;
float otherBound = 0f;
foreach (var row in grid.Rows)
{
currBound += row.Height;
if (currBound > pageHeight - currHeight)
{
otherBound += row.Height;
if (otherBound > pageHeight)
{
otherBound = row.Height;
}
}
}
return otherBound;
}
/// <summary>
/// 获取该文档除页眉和页脚外的总高度
/// </summary>
static float PageDocHeight(PdfDocument doc)
{
float pageHeight = doc.PageSettings.Height - doc.Template.Top.Height - doc.Template.Bottom.Height;
return pageHeight;
}
/// <summary>
/// 根据数据点生成Chart图
/// </summary>
static Image DrawChart(string xName, string yName, Size size, List<PointF> listPoint)
{
System.Windows.Forms.DataVisualization.Charting.Chart chartUse = new System.Windows.Forms.DataVisualization.Charting.Chart();
System.Windows.Forms.DataVisualization.Charting.ChartArea chartAreaUse = new System.Windows.Forms.DataVisualization.Charting.ChartArea();
System.Windows.Forms.DataVisualization.Charting.Series seriesUse = new System.Windows.Forms.DataVisualization.Charting.Series();
System.Windows.Forms.DataVisualization.Charting.DataPoint dataPointTemp = new System.Windows.Forms.DataVisualization.Charting.DataPoint(0D, 0D);
System.Windows.Forms.DataVisualization.Charting.Title titleTemp = new System.Windows.Forms.DataVisualization.Charting.Title();
chartUse.BackColor = System.Drawing.Color.Ivory;
chartAreaUse.AxisX.ArrowStyle = System.Windows.Forms.DataVisualization.Charting.AxisArrowStyle.Triangle;
chartAreaUse.AxisX.Enabled = System.Windows.Forms.DataVisualization.Charting.AxisEnabled.True;
chartAreaUse.AxisX.IntervalAutoMode = System.Windows.Forms.DataVisualization.Charting.IntervalAutoMode.VariableCount;
chartAreaUse.AxisX.MajorGrid.Enabled = false;
chartAreaUse.AxisX.Title = xName;
chartAreaUse.AxisX.TitleAlignment = System.Drawing.StringAlignment.Far;
chartAreaUse.AxisY.ArrowStyle = System.Windows.Forms.DataVisualization.Charting.AxisArrowStyle.Triangle;
chartAreaUse.AxisY.MajorGrid.Enabled = false;
chartAreaUse.AxisY.TextOrientation = System.Windows.Forms.DataVisualization.Charting.TextOrientation.Stacked;
chartAreaUse.AxisY.Title = yName;
chartAreaUse.AxisY.TitleAlignment = System.Drawing.StringAlignment.Far;
chartAreaUse.BackColor = System.Drawing.Color.Transparent;
chartAreaUse.Name = "ChartArea1";
chartUse.ChartAreas.Add(chartAreaUse);
chartUse.Name = "chart1";
chartUse.Palette = System.Windows.Forms.DataVisualization.Charting.ChartColorPalette.None;
seriesUse.ChartArea = "ChartArea1";
seriesUse.IsValueShownAsLabel = true;
seriesUse.IsXValueIndexed = false;
seriesUse.MarkerSize = 2;
seriesUse.Name = "Series1";
seriesUse.Points.Add(dataPointTemp);
seriesUse.SmartLabelStyle.CalloutLineAnchorCapStyle = System.Windows.Forms.DataVisualization.Charting.LineAnchorCapStyle.None;
seriesUse.SmartLabelStyle.CalloutStyle = System.Windows.Forms.DataVisualization.Charting.LabelCalloutStyle.Box;
chartUse.Series.Add(seriesUse);
chartUse.Size = size;
chartUse.TabIndex = 7;
chartUse.Text = "chart1";
titleTemp.Name = "Title1";
chartUse.Titles.Add(titleTemp);
seriesUse.Points.Clear();
foreach (var point in listPoint)
{
seriesUse.Points.AddXY(point.X, point.Y);
}
Bitmap bitmap = new Bitmap(chartUse.Width, chartUse.Height);
chartUse.DrawToBitmap(bitmap, new Rectangle(0, 0, bitmap.Width, bitmap.Height));
return bitmap;
}
#endregion
}
}