Crea un file png da un disegno Google utilizzando App Script

Aug 19 2020

Ho una cartella piena di Disegni Google. Ho i nomi dei file dei Disegni Google in un foglio di lavoro di Google. Posso estrarre i nomi dei file dal foglio di calcolo di Google, scorrere i nomi dei file, trovare tutti i disegni di Google e ... è qui che rimango bloccato. Vorrei convertire i disegni in file PNG e archiviare i file PNG in una cartella di unità separata.

Questa è la sceneggiatura che ho finora ...

function load_list_of_images() {
  var course_workbook_name = "SPREADSHEET"; // Title of spreadsheet to download files
  var course_workbooks = DriveApp.getFilesByName(course_workbook_name); // There may be more than one!
  try{
    var course_workbook_id = course_workbooks.next();
    Logger.log("Spreadsheet ID : " + course_workbook_id);    
  } catch(error) {
    Logger.log("Spreadsheet doesn't exist");
    return(null);
  }
  var course_workbook = SpreadsheetApp.open(course_workbook_id);
  var image_list_sheet = course_workbook.getSheetByName("image_list");
  // Get list of image names (without extensions)
  var list_of_images = [];
  var images = image_list_sheet.getRange(1,1,1000).getValues();
  for (var row in images) {
    for (var col in images[row]) {
      if (images[row][col] == "") {
        return(list_of_images);
      }
      list_of_images.push(images[row][col]);
    }
  }
}

function download_images() {
  var list = load_list_of_images();
  if (list == null){
    return(null);
  }
  for (var row in list){
    var image_name = list[row];
    var image_exists = DriveApp.getFilesByName(image_name);
    // There may be more than one
    if (image_exists.hasNext()) {
      var image = image_exists.next()
      var gDraw_file = DriveApp.getFileById(image.getId());
      DriveApp.createFile(gDraw_file.getBlob());
    }
  }
}

Quando lo eseguo, tutti i disegni di Google vengono convertiti in file PDF e memorizzati nella mia cartella dell'unità.

Risposte

1 ziganotschka Aug 19 2020 at 15:02

È necessario specificare in quale MimeType si desidera convertire il disegno

Tuttavia, la conversione da drawingsa pngnon è possibile direttamente, è necessario eseguire i seguenti passaggi:

  • Crea un link di esportazione per esportare il file come image/png
  • Recupera questo collegamento con UrlFetchApp
  • Crea un file dal BLOB del risultato

Campione

  var id = image.getId(); 
  var exportUrl = "https://www.googleapis.com/drive/v3/files/" + id + "/export?mimeType=image/png";
  var urlFetchOptions = {
    headers: {Authorization : "Bearer " + ScriptApp.getOAuthToken()}
  };
  var blob= UrlFetchApp.fetch(exportUrl, urlFetchOptions).getBlob();
  DriveApp.createFile(blob);