如何用JavaScript Office API实现Word第二页及后续页面的不同页眉
实现Word插件中首页与后续页面的不同页眉设置
要实现首页和第二页及之后页面使用不同页眉的需求,核心是开启Word文档节的「不同首页页眉页脚」功能,然后分别对首页页眉和后续页面页眉设置内容。以下是修改后的完整代码:
Office.initialize = function () { // 插件入口 }; function addHeaderAndFooter() { Word.run(function (context) { var section = context.document.sections.getFirst(); // 开启不同首页页眉页脚设置 section.differentFirstPageHeaderFooter = true; // 加载需要操作的页眉对象:首页页眉、普通页眉、页脚 section.load("firstPageHeader, header, footer"); return context.sync() .then(function () { // 设置首页页眉内容 var firstPageHeader = section.firstPageHeader; firstPageHeader.insertText("ABC", Word.InsertLocation.start); // 设置第二页及以后的页眉内容 var normalHeader = section.header; normalHeader.insertText("DEF", Word.InsertLocation.start); // 设置统一的页脚内容(如果需要区分首页页脚,同理用section.firstPageFooter) var footer = section.footer; footer.insertText("Footer text", Word.InsertLocation.start); return context.sync(); }); }) .catch(function (error) { console.log(error.message); }); }
关键逻辑说明
section.differentFirstPageHeaderFooter = true:必须先开启这个属性,Word才会区分首页和其他页面的页眉页脚section.firstPageHeader:指向当前节的首页专属页眉,仅对第一页生效section.header:开启不同首页设置后,这个对象指向的是除首页外所有页面的页眉- 如果需要页脚也区分首页和其他页,直接使用
section.firstPageFooter设置首页页脚,section.footer设置后续页面页脚即可
内容的提问来源于stack exchange,提问作者amit gangurde
相关产品推荐
相关产品推荐

