Home > Enterprise >  Problem sending data from a newly created PDF file to my website
Problem sending data from a newly created PDF file to my website

Time:05-29

I create a PDF and then send its information to my website so that this PDF is converted to an image file and published:

    SpreadsheetApp.flush();
    var theurl = 'https://docs.google.com/a/mydomain.org/spreadsheets/d/'  
      'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'  
        '/export?format=pdf'  
          '&size=0'  
            '&portrait=true'  
              '&fitw=true'   
                '&top_margin=0'              
                  '&bottom_margin=0'           
                    '&left_margin=0'          
                      '&right_margin=0'       
                        '&sheetnames=false&printtitle=false'  
                          '&pagenum=false'  
                            '&gridlines=false'  
                              '&fzr=FALSE'  
                                '&gid='  
                                  'aaaaaaaaaaa';
    
    var token = ScriptApp.getOAuthToken();
    var docurl = UrlFetchApp.fetch(theurl, { headers: { 'Authorization': 'Bearer '    token } });
    var pdfBlob = docurl.getBlob();
    
    //...get token and Blob (do not create the file);
    
    var fileName = ss.getSheetByName("General").getRange("H2").getValue();
    
    //Access or create the 'Archives' folder;
    var folder;
    var folders = DriveApp.getFoldersByName("Archives");
    if(folders.hasNext()) {
      folder = folders.next();
    }else {
      folder = DriveApp.createFolder("Archives");
    }
    
    //Remove duplicate file with the same name;
    var existing = folder.getFilesByName(fileName);
    if(existing.hasNext()) {
      var duplicate = existing.next();
      if (duplicate.getOwner().getEmail() == Session.getActiveUser().getEmail()) {
        var durl = 'https://www.googleapis.com/drive/v3/files/' duplicate.getId();
        var dres = UrlFetchApp.fetch(durl,{
          method: 'delete',
          muteHttpExceptions: true,
          headers: {'Authorization': 'Bearer ' token}
        });
        var status = dres.getResponseCode();
        if (status >=400) {
          
        } else if (status == 204) {
          folder.createFile(pdfBlob.setName(fileName));
        }
      }
    } else {
      folder.createFile(pdfBlob.setName(fileName));
    }
    
    Utilities.sleep(5000);
    createPostByFileName(folder, fileName);
function createPostByFileName(folder, fileName) {
  var fileIterator = folder.getFilesByName(fileName);
  if(fileIterator.hasNext()) {
    var file = fileIterator.next()
    file.setSharing(DriveApp.Access.ANYONE_WITH_LINK, DriveApp.Permission.VIEW)
    name = file.getName();
    league = name.split(' ')[0];
    title = name.split(league)[1].split('.pdf')[0];
    link = file.getUrl();
    shareable = link.split('/view')[0];
    id = file.getId();
    var data = {
      'api_league_name': league,
      'title': title,
      'google_drive_id': id,
      'google_drive_url': shareable,
      'pass': 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
    };
    var options = {
      'method' : 'post',
      'contentType': 'application/json',
      'payload' : JSON.stringify(data)
    };
    UrlFetchApp.fetch('https://www.xxx.com.br/api/posts', options);
  }
}

For some reason I am forced to put Utilities.sleep(5000); before calling the function that sends the PDF data to my website, because if I don't, when the website tries to convert the PDF to an image, an problem happens as if the PDF is not yet available in the folder or it generates a big slowdown until can access the file.

Obviously putting this sleep is not a professional way to solve the case, because then I can't even know why this happens.

Anyone who has had this experience, can tell me how I should proceed in a professional way?

CodePudding user response:

From the discussions in the comment, when Drive API is used for your script, it becomes as follows. Before you use this, please enable Drive API at Advanced Google services.

Modified script:

function sample() {
  const createFile = (filename, blob, folderId) => Drive.Files.insert({ title: filename, parents: [{ id: folderId }] }, blob);

  SpreadsheetApp.flush();
  var theurl = 'https://docs.google.com/a/mydomain.org/spreadsheets/d/'  
    'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'  
      '/export?format=pdf'  
        '&size=0'  
          '&portrait=true'  
            '&fitw=true'   
              '&top_margin=0'              
                '&bottom_margin=0'           
                  '&left_margin=0'          
                    '&right_margin=0'       
                      '&sheetnames=false&printtitle=false'  
                        '&pagenum=false'  
                          '&gridlines=false'  
                            '&fzr=FALSE'  
                              '&gid='  
                                'aaaaaaaaaaa';
  var token = ScriptApp.getOAuthToken();
  var docurl = UrlFetchApp.fetch(theurl, { headers: { 'Authorization': 'Bearer '   token } });
  var pdfBlob = docurl.getBlob();
  var fileName = ss.getSheetByName("General").getRange("H2").getValue();
  var folder;
  var folders = DriveApp.getFoldersByName("Archives");
  if (folders.hasNext()) {
    folder = folders.next();
  } else {
    folder = DriveApp.createFolder("Archives");
  }
  var existing = folder.getFilesByName(fileName);
  var pdfFileId = "";
  if (existing.hasNext()) {
    var duplicate = existing.next();
    if (duplicate.getOwner().getEmail() == Session.getActiveUser().getEmail()) {
      var durl = 'https://www.googleapis.com/drive/v3/files/'   duplicate.getId();
      var dres = UrlFetchApp.fetch(durl, {
        method: 'delete',
        muteHttpExceptions: true,
        headers: { 'Authorization': 'Bearer '   token }
      });
      var status = dres.getResponseCode();
      if (status >= 400) {
      } else if (status == 204) {
        var obj = createFile(fileName, pdfBlob, folder.getId());
        pdfFileId = obj.id;
      }
    }
  } else {
    var obj = createFile(fileName, pdfBlob, folder.getId());
    pdfFileId = obj.id;
  }

  // Utilities.sleep(5000);

  Drive.Permissions.insert({ role: "reader", type: "anyone" }, pdfFileId);
  league = fileName.split(' ')[0];
  title = fileName.split(league)[1].split('.pdf')[0];
  shareable = "https://drive.google.com/file/d/"   pdfFileId;
  id = pdfFileId;
  var data = {
    'api_league_name': league,
    'title': title,
    'google_drive_id': id,
    'google_drive_url': shareable,
    'pass': 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'
  };
  var options = {
    'method': 'post',
    'contentType': 'application/json',
    'payload': JSON.stringify(data)
  };
  UrlFetchApp.fetch('https://www.xxx.com.br/api/posts', options);
}

Note:

  • This is a sample script for testing whether Utilities.sleep(5000) can be removed.
  • Related