Fill a Doc template and save it as PDF
Apps Script recipes › Email, Docs, Forms and PDF
Copies a Google Doc with {{placeholders}}, fills them in, saves a PDF in a folder and removes the copy.
File Code.gs
const TEMPLATE_DOC_ID = '';
const PDF_FOLDER_ID = '';
/** fields: { name: 'Rina', date: '3 November 2026' } → the PDF file. */
function makePdf_(fields, fileName) {
const folder = DriveApp.getFolderById(PDF_FOLDER_ID);
const copy = DriveApp.getFileById(TEMPLATE_DOC_ID).makeCopy(fileName, folder);
const doc = DocumentApp.openById(copy.getId());
const body = doc.getBody();
Object.entries(fields).forEach(([key, value]) => {
body.replaceText('\\{\\{' + key + '\\}\\}', String(value));
});
doc.saveAndClose();
const pdf = folder.createFile(copy.getAs(MimeType.PDF)).setName(fileName + '.pdf');
copy.setTrashed(true);
return pdf;
}
Good to know
- replaceText takes a regular expression: the recipe escapes the {{ }} around each name.
- The PDF keeps the Doc's own fonts and layout; design the template in Google Docs.
Let the AI put it in your appGAS AI Builder knows every recipe here. Describe your app and it uses this code where it fits, in a Google Apps Script project in your own Drive.
Use it in a project