LoginSignup
1
1

More than 3 years have passed since last update.

Node.jsでGoogle Slides内のテキストを取得してみる

Last updated at Posted at 2020-02-08

Node.jsでGoogle Slides APIを触ってみるの続きです。

準備

前回の記事を参照して、スライド情報にNode.jsからアクセス出来るようにしましょう。

適当なスライドを用意する

こちらを用意してみました。

https://docs.google.com/presentation/d/<ここがプレゼンテーションID>/edit#slide=id.pになるのでこのスライドのプレゼンテーションIDは1ziVnaFocZ_YF_cuXyXF5PUKGoE62eX-XlnOEslPkKUcになります。

Node.jsでGoogle Slidesのテキストを抽出

前回のコードからプレゼンテーションIDの箇所とfunction listSlides(auth)の中身を書き換えてます。

app.js
const fs = require('fs');
const readline = require('readline');
const {google} = require('googleapis');

//変更箇所: プレゼンテーションID - 試すときは自分のスライドでもやってみましょう
const presentationId = `1ziVnaFocZ_YF_cuXyXF5PUKGoE62eX-XlnOEslPkKUc`;

// If modifying these scopes, delete token.json.
const SCOPES = ['https://www.googleapis.com/auth/presentations.readonly'];
// The file token.json stores the user's access and refresh tokens, and is
// created automatically when the authorization flow completes for the first
// time.
const TOKEN_PATH = 'token.json';

// Load client secrets from a local file.
fs.readFile('credentials.json', (err, content) => {
  if (err) return console.log('Error loading client secret file:', err);
  // Authorize a client with credentials, then call the Google Slides API.
  authorize(JSON.parse(content), listSlides);
});

/**
 * Create an OAuth2 client with the given credentials, and then execute the
 * given callback function.
 * @param {Object} credentials The authorization client credentials.
 * @param {function} callback The callback to call with the authorized client.
 */
function authorize(credentials, callback) {
  const {client_secret, client_id, redirect_uris} = credentials.installed;
  const oAuth2Client = new google.auth.OAuth2(
      client_id, client_secret, redirect_uris[0]);

  // Check if we have previously stored a token.
  fs.readFile(TOKEN_PATH, (err, token) => {
    if (err) return getNewToken(oAuth2Client, callback);
    oAuth2Client.setCredentials(JSON.parse(token));
    callback(oAuth2Client);
  });
}

/**
 * Get and store new token after prompting for user authorization, and then
 * execute the given callback with the authorized OAuth2 client.
 * @param {google.auth.OAuth2} oAuth2Client The OAuth2 client to get token for.
 * @param {getEventsCallback} callback The callback for the authorized client.
 */
function getNewToken(oAuth2Client, callback) {
  const authUrl = oAuth2Client.generateAuthUrl({
    access_type: 'offline',
    scope: SCOPES,
  });
  console.log('Authorize this app by visiting this url:', authUrl);
  const rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout,
  });
  rl.question('Enter the code from that page here: ', (code) => {
    rl.close();
    oAuth2Client.getToken(code, (err, token) => {
      if (err) return console.error('Error retrieving access token', err);
      oAuth2Client.setCredentials(token);
      // Store the token to disk for later program executions
      fs.writeFile(TOKEN_PATH, JSON.stringify(token), (err) => {
        if (err) return console.error(err);
        console.log('Token stored to', TOKEN_PATH);
      });
      callback(oAuth2Client);
    });
  });
}

/**
 * Prints the number of slides and elements in a sample presentation:
 * https://docs.google.com/presentation/d/1EAYk18WDjIG-zp_0vLm3CsfQh_i8eXc67Jo2O9C6Vuc/edit
 * @param {google.auth.OAuth2} auth The authenticated Google OAuth client.
 * 
 */
function listSlides(auth) {
  const slides = google.slides({version: 'v1', auth});
  slides.presentations.get({
    presentationId: presentationId,
  }, (err, res) => {
    if (err) return console.log('The API returned an error: ' + err);

    /* 変更箇所: スライド中のテキストを抽出するテスト */
    const firstPage = res.data.slides[0]; //1スライド目
    const firstBox = firstPage.pageElements[0]; //最初の要素
    console.log(firstBox.shape.text.textElements[1].textRun.content); //中身のテキスト確認
  });
}

素でアクセすると

res.data.slides[0].pageElements[0].shape.text.textElements[1].textRun.content

みたいな感じで超深い階層になるみたいです。

  • res.data.slides: スライドXXページごとの配列 今回はタイトルスライドから抜き出すので0指定
  • firstPage.pageElements: 対象ページのオブジェクト(テキストボックスなど)の配列 今回はページの最初の部ジェクトなので0指定

実行

$ node app.js 
Node.jsてすと

ちゃんとテキストがとれましたね。

所感

返ってくるオブジェクトが結構複雑な印象です。

詳細はslides周りのSDKを覗くのが良さそうだけどどんなオブジェクトが返ってくるかはまだ見つけられてないのでconsole.logで探していったほうが早いかも

追記: 今回使ってるpresentations.getのAPIリファレンスはここっぽい

https://developers.google.com/slides/reference/rest/v1/presentations/get

1
1
0

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
1
1