我有一个简单的小应用程序脚本,根据请求刷新我们的动态标志。问题是我不能瞄准头,如果设计师检查"不同的第一页页眉/页脚"复选框。是否有远离目标不同的头,如果它被选中?
下面是我当前使用的代码:
function onOpen() {
DocumentApp.getUi().createMenu('Branding')
.addItem('Update Branding', 'updateLogo')
.addToUi();
}
function updateLogo() {
var doc = DocumentApp.getActiveDocument();
var header = doc.getHeader();
if (header) {
var images = header.getImages();
var logoWidth = 250;
if (images.length > 0) {
var image = images[0];
logoWidth = image.getWidth(); // pixels
image.removeFromParent();
}
var freshLogo = UrlFetchApp.fetch("http://example.com/logo.jpg").getBlob();
var newImage = header.insertImage(0, freshLogo);
var logoRatio = newImage.getHeight() / newImage.getWidth();
newImage.setWidth(logoWidth);
newImage.setHeight(newImage.getWidth() * logoRatio);
}
}
在浏览了Eric的Google问题链接中的几个未解决问题后,我发现了以下问题:
这是我的发现,我将用一个干净的例子来说明。
- 新建Google Doc
- 在标题部分插入"Common header"文本
- 在页脚部分插入文本"Common footer"
- 勾选不同的第一页页眉/页脚选项
- 在现在空白的标题部分输入文本"不同的第一个标题"
- 在现在空白的页脚部分输入文本"不同的第一页脚"
打开脚本编辑器,运行下面的函数:
function getSectionText() {
var d = DocumentApp.getActiveDocument();
var p = d.getBody().getParent();
// let's loop through all the child elements in the document
for ( var i = 0; i < p.getNumChildren(); i += 1 ) {
var t = p.getChild(i).getType();
if ( t === DocumentApp.ElementType.BODY_SECTION ) continue; // not interested in the body
if ( t === DocumentApp.ElementType.HEADER_SECTION ) {
var h = p.getChild(i).asHeaderSection().getText();
Logger.log( 'Child index number: ' + i );
Logger.log( h );
} else if ( t === DocumentApp.ElementType.FOOTER_SECTION ) {
var f = p.getChild(i).asFooterSection().getText();
Logger.log( 'Child index number: ' + i );
Logger.log( f );
}
}
}
当您查看日志文件时,您应该看到以下输出:
[17-09-22 16:33:03:628 AEST] Child index number: 1
[17-09-22 16:33:03:629 AEST] Common header
[17-09-22 16:33:03:633 AEST] Child index number: 2
[17-09-22 16:33:03:633 AEST] Common footer
[17-09-22 16:33:03:636 AEST] Child index number: 3
[17-09-22 16:33:03:637 AEST] Different first header
[17-09-22 16:33:03:659 AEST] Child index number: 4
[17-09-22 16:33:03:660 AEST] Different first footer
这将有助于您与通用页眉和页脚的交互
不幸的是,Apps Script的DocumentApp不知道不同的第一页页眉/页脚设置。请在这里提交功能请求:https://code.google.com/p/google-apps-script-issues/issues/list
这个应该可以工作。您可能必须使用doc.getHeader()
(第一页标头)以及DHeader
(第二页,第三页,第四页的标头……页)。
var doc = DocumentApp.getActiveDocument();
var header = doc.getHeader();
var DHeader = header.getParent().getChild(2).asHeaderSection();
/*
Some may seem pointless as seeing that getParent().getChild(2)
may be replaced somehow with getNextSibling(), however,
googlescript does not allow
the use of getNextSibling() for a HeaderSection
*/