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);
         }
     }
 }

 (本文完)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章