如何用Google Apps Script将生成的Google Doc转为PDF及优化方案
从Google Sheets批量生成填充数据的PDF方案
一、改造现有脚本实现Google Doc转PDF
你当前的脚本已经能生成填充好数据的Google Doc,只需在生成Doc后添加PDF导出逻辑,即可直接生成目标PDF,同时可选择保留或删除临时Doc文件。
修改后的完整脚本
function onOpen() { const ui = SpreadsheetApp.getUi(); const menu = ui.createMenu('AutoFill Docs'); menu.addItem('Create New PDFs', 'createNewPDFs') menu.addToUi(); } function createNewPDFs() { // 模板Doc的ID const googleDocTemplate = DriveApp.getFileById('19Yy2kyLKnvXYPJcOTxmv5GQ46JmpE1JHZSYkcfw1Z9s'); // 存储PDF的目标文件夹ID const destinationFolder = DriveApp.getFolderById('1mWUtqLaaSpPbxIQdn0aARSnnRUH1DpQ6'); const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Data'); const rows = sheet.getDataRange().getValues(); rows.forEach(function(row, index){ if (index === 0) return; // 跳过表头行 if (row[5]) return; // 已生成过PDF则跳过 // 复制模板并填充数据 const docCopy = googleDocTemplate.makeCopy(`${row[1]}, ${row[0]} Employee Details`, destinationFolder); const doc = DocumentApp.openById(docCopy.getId()); const body = doc.getBody(); const friendlyDate = new Date(row[3]).toLocaleDateString(); // 替换模板变量 body.replaceText('{{Name of Investment}}', row[0]); body.replaceText('{{Call #}}', row[1]); body.replaceText('{{Investor Name}}', row[2]); body.replaceText('{{Due Date}}', friendlyDate); body.replaceText('{{Current Call}}', row[4]); body.replaceText('{{Agreement Type}}', row[6]); body.replaceText('{{Total Commitment}}', row[7]); body.replaceText('{{Total Previous Called}}', row[8]); body.replaceText('{{Remaining Uncalled}}', row[9]); body.replaceText('{{Bank Name}}', row[10]); body.replaceText('{{Bank Account Name}}', row[11]); body.replaceText('{{Routing #}}', row[12]); body.replaceText('{{Bank Account #}}', row[13]); doc.saveAndClose(); // 将Doc导出为PDF并保存到目标文件夹 const docFile = DriveApp.getFileById(docCopy.getId()); const pdfBlob = docFile.getAs('application/pdf'); const pdfFile = destinationFolder.createFile(pdfBlob).setName(`${row[1]}, ${row[0]} Employee Details.pdf`); // 将PDF链接写入表格第6列(原Doc链接列) const pdfUrl = pdfFile.getUrl(); sheet.getRange(index + 1, 6).setValue(pdfUrl); // 可选:删除临时生成的Google Doc文件 // docFile.setTrashed(true); }) }
关键修改点
- 调整菜单和函数名称,更贴合PDF生成场景
- 在文档保存关闭后新增PDF导出逻辑:
- 获取生成的临时Doc文件对象
- 将其导出为PDF格式的Blob
- 在目标文件夹创建PDF文件并设置对应名称
- 将PDF链接写入表格第6列
- 可选:取消注释最后一行代码可自动删除临时生成的Google Doc
二、更简便的直接填充PDF表单方案
如果你的原始模板是带可编辑表单字段的PDF,可以跳过Google Doc中转步骤,直接用脚本读取PDF字段并填充数据,效率更高。
实现步骤与示例代码
- 将带可编辑字段的PDF模板上传到Google Drive,记录其文件ID
- 启用Google Apps Script的Advanced Drive Service(脚本编辑器中依次点击「服务」→「添加服务」→ 选择「Drive API」并添加)
- 使用以下脚本批量生成填充后的PDF:
function onOpen() { const ui = SpreadsheetApp.getUi(); const menu = ui.createMenu('AutoFill PDFs'); menu.addItem('Generate PDFs', 'generateFilledPDFs') menu.addToUi(); } function generateFilledPDFs() { // 带表单字段的PDF模板ID const pdfTemplateId = '你的PDF模板ID'; const destinationFolder = DriveApp.getFolderById('1mWUtqLaaSpPbxIQdn0aARSnnRUH1DpQ6'); const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Data'); const rows = sheet.getDataRange().getValues(); rows.forEach(function(row, index){ if (index === 0) return; if (row[5]) return; // 复制PDF模板 const copiedFile = Drive.Files.copy({ title: `${row[1]}, ${row[0]} Employee Details.pdf`, parents: [{id: destinationFolder.getId()}] }, pdfTemplateId); // 构造表单字段填充数据(键为PDF表单字段名称,值为表格对应数据) const formFields = { 'Name of Investment': row[0], 'Call #': row[1], 'Investor Name': row[2], 'Due Date': new Date(row[3]).toLocaleDateString(), 'Current Call': row[4], 'Agreement Type': row[6], 'Total Commitment': row[7], 'Total Previous Called': row[8], 'Remaining Uncalled': row[9], 'Bank Name': row[10], 'Bank Account Name': row[11], 'Routing #': row[12], 'Bank Account #': row[13] }; // 填充PDF表单字段 Drive.Files.update( {contentHints: {form: {inputValues: formFields}}}, copiedFile.id, null, {convert: false} ); // 将PDF链接写入表格 const pdfUrl = `https://drive.google.com/file/d/${copiedFile.id}/view`; sheet.getRange(index + 1, 6).setValue(pdfUrl); }) }
注意事项
- 需确保
formFields中的键与PDF模板的表单字段名称完全一致(可通过Adobe Acrobat等工具查看字段名称) - 若PDF模板没有可编辑表单字段,此方案不适用,仍需使用Doc中转的方式
内容的提问来源于stack exchange,提问作者Brad
相关产品推荐
相关产品推荐

