Copy docs' content using Google Docs API

Viewed 248

I need to copy all content between an initial and a final index in Google Docs API in Python, despite if it is text, image, table, etc. I couldn't find any reference about copying contents regardless of the content type using Google Docs API. Does anyone know how can I implement it?

For example, suppose I want to duplicate the content below inside a Google Doc by copy and paste:

Lorem ipsum dolor sit amet,
[some-image]
[some-table]
consectetur adipiscing elit.

I want to have this output:

Lorem ipsum dolor sit amet,
[some-image]
[some-table]
consectetur adipiscing elit.

Lorem ipsum dolor sit amet,
[some-image]
[some-table]
consectetur adipiscing elit.

1 Answers

I have worked with 2 different options to do this:

Method 1

To copy a complete Google Doc, you can use the files().copy method of Drive API. Something like this:

copy_title = 'Copy Title'
body = {
    'name': copy_title
}
drive_response = drive_service.files().copy(
    fileId=document_id, body=body).execute()
document_copy_id = drive_response.get('id')

You can review and find a sample code in the answer to this post.

Note: You can use this method to copy a part of the document by making a complete copy of the file, and after that, edit the new copy of the document while keeping the original one unmodified. You can use batchUpdate for that

Method 2

You can use the documents.get method to get the content between an initial and a final index. Something like this:

try:
        service = build('docs', 'v1', credentials=creds)

        # Retrieve the documents contents from the Docs service.
        document = service.documents().get(documentId=DOCUMENT_ID).execute()

Note: If you use the documents.get you will get the raw data of the document. You will need to search for the "body" of the document. There you will see the content of the document with the parts of the document with their respective initial and a final index. After that, you can also use a batchUpdate to paste the information into a new document or the same document as on this case.

Reference:

Related