Create PDF from Google Sheets with Drive API
Apps ScriptのurlFetchでPDFを出力するときに使う方法だけど、node(typeScript)でやってみた。 Google Driveの folderに入れて、urlを渡す方式もやりたいが、、
その場合は、localに落としたPDFを、google driveにupload して、そして urlを渡す? なにか違うような...
googleが提供してる Drive APIだと、size, fitw, gid(シートのid)などの指定ができない? csvの話だけど....
code: download.ts
import { google } from "googleapis";
import axios from 'axios'
import fs from 'fs'
async function main() {
// The getClient method will choose a service based authentication model
const auth = new google.auth.GoogleAuth({
keyFile: "/home/xxxx/dev/x/.secret/secret.json",
});
const client = await auth.getClient()
const token = await client.getAccessToken()
console.log(token.token)
const url = https://docs.google.com/spreadsheets/d/xxx/export?exportFormat=pdf&format=pdf&size=A4&fitw=true&gid=873677247
const res = await axios.get(url, {
responseType: 'arraybuffer',
headers: { Authorization: Bearer ${token.token} }
})
fs.writeFileSync("out.pdf", res.data)
}
main().catch(console.error);
特定のgoogle sheetのsheet(gidで指定)
ここでは、service accountのkeyfileで認証してるので、そのservice accountの メールアドレスを対象のgoogle sheetで権限渡す
responseType: 'arraybuffer' を指定する。これが正解かは不明だけど... requestの指定で変わるのだろうか???
typeScriptだけど、ほとんど型指定がない....
module形式、esmでやりたい。それで、ts-nodeで実行したいが、そのままだとできない?ので、