【问题标题】:Get Google Document as HTML以 HTML 格式获取 Google 文档
【发布时间】:2013-02-02 16:18:53
【问题描述】:

我有一个疯狂的想法,我可以使用 Google Drive Documents 为不成熟的用户朋友建立一个网站博客来支持它。我能够创建一个 contentService 来编译文档列表。但是,我看不到将文档转换为 HTML 的方法。我知道 Google 可以在网页中渲染文档,所以我想知道是否有可能获得渲染版本以用于我的内容服务。

这可能吗?

【问题讨论】:

  • 注意:您可能认为DocumentApp.getActiveDocument().getAs(MimeType.HTML) 会起作用,但会引发错误:Converting from application/vnd.google-apps.document to text/html is not supported.

标签: google-apps-script google-docs


【解决方案1】:

你可以试试这个代码:

  function getGoogleDocumentAsHTML(){
  var id = DocumentApp.getActiveDocument().getId() ;
  var forDriveScope = DriveApp.getStorageUsed(); //needed to get Drive Scope requested
  var url = "https://docs.google.com/feeds/download/documents/export/Export?id="+id+"&exportFormat=html";
  var param = {
    method      : "get",
    headers     : {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
    muteHttpExceptions:true,
  };
  var html = UrlFetchApp.fetch(url,param).getContentText();
  Logger.log(html);
}

【讨论】:

    【解决方案2】:

    Node.js 解决方案

    使用Google APIs Node.js Client

    以下是使用 google drive 的 node.js 客户端库获取 html 格式的 google 文档的方法。

    // import googleapis npm package
    var google = require('googleapis');
    
    // variables
    var fileId = '<google drive doc file id>',
        accessToken = '<oauth access token>';
    
    // oauth setup
    var OAuth2 = google.auth.OAuth2,
        OAuth2Client = new OAuth2();
    
    // set oauth credentials
    OAuth2Client.setCredentials({access_token: accessToken});
    
    // google drive setup
    var drive = google.drive({version: 'v3', auth: OAuth2Client});
    
    // download file as text/html
    var buffers = [];
    drive.files.export(
        {
            fileId: fileId,
            mimeType: 'text/html'
        }
    )
        .on('error', function(err) {
            // handle error
        })
        .on('data', function(data) {
            buffers.push(data); // data is a buffer
        })
        .on('end', function() {
            var buffer = Buffer.concat(buffers),
                googleDocAsHtml = buffer.toString();
            console.log(googleDocAsHtml);
        });
    

    查看Google Drive V3 download docs 了解更多语言和选项。

    【讨论】:

      【解决方案3】:

      Google 文档目前具有执行此操作的功能。 只需下载到 zip(.html),您就可以拥有一个带有 html 和图像(如果已插入)的 zip 存档

      我知道这不是基于代码的解决方案,而是它的工作原理:)

      【讨论】:

        【解决方案4】:

        在 GAS 中没有直接的方法来获取文档的 HTML 版本,这是一个相当古老的 enhancement request,但 Henrique Abreu 的 workaround described originally 效果很好,我一直在使用它...

        授权过程中唯一烦人的事情是需要从脚本编辑器中调用,这使得在共享应用程序中使用起来很不方便(“无法使用脚本”的用户),但这只会发生一次;)。

        还有一个由Romain Vialard 创建的Library,它使事情(有点)变得更容易......并添加了一些其他有趣的功能。

        【讨论】:

        • 我很想查看您从@HenriqueAbreu 提到的解决方法,但该链接不再可用:它是否在其他地方发布? -- 谢谢,福斯托
        • 是的,我知道,他们清除了档案……无论如何,代码在许多地方仍然可见。例如stackoverflow.com/questions/10954075/…。在问题跟踪器上也是如此。
        【解决方案5】:

        根据 Enrique 发布的想法,以下是新版 goole AOuth 的一些片段:

        function exportAsHTML(){
          var forDriveScope = DriveApp.getStorageUsed(); //needed to get Drive Scope requested
          var docID = DocumentApp.getActiveDocument().getId();
          var url = "https://docs.google.com/feeds/download/documents/export/Export?id="+docID+"&exportFormat=html";
          var param = {
            method      : "get",
            headers     : {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
            muteHttpExceptions:true,
          };
          var html = UrlFetchApp.fetch(url,param).getContentText();
          return html; 
        
        }
        

        然后使用通常的mailApp:

        function mailer(){
           var docbody = exportAsHTML();
           MailApp.sendEmail({
             to: "email@mail.com",
             subject: "document emailer",
             htmlBody:  docbody  });
        }
        

        希望新的解决方法有所帮助

        京东

        【讨论】:

          【解决方案6】:

          您可以使用解决方案here

          /**
           * Converts a file to HTML. The Advanced Drive service must be enabled to use
           * this function.
           */
          function convertToHtml(fileId) {
            var file = Drive.Files.get(fileId);
            var htmlExportLink = file.exportLinks['text/html'];
            if (!htmlExportLink) {
              throw 'File cannot be converted to HTML.';
            }
            var oAuthToken = ScriptApp.getOAuthToken();
            var response = UrlFetchApp.fetch(htmlExportLink, {
              headers:{
                'Authorization': 'Bearer ' + oAuthToken
              },
              muteHttpExceptions: true
            });
            if (!response.getResponseCode() == 200) {
              throw 'Error converting to HTML: ' + response.getContentText();
            }
            return response.getContentText();
          }
          

          作为 fileId 传递,谷歌文档的 id 并按照说明here 启用高级驱动器服务。

          【讨论】:

            【解决方案7】:

            我也遇到过这个问题。 Document HTML Export 吐出的 HTML 真的很难看,所以这是我的解决方案:

            /**
             * Takes in a Google Doc ID, gets that doc in HTML format, cleans up the markup, and returns the resulting HTML string.
             *
             * @param {string} the id of the google doc
             * @param {boolean} [useCaching] enable or disable caching. default true.
             * @return {string} the doc's body in html format
             */
            function getContent(id, useCaching) {
            
              if (!id) {
                throw "Please call this API with a valid Google Doc ID";
              }
            
              if (useCaching == null) {
                useCaching = true;
              }
            
              if (typeof useCaching != "boolean") {
                throw "If you're going to specify useCaching, it must be boolean.";
              }
            
              var cache = CacheService.getScriptCache();
              var cached = cache.get(id); // see if we have a cached version of our parsed html
              if (cached && useCaching) {
                var html = cached;
                Logger.log("Pulling doc html from cache...");
              } else {
            
                Logger.log("Grabbing and parsing fresh html from the doc...");
            
                try {
                  var doc = DriveApp.getFileById(id);
                } catch (err) {
                  throw "Please call this API with a valid Google Doc ID. " + err.message;
                }
            
                var docName = doc.getName();
            
                var forDriveScope = DriveApp.getStorageUsed(); // needed to get Drive Scope requested in ScriptApp.getOAuthToken();
                var url = "https://docs.google.com/feeds/download/documents/export/Export?id=" + id + "&exportFormat=html";
                var param = {
                  method: "get",
                  headers: {"Authorization": "Bearer " + ScriptApp.getOAuthToken()},
                  muteHttpExceptions:true,
                };
            
                var html = UrlFetchApp.fetch(url, param).getContentText();
            
                // nuke the whole head section, including the stylesheet and meta tag
                html = html.replace(/<head>.*<\/head>/, '');
                // remove almost all html attributes
                html = html.replace(/ (id|class|style|start|colspan|rowspan)="[^"]*"/g, '');
                // remove all of the spans, as well as the outer html and body
                html = html.replace(/<(span|\/span|body|\/body|html|\/html)>/g, '');
                // clearly the superior way of denoting line breaks
                html = html.replace(/<br>/g, '<br />');
            
                cache.put(id, html, 900) // cache doc contents for 15 minutes, in case we get a lot of requests
            
              }
            
              Logger.log(html);
            
              return html;
            
            }
            

            https://gist.github.com/xd1936/cc229d14a89e6327336177bb07ac2980

            【讨论】:

              【解决方案8】:

              也许这对你有用...

              function doGet() {
                var blob = DriveApp.getFileById('myFileId').getAsHTML();
                return HtmlService.createHtmlOutput(blob);
              }
              

              【讨论】:

              • 你引用了 Romain Vialard 的图书馆吗?如果是这种情况,您应该在评论中提及它
              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 2019-07-09
              • 2011-07-08
              • 2016-02-08
              • 2012-10-16
              • 2016-05-15
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多