Home > Back-end >  how to make sure the code is rendered to googlesheet before export pdf file?
how to make sure the code is rendered to googlesheet before export pdf file?

Time:11-19

I created a template sheet in google sheet. I need to generate multiple pdf files with variable data based on the template.

For example, I put "Michael" into the specific cell of the template using getRanage.Setvalu function and export the pdf file. What I need is that it would generate a pdf file with respectively variable data. However, the problem is that it is a template pdf file without the data of "Michael". When I check the template sheet, it does show the "Michael" on the template sheet.

My code is something like below.

getRange("A1").SetValue(); genaratePdf();

I tried to use the timeout function, it does work. However, this is not what I want and is inefficient.

My question is that if there is a way to make sure that "Michael" is rendered to the sheet before running the export pdf function?

CodePudding user response:

try SpreadsheetApp.flush() before running the pdf code.

CodePudding user response:

If the function getRange().setValue() has been executed successfully, the cell should be updated by the value entered in setValue, keep in mind that the value can be numeric, string, boolean or date. Unless the content of those cells is being modified by another process, such as Formulas or GAS script, you would not need to implement any additional check.

In any case, you can control if that cell was set properly before running the generatePdf function.

Code.gs
function main() {
  var dataARR = ["Michael", "Anna", "Fish"]
  var ss_id = "1CmlUOdz_8LVV00WvCU9aqIJBUf7bpNBiqk7Clwy3eHc"
  var folder_id = "1roIvZbLxhX9PKQesj0ItINfBNHia_Kv2"
  for (let data of dataARR) {
    if (editSpreadSheet(data, ss_id) === data) generatePdf(folder_id, ss_id, data)
}}
function editSpreadSheet(data, id) {
  let ss = SpreadsheetApp.openById(id).
  ss.getRange('A1').setValue(data)
  return ss.getRange('A1').getValue()
}
function generatePDF(folder_id, ss_id, data) {
  var blob_pdf = DriveApp.getFileById(ss_id).getAs('application/pdf')
  DriveApp.getFolderById(folder_id).createFile(blob_pdf).setName(data)
}
Documentation
  • Related