在word工具栏里,我们通常会设置页眉,页脚,页码来对word文档进行排版。该文将详细介绍如何使用c#为word文档添加页眉,页脚和页码。
第一部分
如果word文档包含许多页,我们可以在页眉页脚处添加页码。该页码可显示当前页数, 总页数。我们以在页脚处添加页码为例:
c#
document document = new document();
section sec = document.addsection();
paragraph para = sec.addparagraph();
para.appendtext("page 1");
para.appendbreak(breaktype.pagebreak);
para.appendtext("page 2");
headerfooter footer = sec.headersfooters.footer;
paragraph footerpara = footer.addparagraph();
footerpara.appendfield("页码", fieldtype.fieldpage);
footerpara.appendtext(" of ");
footerpara.appendfield("总页数", fieldtype.fieldnumpages);
footerpara.format.horizontalalignment = horizontalalignment.right;
document.savetofile("添加页码.docx", fileformat.docx);
vb.net
dim document as document = new document
dim sec as section = document.addsection
dim para as paragraph = sec.addparagraph
para.appendtext("page 1")
para.appendbreak(breaktype.pagebreak)
para.appendtext("page 2")
dim footer as headerfooter = sec.headersfooters.footer
dim footerpara as paragraph = footer.addparagraph
footerpara.appendfield("页码", fieldtype.fieldpage)
footerpara.appendtext(" of ")
footerpara.appendfield("总页数", fieldtype.fieldnumpages)
footerpara.format.horizontalalignment = horizontalalignment.right
document.savetofile("添加页码.docx", fileformat.docx)
页码效果图:
第二部分
c# 为word文档添加图文混排的页面页脚。
图片和文字都能被添加为页眉或页脚,我们用c#来为word文档添加图文混排的页眉为例。
c#
document document = new document();
section sec = document.addsection();
paragraph para = sec.addparagraph();
para.appendtext("page 1");
headerfooter header = sec.headersfooters.header;
paragraph headerpara = header.addparagraph();
//add text and image to the header
docpicture headerimage = headerpara.appendpicture(image.fromfile("logo.jpg"));
textrange tr = headerpara.appendtext("成都冰蓝科技");
document.savetofile("图文页眉.docx", fileformat.docx);
vb.net
dim document as document = new document
dim sec as section = document.addsection
dim para as paragraph = sec.addparagraph
para.appendtext("page 1")
dim header as headerfooter = sec.headersfooters.header
dim headerpara as paragraph = header.addparagraph
dim headerimage as docpicture = headerpara.appendpicture(image.fromfile("logo.jpg"))
dim tr as textrange = headerpara.appendtext("成都冰蓝科技")
document.savetofile("图文页眉".docx", fileformat.docx)
页眉效果图:
同时,我们可以通过 textwrappingstyle 和 textwrappingtype来设置图片在文本中的位置和自动换行:
c#
headerimage.textwrappingstyle = textwrappingstyle.through;
headerimage.textwrappingtype = textwrappingtype.left;
vb.net
headerimage.textwrappingstyle = textwrappingstyle.through
headerimage.textwrappingtype = textwrappingtype.left
第三部分
在c#里实现word页眉页脚的奇偶页不同和k8凯发天生赢家首页不同。主要代码设置如下所示,具体的页眉和页脚步骤参照第二部分,这里不再复述。
c#
sec.pagesetup.differentoddandevenpagesheaderfooter = true;
sec.pagesetup.differentfirstpageheaderfooter = true;
vb.net
sec.pagesetup.differentoddandevenpagesheaderfooter = true
sec.pagesetup.differentfirstpageheaderfooter = true