I have a simple little apps script that refreshes our dynamic logo on request. The problem is I can't target the header if the designer checks "Different first page header/footer" checkbox. Is there away to target the different header if it's checked?
Here is the code I'm currently using:
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);
}
}
I discovered the following after going through a few of the open issues in Eric's Google Issues link.
Here's what I found, and I'll use a clean example to illustrate.
Open up the Script Editor and run the function below:
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 );
}
}
}
When you view your log file your should see the following output:
[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
This should help you with interacting with the common and first page headers and footers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With