Is there a way to replace URL Link of Text in Google Docs API?

爷,独闯天下 提交于 2021-01-01 07:34:04

问题


I started exploring Google Docs API in Python. It does pretty much everything I want it to do except for one thing.

I can replace the text of a document but I can't change the value of the hyperlinks.

Meaning if a link looks like this : a link, I can change the value of the text a link but not the target URL.

I've been going through the documentation but I can't find anything about it. Could it be a missing feature or am I missing the way to do that?


回答1:


You can modify the hyperlink using UpdateTextStyleRequest of the batchupdate method in Google Docs API. At this time, please set the property of Link of TextStyle.

Endpoint

POST https://docs.googleapis.com/v1/documents/{file ID}:batchUpdate

Request body:

{
 "requests": [
  {
   "updateTextStyle": {
    "textStyle": {
     "link": {
      "url": "https://sampleUrl"  # Please set the modified URL here.
     }
    },
    "range": {
     "startIndex": 1,
     "endIndex": 2
    },
    "fields": "link"
   }
  }
 ]
}

Note:

  • From your question, I could understand that you have already used Google Docs API and you can modify the text of the link text. I think that you can modify the link using above request body and the script you have.

References:

  • UpdateTextStyleRequest
  • TextStyle
  • Link

If this was not useful for your situation, I apologize.

Edit:

  • You want to retrieve the text with the hyperlink.

From your reply comment, I could understand like above. When my understanding is correct, you can retrieve it using documents.get method. In this case, when fields is used, the response become to easily read.

Endpoint:

GET https://docs.googleapis.com/v1/documents/{file ID}?fields=body(content(paragraph(elements(endIndex%2CstartIndex%2CtextRun(content%2CtextStyle%2Flink%2Furl)))))
  • In this endpoint, body(content(paragraph(elements(endIndex,startIndex,textRun(content,textStyle/link/url))))) is used as fields.

Sample response:

For example, when the following texts are put in a Google Document and def has a hyperlink,

abc
def

The response is as follows. From the following result, you can retrieve the position of text with the hyperlink can be retrieved. Using this, you can modify the hyperlink.

{
  "body": {
    "content": [
      {},
      {
        "paragraph": {
          "elements": [
            {
              "startIndex": 1,
              "endIndex": 5,
              "textRun": {
                "content": "abc\n",
                "textStyle": {}
              }
            }
          ]
        }
      },
      {
        "paragraph": {
          "elements": [
            {
              "startIndex": 5,
              "endIndex": 8,
              "textRun": {
                "content": "def",
                "textStyle": {
                  "link": {
                    "url": "https://sample/"
                  }
                }
              }
            },
            {
              "startIndex": 8,
              "endIndex": 9,
              "textRun": {
                "content": "\n",
                "textStyle": {}
              }
            }
          ]
        }
      }
    ]
  }
}

Reference:

  • documents.get



回答2:


batchUpdate requires to know position of text, we can get document with all content and find positions of links

In my case I implement it as:

  1. Copy template to new place with final name
  2. Replace link texts and other parts of text
  3. Get document
  4. Find links positions in doc
  5. Update link URLs

Here example in nodejs

const {google, docs_v1} = require('googleapis');

async function replaceInDoc(doc) {
  let documentId = 'some doc id'
  let auth = 'auth value for user'
  let linkNewUrl = 'https://github.com/googleapis/google-api-nodejs-client'

  google.options({auth: auth})
  var docs = new docs_v1.Docs({}, google)

  // document should have link with http://repo-url.com text, we will update it

  var requests = [
    {
      replaceAllText: {
        containsText: {
          text: 'http://repo-url.com',
          matchCase: true,
        },
        replaceText: linkNewUrl,
      },
    }
  ]

  var updateRes = await docs.documents.batchUpdate({
    documentId: documentId,
    resource: {
      requests: requests,
    },
  });

  var docInfo = await docs.documents.get({documentId: documentId})
  var linkPos = findLinksInDoc(docInfo)

  // set new url to link by position of link in the document
  var requests = [
    {
      updateTextStyle: {
        textStyle: {
          link: {
            url: linkNewUrl
          }
        },
        range: {
          startIndex: linkPos[linkNewUrl][0],
          endIndex: linkPos[linkNewUrl][1]
        },
        fields: "link"
      }
    }
  ]

  var updateRes = await docs.documents.batchUpdate({
    documentId: documentId,
    resource: {
      requests: requests,
    },
  });
}

// returns hash as { 'http://example.com': [startPosition, endPosition] }
function findLinksInDoc(doc) {
  var links = {}

  doc.data.body.content.forEach(section => {
    if (section.paragraph) {
      section.paragraph.elements.forEach(element => {
        if (element.textRun && element.textRun.textStyle.link) {
          links[element.textRun.content] = [element.startIndex, element.endIndex]
        }
      })
    }
  })

  return links
}


来源:https://stackoverflow.com/questions/55538289/is-there-a-way-to-replace-url-link-of-text-in-google-docs-api

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!