LoginSignup
13

More than 5 years have passed since last update.

GASでDocumentsからHTMLへ変換する

Last updated at Posted at 2013-02-01

GASではDocumentsやSpreadsheetからpdfに変換可能なgetAsというメソッドがあります。

    var pdfBlob = SpreadsheetApp.getActive().getAs("application/pdf");

これはこれで便利なのですが、他のフォーマットに変えたい場合もあります。
しかし現在のところgetAsメソッドはpdfの変換しか対応していません。確か

なので今回はGoogle Drive APIを利用してDocumentsからHTMLに変換してみようと思います。

コード

var KEY = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'; //developer key , get from https://code.google.com/apis/console/b/1/ 
var FILE_ID = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'; // drive file id
function convertDocuments2() {

  var oauthConfig = UrlFetchApp.addOAuthService('drive');

  //Create oauth config for drive api
  var scope = 'https://www.googleapis.com/auth/drive';
  oauthConfig.setConsumerKey('anonymous');
  oauthConfig.setConsumerSecret('anonymous');
  oauthConfig.setRequestTokenUrl('https://www.google.com/accounts/OAuthGetRequestToken?scope='+scope);
  oauthConfig.setAuthorizationUrl('https://accounts.google.com/OAuthAuthorizeToken');    
  oauthConfig.setAccessTokenUrl('https://www.google.com/accounts/OAuthGetAccessToken');  
  //1gC166L6sjPzhKlZB-ux2L7wsqnYn5eZ_bqbe5BjgwSM
  var param = {
    method:'get',
    oAuthServiceName: 'drive',
    oAuthUseToken: 'always',
  };

  //Get file 
  var res = UrlFetchApp.fetch('https://www.googleapis.com/drive/v2/files/' + FILE_ID + '?fields=exportLinks&key='+KEY, param);

  //this response body format is json , and it has file id. Please see https://developers.google.com/drive/v2/reference/files#resource
  var fileDataResponse = JSON.parse(res.getContentText());

  var res = UrlFetchApp.fetch(fileDataResponse.exportLinks["text/html"] + "&key=" + KEY,param);

  return res.getContentText();

}

軽い解説

KEYGoogle APIs Consoleから取得したAPI KEYを設定し、
FILE_IDにはDocumentsのID(URLのkey)を設定してください。

あとはOAuthして、Google Drive APIを利用してファイルのメタデータを取得、変換用のリンクを使って、HTMLバージョンを取得しています。

補足

  • ちゃんとメソッド化してないけど許してください。
  • 他の変換についてはこちらを参照してください。

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13