Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to inline/add a non-publicly accessible image to a Google Doc using the Docs API?

Looking at the API guide here https://developers.google.com/docs/api/how-tos/images, the banner states that "The image must be publicly accessible using the URL that you provide in this method."

Is there any other way that I can add/inline a non-public image to a Google Doc through the API?For example, if I have an image stored in my Drive, or image byte data that is in the scope of the code.

like image 764
adadadcs Avatar asked Sep 10 '25 15:09

adadadcs


1 Answers

As mentioned in other answers, this is currently not possible using the Google Docs API.

However, after having struggled with the Docs API for a couple of days now, I finally have come to the following realizations:

  • Instead of using the Google Docs API, you can use the Google Drive API to upload HTML content as a Google Doc. This is what it looks like using Node.js:

    const response = drive.files.create({
      resource: {
        name: this.name,
        mimeType: 'application/vnd.google-apps.document'
      },
      media: {
        mimeType: 'text/html',
        body: '<html><body>... your HTML ...</body></html>'
      },
      fields: 'id'
    });
    
    const documentId = response.data.id;
    const documentUrl = `https://docs.google.com/document/d/${documentId}`;
    
  • Instead of uploading the images separately to Google Drive and trying to link them, you can just encode them as data URIs and insert them directly into your HTML content. Google Docs will retain them, and they will be correctly included in your document.
  • It is a lot easier to just generate HTML than to create content using the Google Docs API (especially keeping track of the location indexes is a pain).

So far, for my use case, this works flawlessly with only some minor drawbacks:

  • Google Docs picks up heading styles (h1-h6) correctly and displays the headers in the outline and table of contents (should you generate one). However, I have yet to figure out how to style the title and subtitle elements for Google Docs to recognize them as such.
  • The table of contents itself can only be generated from within Google Docs or using the Google Docs API, so that's an extra step.
like image 185
Robby Cornelissen Avatar answered Sep 13 '25 10:09

Robby Cornelissen