在Word文檔中,我們可以通過添加頁眉、頁腳的方式來豐富文檔內容。添加頁眉、頁腳時,可以添加時間、日期、文檔標題,文檔引用信息、頁碼、內容解釋、圖片/LOGO等多種圖文信息。同時也可根據需要調整文字或圖片在頁眉、頁腳處的位置。因此,本文將介紹如何在C#中使用社區版控件Free Spire. Doc for .NET來添加頁眉、頁腳以及頁碼方法。
提示:下載安裝該組件後注意在你的VS項目程序中引用dll文件(該dll文件可在安裝文件下的Bin文件夾中獲取)
一、添加文本、圖片頁眉
using Spire.Doc;
using Spire.Doc.Documents;
using System.Drawing;
using Spire.Doc.Fields;
namespace AddHeaderAndFooter
{
class Program
{
static void Main(string[] args)
{
//創建一個Document類實例,添加section和Paragraph
Document document = new Document(@"C:\Users\Administrator\Desktop\Test.docx");
Section sec = document.AddSection();
Paragraph para = sec.AddParagraph();
//聲明一個HeaderFooter類對象,添加頁眉、頁腳
HeaderFooter header = sec.HeadersFooters.Header;
Paragraph headerPara = header.AddParagraph();
HeaderFooter footer = sec.HeadersFooters.Footer;
Paragraph footerPara = footer.AddParagraph();
//添加圖片和文本到頁眉,並設置文本格式
DocPicture headerImage = headerPara.AppendPicture(Image.FromFile(@"C:\Users\Administrator\Desktop\2.jpg"));
TextRange TR = headerPara.AppendText("The Word Trade Organization, WTO");
TR.CharacterFormat.FontName = "Andalus";
TR.CharacterFormat.FontSize = 12;
TR.CharacterFormat.TextColor = Color.Green;
TR.CharacterFormat.Bold = false;
headerImage.TextWrappingType = TextWrappingType.Right;
//添加文本到頁腳,並設置格式
TR = footerPara.AppendText("The World Trade Organization is an intergovernmental organization that regulates international trade.The WTO officially commenced on 1 January 1995 under the Marrakesh Agreement, signed by 123 nations on 15 April 1994, replacing the General Agreement on Tariffs and Trade, which commenced in 1948. ");
TR.CharacterFormat.Bold = false;
TR.CharacterFormat.FontSize = 9;
//保存文檔並運行該文檔
document.SaveToFile("圖文頁眉.docx", FileFormat.Docx);
System.Diagnostics.Process.Start("圖文頁眉.docx");
}
}
}
運行結果:
PS:對於需要設置圖片在文字中的位置的情況,我們可以通過TextWrappingStyle或TextWrappingTpye 來實現。
Eg:
headerImage.TextWrappingStyle = TextWrappingStyle.Through;
或
headerImage.TextWrappingType = TextWrappingType.Right;
二、添加頁碼
添加頁碼,我們可以選擇在頁眉或者頁腳處添加。
using Spire.Doc;
using Spire.Doc.Documents;
namespace AddPageNumber_Doc
{
class Program
{
static void Main(string[] args)
{
//實例化一個Document類,添加section和Paragraph
Document document = new Document();
Section sec = document.AddSection();
Paragraph para = sec.AddParagraph();
//添加文本到paragraph,設置BreakType爲分頁
para.AppendText("第1頁");
para.AppendBreak(BreakType.PageBreak);
para.AppendText("第2頁");
//創建一個HeaderFooter類實例,添加頁腳
HeaderFooter footer = sec.HeadersFooters.Footer;
Paragraph footerPara = footer.AddParagraph();
//添加字段類型爲頁碼,添加當前頁、分隔線以及總頁數
footerPara.AppendField("頁碼", FieldType.FieldPage);
footerPara.AppendText(" / ");
footerPara.AppendField("總頁數", FieldType.FieldNumPages);
footerPara.Format.HorizontalAlignment = HorizontalAlignment.Right;
//保存文檔
document.SaveToFile("添加頁碼.docx", FileFormat.Docx);
System.Diagnostics.Process.Start("添加頁碼.docx");
}
}
}
運行結果:
以上是本文關於Word如何添加頁眉、頁腳和頁碼的代碼操作。如果喜歡,歡迎轉載(轉載請註明出處)
感謝瀏覽!