页脚添加效果:
2.给现有PDF文档添加页眉页脚
【C#】
using Spire.Pdf;
using Spire.Pdf.AutomaticFields;
using Spire.Pdf.Graphics;
using System;
using System.Drawing;
namespace PdfHeader
{
class Program
{
static void Main(string[] args)
{
//加载一个测试文档
PdfDocument existingPdf = new PdfDocument();
existingPdf.LoadFromFile("Test.pdf");
//调用DrawHeader方法在现有文档添加页眉
DrawHeader(existingPdf);
//调用DrawFooter方法在现有文档添加页脚
DrawFooter(existingPdf);
//保存并打开文档
existingPdf.SaveToFile("output.pdf");
System.Diagnostics.Process.Start("output.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("logo.png");
float width = headerImage.Width / 7;
float height = headerImage.Height / 7;
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);
//在每一页的指定位置绘制文字
y = y + 5;
PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("黑体", 10f, FontStyle.Bold), true);
PdfStringFormat format = new PdfStringFormat(PdfTextAlignment.Left);
String footerText = " Websiten https://www.easck.com//在每一页的指定位置当前页码和总页码
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);
}
}
}
}











