2013-02-02 6 views
7

Mi è venuta l'idea che potessi creare un blog per un amico utente non sofisticato utilizzando Documenti Google Drive per supportarlo. Sono stato in grado di creare un contentService che compila un elenco di documenti. Tuttavia, non riesco a vedere un modo per convertire il documento in HTML. So che Google può eseguire il rendering di documenti in una pagina Web, quindi mi chiedevo se fosse possibile ottenere una versione renderizzata per l'utilizzo nel mio servizio di contenuti.Ottieni il documento Google come HTML

È possibile?

risposta

3

Non v'è alcun metodo diretto a GAS per ottenere una versione HTML di un documento e questo è piuttosto un vecchio enhancement request ma il workaround described originally da Henrique Abreu funziona piuttosto bene, lo uso per tutto il tempo ...

Il unica cosa fastidiosa nel processo di autorizzazione che deve essere richiamato dall'editor di script che lo rende difficile da usare in un'applicazione condivisa (con utenti "script non in grado") ma ciò accade solo una volta;).

C'è anche un Library creato da Romain Vialard che rende le cose (un po ') più facili ... e aggiunge alcune altre interessanti funzioni.

+2

mi piacerebbe rivedere la soluzione che lei ha citato dal @HenriqueAbreu ma il link non è un più disponibile: è pubblicato altrove? - Grazie, Fausto –

+0

Sì, lo so, hanno cancellato gli archivi ... comunque il codice è ancora visibile in molti posti. Questo per esempio http://stackoverflow.com/questions/10954075/unexpected-exception-upon-serializing-continuation. E anche sul tracker dei problemi. –

+0

Grazie, già in uso –

-2

Forse questo dovrebbe funzionare per voi ...

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

Dove hai trovato qualcosa chiamato 'DriveApp'? –

+0

Hai fatto riferimento alla biblioteca di Romain Vialard? se è il caso, dovresti menzionarlo nel tuo commento –

11

Si può provare questo codice:

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

Qui è un po 'tagliò per la nuova versione di Goole Aouth seguendo l'idea pubblicato da 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; 

} 

e quindi utilizzare la solita mailApp:

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

auguriamo che il nuovo soluzione aiuta

JD

1

Node.js Soluzione

Ecco come è possibile ottenere un documento Google in formato HTML usando libreria client node.js di auto di 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); 
    }); 

Date un'occhiata al Google Drive V3 download docs per più lingue e opzioni.

Si noti che lo Google APIs Node.js Client è in alpha (gennaio 2017).

0

È possibile utilizzare la soluzione 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(); 
} 

Passo come fileId, l'id del documento google e ad attivare i servizi di trasmissione avanzati seguire le istruzioni here.

0

Ho avuto questo problema pure.Il codice HTML che il documento HTML Export sputa fuori è davvero brutto, quindi questa è stata la mia soluzione:

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