2013-02-02 1 views
7

Googleドライブドキュメントを使用して親しみのないユーザーの友だちのためにウェブサイトのブログを構築することができたというのは野心的な考えでした。ドキュメントのリストをコンパイルするcontentServiceを作成することができました。しかし、ドキュメントをHTMLに変換する方法がわかりません。私はGoogleがウェブページでドキュメントをレンダリングできることを知っているので、コンテンツサービスで使用するためにレンダリングされたバージョンを取得することが可能かどうか疑問に思った。GoogleドキュメントをHTML形式で入手する

これは可能ですか?

答えて

3

ありドキュメントのHTML版を入手するガス中のNO直接的な方法はありません、これはかなり古いenhancement requestですが、エンリケ・アブレウによってworkaround described originallyはかなりうまく動作しますが、私はすべての時間それを使用する...

スクリプト・エディタから呼び出される必要がある認証プロセスでは迷惑なことしか起こさず、共有アプリケーション(「スクリプトが使用できない」ユーザー)で使用するのが難しくなりますが、これは一度しか起こりません。

Romain Vialardによって作成されたLibraryもあります。これにより、作業が簡単になります。また、その他の興味深い機能がいくつか追加されています。

+2

私はあなたが@HenriqueAbreuから言及した回避策を検討してみたいが、リンクがノーでありますより長い利用可能:それは他の場所に公開されていますか? - ありがとう、Fausto –

+0

はい、私は知っている、彼らはアーカイブを一掃...とにかくコードはまだ多くの場所で見ることができます。これは、たとえばhttp://stackoverflow.com/questions/10954075/unexpected-exception-upon-serializing-continuationです。そして、問題追跡者にも。 –

+0

ありがとう、既にそれを使用しています –

-2

おそらくこれは、あなたのために働くだろう...

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

「DriveApp」とは何が見つかりましたか? –

+0

Romain Vialardのライブラリーを参照しましたか?それはあなたのコメントでそれを言及する必要がある場合 –

11

あなたはこのコードを試すことができます:ここでは

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); 
} 
1

は、によって投稿アイデア以下グール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 protected]", 
    subject: "document emailer", 
    htmlBody: docbody }); 
} 

が新たな問題を回避するには、

JD

1

のNode.jsソリューション

お役に立てば幸いです。ここは、Googleドライブの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をご覧ください。

Google APIs Node.js Clientはアルファ(2017年1月)であることに注意してください。

0

あなたはFILEID、GoogleドキュメントのIDとパスに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(); 
} 

ソリューションを使用することができ、高度なドライブサービスは指示に従ってくださいhere可能にします。

0

私もこの問題を抱えていました。ドキュメントのHTMLエクスポートが吐く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

関連する問題