Create output document from source doc instead of template

this preserves the formatting of the source document, which was being
modified in copying, at the cost of a little bit more complexity
fixes #1
This commit is contained in:
Adam Goldsmith 2020-03-18 14:41:23 -04:00
parent 862a1d9f63
commit 4b69914181

41
Code.ts
View File

@ -69,27 +69,28 @@ function generateForCurrentRow() {
cell.getRow()
);
const source_doc = DocumentApp.openById(row['Document ID']);
const template_doc = DocumentApp.openById(row['Template ID']);
const template_file = DriveApp.getFileById(row['Template ID']);
const source_file = DriveApp.getFileById(row['Document ID']);
const out_folder = DriveApp.getFolderById(
'1ROyJXk-QANTHM6Jiw0ne3EQiR1f2UsLr'
);
const out_file = template_file.makeCopy(
const out_file = source_file.makeCopy(
row['Document Name'] + row['Version'],
out_folder
);
const out_doc = DocumentApp.openById(out_file.getId());
// do text replacement
Object.entries(row).forEach(([header, data]) => {
out_doc.getBody().replaceText(`{{${header}}}`, String(data));
out_doc.getHeader().replaceText(`{{${header}}}`, String(data));
out_doc.getFooter().replaceText(`{{${header}}}`, String(data));
});
// Copy header
out_doc.getHeader().clear();
copySection(template_doc.getHeader(), out_doc.getHeader());
const insert_point = out_doc
// Copy footer
out_doc.getFooter().clear();
copySection(template_doc.getFooter(), out_doc.getFooter());
const insert_point = template_doc
.getBody()
.findText('{{body}}')
?.getElement();
@ -103,10 +104,24 @@ function generateForCurrentRow() {
while (parent.getParent().getType() != DocumentApp.ElementType.BODY_SECTION) {
parent = parent.getParent();
}
const index = out_doc.getBody().getChildIndex(parent);
const index = template_doc.getBody().getChildIndex(parent);
// Copy body contents above and below {{body}} tag
for (let j = 0; j < template_doc.getBody().getNumChildren(); j++) {
if (j < index)
copyElement(template_doc.getBody().getChild(j), out_doc.getBody(), j);
// don't copy {{body}} tag
else if (j == index) continue;
else copyElement(template_doc.getBody().getChild(j), out_doc.getBody());
}
// do text replacement
Object.entries(row).forEach(([header, data]) => {
out_doc.getBody().replaceText(`{{${header}}}`, String(data));
out_doc.getHeader().replaceText(`{{${header}}}`, String(data));
out_doc.getFooter().replaceText(`{{${header}}}`, String(data));
});
copyBody(source_doc.getBody(), out_doc.getBody(), index);
out_doc.getBody().removeChild(parent);
out_doc.saveAndClose();
// create PDF file