Reputation: 3
I have built a tool in google scripts that is currently set up as a bound script to a google docs file. The goal of the tool is to pull in templates from other created docs files from a custom form input. The code works as is as a bound script, but I am trying to port that code over to create an Add-on for users within my organization. The issue right now is that when trying to insert the template elements into the header or footer of the clean test documents, the code throws an error when attempting to append the elements to the saying Cannot call method "appendParagraph" of null.
I have tried appending as a header and footer with DocumentApp.getActiveDocument().getHeader().appendParagraph
. This method works when I am using the script as a bound script and it works as expected. When I try to append the paragraph (or other element) to the body instead of the header or footer while testing as an Add-on the elements are appended without issue. The only time I am getting this error is when I try to append the elements to either the header or footer.
function examplefunction_( docLink, locPaste ) {
var srcBody = DocumentApp.openById( docLink )
.getBody();
var srcNumChild = srcBody.getNumChildren();
var activeBody = DocumentApp.getActiveDocument()
.getBody();
var activeHead = DocumentApp.getActiveDocument()
.getHeader();
var activeFoot = DocumentApp.getActiveDocument()
.getFooter();
var a =0;
if ( locPaste == 'Body') {
var activeLoc = activeBody;
}
else if (locPaste == 'Header') {
var activeLoc = activeHead;
}
else if (locPaste == 'Footer') {
var activeLoc = activeFoot;
}
for (var i = 0; i<srcNumChild; i++) {
if (srcBody.getChild(i).getType() == DocumentApp.ElementType.PARAGRAPH) {
var srcText = srcBody.getChild(i).copy();
activeLoc.appendParagraph(srcText);
}
else if (srcBody.getChild(i).getType() == DocumentApp.ElementType.TABLE) {
var srcTable = srcBody.getTables();
var copiedTable = srcTable[a].copy()
a = a + 1;
activeLoc.appendTable(copiedTable);
}
else if (srcBody.getChild(i).getType() == DocumentApp.ElementType.LIST_ITEM) {
var srcList = srcBody.getChild(i).getText();
var listAtt = srcBody.getChild(i).getAttributes();
var nestLvl = srcBody.getChild(i).getNestingLevel();
activeLoc.appendListItem(srcList).setAttributes(listAtt).setNestingLevel(nestLvl);
}
else {
Logger.log("Could not get element: " + i);
}
}
}
I expected the elements to be appended to the headers and footers from the template without error like when run as a bounded script. The actual result while being run kills the process with error "Cannot call method appendParagraph
of null." at the line: activeLoc.appendParagraph(srcText);
Upvotes: 0
Views: 720
Reputation: 26836
Add to the beginning of your function:
if(!DocumentApp.getActiveDocument().getHeader()){
DocumentApp.openById(docLink).addHeader();
}
Same for the footer.
Upvotes: 0