2013-02-02 14 views
7

Ich hatte eine wilde Idee, dass ich einen Website-Blog für einen einfachen Benutzer Freund mit Google Drive-Dokumenten erstellen könnte, um es zu unterstützen. Ich konnte einen contentService erstellen, der eine Liste von Dokumenten kompiliert. Ich sehe jedoch keine Möglichkeit, das Dokument in HTML zu konvertieren. Ich weiß, dass Google Dokumente auf einer Webseite rendern kann, also fragte ich mich, ob es möglich war, eine gerenderte Version für die Verwendung in meinem Content-Service zu bekommen.Get Google Dokument als HTML

Ist das möglich?

Antwort

3

Es gibt keine direkte Methode in GAS eine HTML-Version eines doc zu bekommen, und das ist schon ein altes enhancement request aber die workaround described originally von Henrique Abreu funktioniert ziemlich gut, ich benutze es die ganze Zeit ...

Die nur lästige Sache im Autorisierungsprozess, der vom Skripteditor aufgerufen werden muss, der es unruhig macht, in einer geteilten Anwendung (mit "skriptunfähigen" Benutzern) zu verwenden, aber dies geschieht nur einmal;).

Es gibt auch eine Library erstellt von Romain Vialard, die Dinge (ein bisschen) einfacher macht ... und fügt ein paar andere interessante Funktionen hinzu.

+2

Ich würde gerne die Abhilfe Sie von @HenriqueAbreu Bewertung erwähnt, aber die Verbindung ist nicht länger verfügbar: Wird es an anderer Stelle veröffentlicht? - Danke, Fausto –

+0

Ja ich weiß, sie haben die Archive ausgelöscht ... trotzdem ist der Code an vielen Stellen immer noch sichtbar. Dies zum Beispiel http://stackoverflow.com/questions/10954075/unexpected-exception-uponserializing-continuation. Und auch auf dem Problem Tracker. –

+0

Danke, es bereits verwendet –

-2

Vielleicht wäre dies für Sie arbeiten ...

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

Wo haben Sie DriveApp gefunden? –

+0

Haben Sie sich auf die Bibliothek von Romain Vialard bezogen? Wenn dies der Fall ist, sollten Sie dies in Ihrem Kommentar erwähnen –

11

Sie diesen Code versuchen:

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

Hier ist ein kleines snipped für die neue Version von goole Aouth den entsandten Idee gefolgt von Enrique:

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; 

} 

und dann mit dem üblichen mailApp:

function mailer(){ 
    var docbody = exportAsHTML(); 
    MailApp.sendEmail({ 
    to: "[email protected]", 
    subject: "document emailer", 
    htmlBody: docbody }); 
} 

Hoffe, dass die neue Umgehungs

JD

1

Node.js Lösung

Hier hilft, wie Sie ein Google-Dokument als HTML bekommen können Google-Laufwerk des node.js Client-Bibliothek.

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

Werfen Sie einen Blick auf die Google Drive V3 download docs für weitere Sprachen und Optionen.

Beachten Sie, dass die Google APIs Node.js Client in Alpha ist (Januar 2017).

0

können Sie die Lösung 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(); 
} 

Pass als fileId, die ID des Google-doc verwenden und fortschrittliche Antriebs Dienste die Anweisungen here folgen zu können.

0

Ich hatte dieses Problem auch.Der HTML-Code, das Dokument HTML-Export ausspuckt ist wirklich hässlich, so war dies meine Lösung:

/** 
* 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