I am attempting to change the margins of the first section of a Google Doc, however the code below is applying this to the whole document:
// Insert section break at the beginning of the document
const resource = {requests: [{insertSectionBreak: {sectionType: "NEXT_PAGE", location: {index: 1}}}]};
Docs.Documents.batchUpdate(resource, docId);
var body = doc.getBody();
body.setMarginTop(0);
body.setMarginLeft(0);
body.setMarginRight(0);
body.setMarginBottom(0);
Is there a way to apply margin settings to a specific section of the document?
I believe your goal is as follows.
When I checked this, unfortunately, I couldn't find the built-in method of Document service (DocumentApp)for achieving your goal. But, fortunately, it seems that this can be achieved by Google Docs API. In this case, I would like to propose the sample script using Docs API.
Before you use this script, please enable Google Docs API at Advanced Google services.
function myFunction() {
const sectionNumber = 1; // 1 is the first section.
const doc = DocumentApp.getActiveDocument();
const docId = doc.getId();
const obj = Docs.Documents.get(docId, { fields: "body(content(sectionBreak,startIndex,endIndex))" }).body.content.filter(e => e.sectionBreak);
const section = obj[sectionNumber - 1];
if (!section) {
throw new Error(`No section of ${sectionNumber} is not found.`);
}
const { startIndex, endIndex } = section;
const requests = [{
updateSectionStyle: {
range: { startIndex: startIndex || 0, endIndex },
sectionStyle: {
marginLeft: { unit: "PT", magnitude: 0 },
marginRight: { unit: "PT", magnitude: 0 },
marginTop: { unit: "PT", magnitude: 0 },
marginBottom: { unit: "PT", magnitude: 0 }
},
fields: "marginLeft,marginRight,marginTop,marginBottom"
}
}];
Docs.Documents.batchUpdate({ requests }, docId);
}
sectionStyle
to your actual situation.