我参考中文帮助中的代码给一个横向的页面设置页眉页脚, 执行后,页脚和页眉分别跑到了左侧和右侧, 代码如下:
- Code: Select all
static void Main(string[] args)
{
//加载一个测试文档
PdfDocument existingPdf = new PdfDocument();
existingPdf.LoadFromFile(@"C:\Users\Administrator\Desktop\test加页眉页脚.pdf");
//调用DrawHeader方法在现有文档添加页眉
DrawHeader(existingPdf);
//调用DrawFooter方法在现有文档添加页脚
DrawFooter(existingPdf);
//保存文档
existingPdf.SaveToFile(@"C:\Users\Administrator\Desktop\test加页眉页脚_ok.pdf");
}
//在页面上方空白部位绘制页眉
static void DrawHeader(PdfDocument doc)
{
//获取页面大小
SizeF pageSize = doc.Pages[0].Size;
//声明x,y两个float型变量
float x = 90;
float y = 20;
for (int i = 0; i < doc.Pages.Count; i++)
{
//在每一页的指定位置绘制图片
PdfImage headerImage = PdfImage.FromFile(@"C:\Users\Administrator\Desktop\logo.png");
float width = headerImage.Width / 3;
float height = headerImage.Height / 3;
doc.Pages[i].Canvas.DrawImage(headerImage, x, y, width, height);
//在每一页的指定位置绘制横线
PdfPen pen = new PdfPen(PdfBrushes.Gray, 0.5f);
doc.Pages[i].Canvas.DrawLine(pen, x, y + height + 2, pageSize.Width - x, y + height + 2);
}
}
//在页面下方空白部位绘制页脚
static void DrawFooter(PdfDocument doc)
{
//获取页面大小
SizeF pageSize = doc.Pages[0].Size;
//声明x,y两个float型变量
float x = 90;
float y = pageSize.Height - 72;
for (int i = 0; i < doc.Pages.Count; i++)
{
//在每一页的指定位置绘制横线
PdfPen pen = new PdfPen(PdfBrushes.Gray, 0.5f);
doc.Pages[i].Canvas.DrawLine(pen, x, y, pageSize.Width - x, y);
//在每一页的指定位置绘制文字
PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("黑体", 10f, FontStyle.Bold), true);
//在每一页的指定位置当前页码和总页码
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(doc.Pages[i].Canvas);
}
}
最终期待的效果如下: