2010年7月30日金曜日

groovyとgdata-java-clientでGoogle Documents内の指定した名前のプレゼンテーションをPDFファイルにエクスポートする

groovyとgdata-java-clientでGoogle Documents内の指定した名前のプレゼンテーションをPDFファイルにエクスポートするには、以下のコードを実行します。

import com.google.api.client.googleapis.*
import com.google.api.client.googleapis.auth.clientlogin.*
import com.google.api.data.docs.v3.*
import com.google.api.data.docs.v3.atom.*
import com.google.api.client.xml.atom.*
import com.google.api.client.util.*

// エントリ
public class Entry
{
@Key
String title
@Key
String id
@Key("gd:resourceId")
String resourceId
}

// リンク
public class Link
{
@Key("@rel")
String rel
@Key("@type")
String type
@Key("@href")
String href
}

// フィード
public class Feed
{
@Key
String title
@Key
List<Link> link
@Key
List<Entry> entry
}

// Parser設定
GoogleTransport transport = new GoogleTransport()
transport.applicationName = "yourcorp-yourapp-1.0"
transport.setVersionHeader(GoogleDocumentsList.VERSION)
ap = new AtomParser()
ap.namespaceDictionary = GoogleDocumentsListAtom.NAMESPACE_DICTIONARY
transport.addParser(ap)

// 認証
cl = new ClientLogin()
cl.authTokenType = GoogleDocumentsList.AUTH_TOKEN_TYPE
cl.username = "youraccount@gmail.com"
cl.password = 'yourpassword'
cl.authenticate().setAuthorizationHeader(transport)

// 指定した名前のプレゼンテーションをPDFファイルにエクスポートする
docname = "サンプルプレゼンテーション1"
requrl = "https://docs.google.com/feeds/default/private/full/-/document" +
"?title=${URLEncoder.encode(docname, 'UTF-8')}&title-exact=true"
while(requrl != null){
request = transport.buildGetRequest()
request.url = requrl
feed = request.execute().parseAs(Feed.class)
println "feed title:" + feed.title
for(item in feed.entry){
// 指定した名前の文書が見つかったのでエクスポート
println item.title

// pdfファイルをダウンロード
request = transport.buildGetRequest()
request.url= "https://docs.google.com" +
"/present/export" +
"?id=${item.resourceId.substring(item.resourceId.indexOf(":")+1)}" +
"&format=pdf"
is = request.execute().getContent()

bos = new BufferedOutputStream(
new FileOutputStream("ダウンロードした${item.title}.pdf"))
buf = new byte[1024]
while((sz = is.read(buf, 0, 1024)) != -1){
bos.write(buf, 0, sz)
}
bos.flush()
bos.close()
}
// 100個以上の文書の場合
requrl = null
for(link in feed.link){
if( link.rel == "next" ){
requrl = link.href
}
}
}


動作環境
groovy 1.7.2, JDK6 Update20, gdata-java-2.2.1-alpha

関連情報
gdata-java-client
http://code.google.com/p/gdata-java-client/

0 件のコメント:

コメントを投稿