【问题标题】:using Google Apps Script: how to convert/export a Drive file?使用 Google Apps 脚本:如何转换/导出云端硬盘文件?
【发布时间】:2017-08-10 18:50:10
【问题描述】:

我想使用 Google Apps 脚本将原生 Google 电子表格/文档/绘图/演示文件导出到同一文件夹中的另一种格式。 我启用了Advanced Drive Service,并查看了Open and Convert Google Docs in your app的说明。

希望我可以使用Export 获得File,然后我可以使用Insert 保存/重命名它。

尝试实现以下目标:

var file = {fileId: "1yDe...lD2U", 
            folderId: "0B_...hZ1k", 
            mimetype:"application/vnd.google-apps.document", 
            targetMimetype:"application/pdf", 
            targetName:"my converted document"}
var newFile = Drive.Files.export(file.fileId, file.targetMimetype)

// results in error message:
// "Export requires alt=media to download the exported content."

// I am sure the above is incomplete, but unsure how to actually
// save the exported file, in the correct location, with correct filename

更新:将 alt=media 添加到调用 (var newFile = Drive.Files.export(file.fileId, file.targetMimetype, {alt: "media"})) 时,脚本会以错误代码 200 退出并在错误消息中显示 PDF 内容。类似于issue 6573

更新:这可能不够清楚,我想转换/转换Advanced Drive 页面中列出的所有格式,而不仅仅是 PDF。 DriveApp getAs 文档指出 DriveApp 可以大部分转换为 PDF 和图像。因此,重点是使用 Advanced Drive 而不是 DriveApp。

【问题讨论】:

  • 出于任何原因,您不能使用应用脚本原生函数,例如:var blob = DriveApp.getFileById(file.fileId).getAs('application/pdf') 和 DriveApp.getFolderById(file.folderId)。 createFile(blob) 来创建你的 newPdfFile?
  • 好点。应该适用于 PDF 导出。不过,我需要转换为“在您的应用中打开和转换 Google 文档”中列出的所有格式。 developers.google.com/apps-script/reference/drive/… 声明:要转换为的 MIME 类型。对于大多数 blob,“application/pdf”是唯一有效的选项。对于 BMP、GIF、JPEG 或 PNG 格式的图像,“image/bmp”、“image/gif”、“image/jpeg”或“image/png”中的任何一个都有效。

标签: google-apps-script google-drive-api


【解决方案1】:

你很亲密。只需将 pdf 内容用作多部分插入/发布的一部分。

【讨论】:

  • 听起来很有希望。你会碰巧有一个工作的例子吗?我还不熟悉创建多部分插入。
【解决方案2】:

尝试从 Armit Agarwal 调整 this code。将驱动器文件导出为 PDF 的重要部分是这部分代码:

var blob = DriveApp.getFileById(ss.getId()).getAs("application/pdf");

  blob.setName(ss.getName() + ".pdf"); 

然后您可以通过附加pdf文件将其发送到您的电子邮件:

// If allowed to send emails, send the email with the PDF attachment
  if (MailApp.getRemainingDailyQuota() > 0) 
    GmailApp.sendEmail(email, subject, body, {
      htmlBody: body,
      attachments:[blob]     
    });  

查看指南以获取更多参考。

【讨论】:

  • 同意,仅转换为 PDF DriveApp 就足够了。我还需要转换为其他格式,例如Word/Excel。
【解决方案3】:

作为一种解决方法,我现在使用 OAuth2 库和直接 Drive API。

// ---------------------------------------------------------------------------------------------------
function testConvert() {
  var file = {
    id: "1cpAZp...I7ejZW1idk", // Google Sheet
    folderId: "0B_...Z1k", // test folder
  }

  convert(file, "pdf", "application/pdf");
  convert(file, "csv", "text/csv");
  convert(file, "xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
}

// ---------------------------------------------------------------------------------------------------
function convert(file, extension, targetMimeType) {
  var exportDetails = {
    targetMimeType: targetMimeType || "application/pdf",
    extension: extension || "pdf",
    postfix: "CONVERTED_FROM_GOOGLE_DOC",
  }

  // http://stackoverflow.com/questions/42887569/using-google-apps-script-how-to-convert-export-a-drive-file
  // https://code.google.com/p/google-apps-script-issues/issues/detail?id=6573

  // var blob = Drive.Files.export(file.id, exportDetails.targetMimeType, {alt: "media"})
  /*
    results in error 200 + content of converted file
    documentation https://developers.google.com/drive/v2/reference/files/export
    1) does not mention the {alt:"media"} (and without it the error is: "export requires alt=media to download the exported content")
    2) states the output is a Files resource (not a blob)
  */

  // using alternative: OAuth2 + public API
  // https://github.com/googlesamples/apps-script-oauth2
  var driveService = getDriveService();
  if (!driveService.hasAccess()) {
    showSidebar();
    return;
  }

  var accessToken = driveService.getAccessToken();
  var url = "https://www.googleapis.com/drive/v2/files/"+file.id+"/export?mimeType="+ exportDetails.targetMimeType
  var blob = UrlFetchApp.fetch(url, {
    headers: {
      Authorization: 'Bearer ' + driveService.getAccessToken()
    }
  });

  var resource = {
    title: DriveApp.getFileById(file.id).getName() +" "+ exportDetails.postfix +"."+ exportDetails.extension,
    description: "This is a converted document",
    mimeType: exportDetails.targetMimeType,
    parents: [{
      "kind": "drive#parentReference",
      "id": file.folderId,
      //"selfLink": string,
      //"parentLink": string,
      "isRoot": false
    }],
  }

  try {
    var convertedFile = Drive.Files.insert(resource, blob);
    Logger.log('ID: %s, File size (bytes): %s', convertedFile.id, convertedFile.fileSize);

  } catch(e) {
    Logger.log(e)
  }
}

【讨论】:

    【解决方案4】:

    这是来自 https://issuetracker.google.com/issues/36765129#comment8 的正确解决方案,由 Google 人员提供。

    Files.export() 最近被添加到 Drive v2 API,但替代方法是使用旧的 File.exportLinks 字段。这是一个例子:

    function convertToDocx(documentId) { 
      var file = Drive.Files.get(documentId); 
      var url = file.exportLinks['application/vnd.openxmlformats-officedocument.wordprocessingml.document']; 
      var oauthToken = ScriptApp.getOAuthToken(); 
      var response = UrlFetchApp.fetch(url, { 
        headers: { 
          'Authorization': 'Bearer ' + oauthToken 
        } 
      }); 
      return response.getBlob(); 
    }
    

    【讨论】:

      猜你喜欢
      • 2017-07-13
      • 2017-09-21
      • 2017-08-14
      • 2019-02-28
      • 2020-02-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多