0

Get Document as Text

by
Published today

Get a Google Doc's title and body as plain text.

Script gdocs Verified

The script

Submitted by hugo989 Typescript (fetch-only)
Verified 4 hours ago
1
//native
2

3
/**
4
 * Get Document as Text
5
 * Get a Google Doc's title and its body as plain text (paragraphs and table cells, in reading order). Only the first tab of a multi-tab document is read.
6
 */
7
export async function main(auth: RT.Gdocs, document_id: string) {
8
  const response = await fetch(
9
    `https://docs.googleapis.com/v1/documents/${document_id}`,
10
    {
11
      headers: {
12
        Authorization: `Bearer ${auth.token}`,
13
        Accept: "application/json",
14
      },
15
    }
16
  )
17
  if (!response.ok) {
18
    throw new Error(`${response.status} ${await response.text()}`)
19
  }
20

21
  const doc = await response.json()
22
  return {
23
    document_id: doc.documentId,
24
    title: doc.title,
25
    text: toText(doc.body?.content ?? []),
26
  }
27
}
28

29
function toText(content: any[]): string {
30
  let text = ""
31
  for (const el of content) {
32
    for (const e of el.paragraph?.elements ?? [])
33
      text += e.textRun?.content ?? ""
34
    for (const row of el.table?.tableRows ?? [])
35
      for (const cell of row.tableCells ?? [])
36
        text += toText(cell.content ?? [])
37
    if (el.tableOfContents) text += toText(el.tableOfContents.content ?? [])
38
  }
39
  return text
40
}
41