2013-02-02 42 views
7

Tôi đã có một ý tưởng hoang dã rằng tôi có thể tạo một blog trang web cho một người bạn không sử dụng Google Drive Documents để sao lưu nó. Tôi đã có thể tạo một contentService để biên dịch một danh sách các tài liệu. Tuy nhiên, tôi không thể thấy cách chuyển đổi tài liệu thành HTML. Tôi biết rằng Google có thể hiển thị tài liệu trong một trang web, vì vậy tôi tự hỏi liệu có thể có được một phiên bản được hiển thị để sử dụng trong dịch vụ nội dung của tôi hay không.Tải Tài liệu Google dưới dạng HTML

Điều này có khả thi không?

Trả lời

3

Không có phương pháp trực tiếp tại GAS để có được một phiên bản HTML của một doc và điều này là khá một tuổi enhancement request nhưng workaround described originally bởi Henrique Abreu hoạt động khá tốt, tôi sử dụng nó mọi lúc ...

Các điều khó chịu nhất trong quá trình ủy quyền cần được gọi từ trình chỉnh sửa tập lệnh khiến bạn khó sử dụng trong ứng dụng được chia sẻ (với người dùng "tập lệnh không thể") nhưng điều này chỉ xảy ra một lần;).

Ngoài ra còn có một Library được tạo bởi Romain Vialard làm cho mọi thứ (một chút) dễ dàng hơn ... và thêm một vài chức năng thú vị khác.

+2

tôi rất muốn xem lại cách giải quyết mà bạn đề cập từ @HenriqueAbreu nhưng liên kết không còn có sẵn: là nó được xuất bản ở nơi khác? - Cảm ơn, Fausto –

+0

Vâng tôi biết, họ đã xóa sổ lưu trữ ... dù sao mã vẫn có thể xem được ở nhiều nơi. Điều này ví dụ http://stackoverflow.com/questions/10954075/unexpected-exception-upon-serializing-continuation. Và trên bộ theo dõi vấn đề là tốt. –

+0

Cảm ơn bạn, đã sử dụng nó –

-2

Có lẽ điều này sẽ làm việc cho bạn ...

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

Bạn tìm thấy bất cứ thứ gì có tên 'DriveApp' ở đâu? –

+0

Bạn đã tham khảo thư viện của Romain Vialard chưa? nếu đó là trường hợp bạn nên đề cập đến nó trong bình luận của bạn –

11

Bạn có thể thử mã này:

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

Đây là một Snipped chút cho phiên bản mới của goole AOuth sau ý tưởng đăng bởi 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; 

} 

và sau đó sử dụng thư thông thườngApp:

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

Hy vọng những cách giải quyết mới giúp

JD

1

Node.js Giải pháp

Đây là cách bạn có thể nhận được một doc google như html sử dụng thư viện client Node.js google của ổ đĩa.

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

Hãy xem Google Drive V3 download docs để biết thêm ngôn ngữ và tùy chọn.

Lưu ý rằng Google APIs Node.js Client ở dạng alpha (tháng 1 năm 2017).

0

Bạn có thể sử dụng giải pháp 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(); 
} 

đèo như fileId, id của google doc và cho phép các dịch vụ ổ đĩa tiên tiến làm theo hướng dẫn here.

0

Tôi cũng gặp sự cố này.HTML mà các tài liệu HTML Xuất spits ra là thực sự xấu xí, vì vậy đây là giải pháp của tôi:

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