Home > Software engineering >  Pass value from .gs to htmlService
Pass value from .gs to htmlService

Time:09-13

I'm quite new to GAS & JS so please bear with me.

Problem 1 solved by @Cooper

I'm trying to pass the pdf link that gets generated by pdf.gs to an href in PDFlinkHTML.html.

I initially just had a Html output in the generatePDF() function and used href:"${pdf.getURl()}" but this is not viable anymore since the htmlService uses a lot of CSS, jQuery and needs a separate File.

Problem 2

I also have a loading spinner (essentially just a fixed div) in my htmlService which i want to hide (with either pure JS or jQuery) as soon as the PDF is generated and the link has been passed on to the href.

(My current "workaround" is just displaying the loading spinner in a separate ModalDialog at the start of the function & the PDFlinkHTML.html the at the end. Looks fine but feels cheap.)

I'd really appreciate some help & input.

Regards

pdf.gs

function createPDF(ssId, sheet, pdfName, lr) {
  const fr = 0, fc = 0, lc = 9;
  const url = "https://docs.google.com/spreadsheets/d/"   ssId   "/export"  
    "?format=pdf&"  
    "size=7&"  
    "fzr=true&"  
    "portrait=true&"  
    "fitw=true&"  
    "gridlines=false&"  
    "printtitle=false&"  
    "top_margin=0.5&"  
    "bottom_margin=0.25&"  
    "left_margin=0.5&"  
    "right_margin=0.5&"  
    "sheetnames=false&"  
    "pagenum=UNDEFINED&"  
    "attachment=true&"  
    "gid="   sheet.getSheetId()   '&'  
    "r1="   fr   "&c1="   fc   "&r2="   lr   "&c2="   lc;

  const params = { method: "GET", headers: { "authorization": "Bearer "   ScriptApp.getOAuthToken() } };
  const blob = UrlFetchApp.fetch(url, params).getBlob().setName(pdfName   '.pdf');
  const destinationFolder = DriveApp.getFolderById('1BI_cD628wyqHWgagwmkxYBhvHo1irrQY'); // PDF destination folder
  const pdfFile = destinationFolder.createFile(blob);
  return pdfFile;
}

function generatePDF() {

  var lock = LockService.getScriptLock();
  try {
    lock.waitLock(20000); // Attempts to acquire the lock, timing out with an exception after 20 seconds
  } catch (e) {
    Logger.log('Could not obtain lock after 20 seconds.');
    return Browser.msgBox("Server beschäftigt bitte versuche es in einem Moment erneut.");
  };

  var html = HtmlService.createTemplateFromFile('PDFloadingHTML')
  .evaluate()
  .setWidth(400)
  .setHeight(250);
  ui.showModalDialog(html, "‎");

  const templateSheet = SpreadsheetApp.openById('1entOMh9MqliPJjQm7W9loDYeghJEnqTCqcaXDoU1FCc');
  const destinationSS = templateSheet.copy('Inventory');
  const destinationSheet = destinationSS.getSheets()[0];
  const destinationID = destinationSS.getId();
  const f2 = iSheet.getRange(2, 6).getValue();
  const timestamp = Utilities.formatDate(new Date(), "GMT 2", "yyyy/MM/dd HH:mm");
  const pdfname = ""   f2   " "   timestamp   ""; // PDF output name
  // PDF generation & cleanup.

  sortedArr = sortRange();
  var letter = "";
  var counter = 0;
  var i = 5;
  while (!destinationSheet.getRange(i, 1).isBlank()) {
    if (destinationSheet.getRange(i, 1).getValue().toString().trim().length == 1) {
      letter = destinationSheet.getRange(i, 1).getValue().toString().trim().toLowerCase();
    } else if (String(sortedArr[counter]).trim().toLowerCase().startsWith(letter) && String(sortedArr[counter]).trim().toLowerCase() != "undefined") {
      destinationSheet.getRange(i, 1).setValue(sortedArr[counter][0]);
      destinationSheet.getRange(i, 2).setValue(sortedArr[counter][1]);
      counter  = 1;
      for (var j = counter; j < sortedArr.length; j  ) {
        if (String(sortedArr[counter]).trim().toLowerCase().startsWith(letter)) {
          destinationSheet.insertRowAfter(i);
          if (letter == "z") {
            destinationSheet.getRange(i, 1, 1, 9).copyTo(destinationSheet.getRange(i   1, 1, 1, 2), { formatOnly: true });
          } else {
            destinationSheet.getRange(i, 1, 1, 2).copyTo(destinationSheet.getRange(i   1, 1, 1, 2), { formatOnly: true });
          };
          i  = 1;
          destinationSheet.getRange(i, 1).setValue(sortedArr[counter][0]);
          destinationSheet.getRange(i, 2).setValue(sortedArr[counter][1])
          counter  = 1;
        };
      };
    } else {
      destinationSheet.getRange(i, 1).setValue("-");
      destinationSheet.getRange(i, 2).setValue("-");
    };
    i  = 1;
  };
  SpreadsheetApp.flush();
  destinationSheet.autoResizeColumns(2, 1);
  Utilities.sleep(500); // Using to offset any potential latency in creating .pdf
  const pdf = createPDF(destinationID, destinationSheet, pdfname, destinationSheet.getLastRow());
  DriveApp.getFileById(destinationID).setTrashed(true);

  var html = HtmlService.createTemplateFromFile('PDFlinkHTML')
  .evaluate()
  .setWidth(400)
  .setHeight(250);
  ui.showModalDialog(html, "‎");
  
  return;
}

function sortRange() {
  arr = iSheet.getRange(`D6:E${iSheet.getLastRow()}`).getDisplayValues();
  arr.sort(function (x, y) {
    var xp = x[0];
    var yp = y[0];
    return xp == yp ? 0 : xp < yp ? -1 : 1;
  });
  return arr;
}

CodePudding user response:

How about something like this:

var temp = HtmlService.createTemplateFromFile('PDFlinkHTML')
temp.pdflink = pdflinkData;
var html = temp.evaluate().setWidth(400).setHeight(250);
ui.showModalDialog(html, "‎");

 href= <?= pdflink ?>
  • Related