在PDF文件的阅读和使用中,PDF页眉一般都需要设置一些相同的信息,如公司Logo、公司名字、作者、时间、标题等信息,也可以包含图标或者图像。
Spire.PDF for .NET是一款功能强大的PDF文件处理类控件,可以帮助开发人员快速为PDF文件添加和设置页眉,可以通过控件提供的API快速为PDF文件添加文本或者图片形式的页面,并且对文本格式以及图片大小等都可以进行有效的控制,具体如何使用可以参考下面的详细代码:
static void Main(string[] args)
{
//create new PDF document
PdfDocument doc = new PdfDocument();
//set margin
PdfUnitConvertor unitCvtr = new PdfUnitConvertor();
PdfMargins margin = new PdfMargins();
margin.Top = unitCvtr.ConvertUnits(2.54f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point);
margin.Bottom = margin.Top;
margin.Left = unitCvtr.ConvertUnits(4.17f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point);
margin.Right = margin.Left;
//apply template in PDF document
SetDocumentTemplate(doc, PdfPageSize.A4, margin);
//add two pages in PDF
PdfPageBase page = doc.Pages.Add();
doc.Pages.Add();
doc.SaveToFile("header.pdf");
System.Diagnostics.Process.Start("header.pdf");
}
static void SetDocumentTemplate(PdfDocument doc, SizeF pageSize, PdfMargins margin)
{
//set a top page template
PdfPageTemplateElement topSpace = new PdfPageTemplateElement(pageSize.Width, margin.Top);
topSpace.Foreground = true;
doc.Template.Top = topSpace;
//draw text header in template
PdfTrueTypeFont font1 = new PdfTrueTypeFont(new Font("Trebuchet MS", 14f, FontStyle.Italic));
PdfStringFormat format = new PdfStringFormat(PdfTextAlignment.Right);
String label = "This is a PDF text header";
SizeF size = font1.MeasureString(label, format);
float y = 0;
float x = PdfPageSize.A4.Width;
topSpace.Graphics.DrawString(label, font1, PdfBrushes.PaleVioletRed, x,y, format);
//drew an image header with custom size in template
PdfImage headerImage = PdfImage.FromFile(@"logo.png");
float width = headerImage.Width;
float height = headerImage.Height;
PointF pageLeftTop = new PointF(0 , 0);
topSpace.Graphics.DrawImage(headerImage,0,0,width/2,height/2);
}