Aspose.Words如何为Word文档插入页码

作者:控件中国网   出处:控件中国网   2016-08-12 10:21:56   阅读:46

Aspose.Words是一款完全利用API操作Word文档的.NET和Java控件,该产品支持大多数Microsoft Words软件可以实现的功能,而且电脑上还不需要安装Microsoft Words软件,在使用Word文档时经常需要为文档添加页眉页脚,而页脚里很多时候都需要添加页码,那么如何利用Aspose.Words为word文档添加页码呢,控件提供DocumentBuilder类,利用该类的builder.InsertField()方法可以为Word文档插入页码,具体的用法可以参考下面的代码:
           Document doc = new Document("1.doc");
           DocumentBuilder builder = new DocumentBuilder(doc);
           InsertHeaderFooter(builder.CurrentSection, HeaderFooterType.FooterPrimary);
           InsertHeaderFooter(builder.CurrentSection, HeaderFooterType.HeaderFirst);
           builder.MoveToHeaderFooter(HeaderFooterType.FooterPrimary);
 
            //Set start number
            builder.PageSetup.PageStartingNumber = 1;
            //Page numbers will be restarted for each section
            builder.PageSetup.RestartPageNumbering = false;
            builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;
            //Insert PAGE field into the header
            builder.MoveToHeaderFooter(HeaderFooterType.FooterPrimary);
            builder.Write("页码:");
            builder.InsertField("PAGE", string.Empty);
            builder.MoveToDocumentEnd();
            //Insert page break
            builder.InsertBreak(BreakType.PageBreak);
            //Insert section break
            builder.InsertBreak(BreakType.SectionBreakNewPage);
 
            doc.Save("PageOut.docx");
private static void InsertHeaderFooter(Section sect, HeaderFooterType headerType)
        {
            HeaderFooter header = sect.HeadersFooters[headerType];
 
            if (header == null)
            {
                // There is no header of the specified type in the current section, create it.
                header = new HeaderFooter(sect.Document, headerType);
                sect.HeadersFooters.Add(header);
            }
        }
Copyright© 2006-2015 ComponentCN.com all rights reserved.重庆磐岩科技有限公司(控件中国网) 版权所有 渝ICP备12000264号 法律顾问:元炳律师事务所
客服软件
live chat