C#添加PDF文档页眉

 在现代电子文档中,页眉是一种对文档载体特定位置区域位置的描述,在此位置上可以插入时间、图形、文字等来传达文档的一些附加信息。我们知道,PDF是一种不太易于编辑的文档,若是想要在PDF文档中添加页眉该怎么来操作呢?这里分享一个在C#中来实现PDF添加页眉的方法(这里使用了免费版组件Free Spire.PDF for .NET)。(本文转载自博客http://www.cnblogs.com/Yesi/p/6248466.html

目标效果示例图:


 using System;
 using Spire.Pdf;
 using System.Drawing;
 using Spire.Pdf.Graphics;
 
 namespace PDF添加页眉
 {
     class Program
     {
         static void Main(string[] args)
         {
             PdfDocument doc = new PdfDocument();
 
             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;
 
             SetDocumentTemplate(doc, PdfPageSize.A4, margin);
             PdfPageBase page = doc.Pages.Add();
             doc.Pages.Add();
 
             doc.SaveToFile("页眉.pdf");
             System.Diagnostics.Process.Start("页眉.pdf");
         }
 
         static void SetDocumentTemplate(PdfDocument doc, SizeF pageSize, PdfMargins margin)
         {
             PdfPageTemplateElement topSpace = new PdfPageTemplateElement(pageSize.Width, margin.Top);
             topSpace.Foreground = true;
             doc.Template.Top = topSpace;
            
             PdfTrueTypeFont font1 = new PdfTrueTypeFont(new Font("宋体", 15f), true);
             PdfStringFormat format = new PdfStringFormat(PdfTextAlignment.Right);
             String  Text = "PDF文本页眉";
             float y = 0;
             float x = PdfPageSize.A4.Width;
             topSpace.Graphics.DrawString(Text, font1, PdfBrushes.PaleVioletRed, x, y, format);
             
             PdfImage headerImage = PdfImage.FromFile(@"C:\Users\Administrator\Pictures\under_construction.jpg");
             float width = headerImage.Width;
             float height = headerImage.Height;
             PointF pageLeftTop = new PointF(0, 0);
             topSpace.Graphics.DrawImage(headerImage, 0, 0, width / 2, height / 2);
         }
     }
 }

 (本文完)

猜你喜欢

转载自miaonly.iteye.com/blog/2404320