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();
}
軽い解説
KEY
にGoogle APIs Consoleから取得したAPI KEYを設定し、
FILE_ID
にはDocumentsのID(URLのkey)を設定してください。
あとはOAuthして、Google Drive APIを利用してファイルのメタデータを取得、変換用のリンクを使って、HTMLバージョンを取得しています。
補足
- ちゃんとメソッド化してないけど許してください。
- 他の変換についてはこちらを参照してください。