Search code examples
google-apps-scriptgoogle-docs

Batch convert jpg to Google Docs


I have a folder of jpgs in Google Drive that I would like to convert to Google Docs. Now I can select each one manually and in the context menu "Open in Google Docs" This creates a new document with the image at the top of the page and OCR text below. I just want to do this with all my images.

There is a script here which converts gdoc to docx which I ought to be able to adapt for my case but I don't seem to be able to get it to work.

Here is my adapted script:

function convertJPGtoGoogleDocs() {
  var srcfolderId = "~~~~~~~~~Sv4qZuPdJgvEq1A~~~~~~~~~"; // <--- Please input folder ID.
  var dstfolderId = srcfolderId; // <--- If you want to change the destination folder, please modify this.
  var files = DriveApp.getFolderById(srcfolderId).getFilesByType(MimeType.JPG);
  while (files.hasNext()) {
    var file = files.next();
    DriveApp.getFolderById(dstfolderId).createFile(
      UrlFetchApp.fetch(
        "https://docs.google.com/document/d/" + file.getId() + "/export?format=gdoc",
        {
          "headers" : {Authorization: 'Bearer ' + ScriptApp.getOAuthToken()},
          "muteHttpExceptions" : true
        }
      ).getBlob().setName(file.getName() + ".docx")
    );
  }
}

Can anyone help?

Thanks.


Solution

    • You want to convert Jpeg files in a folder as Google Document.
    • When the Jpeg file is converted to Google Document, you want to use OCR.

    If my understanding is correct, how about this modification?

    Modification points:

    • In the script you modified, MimeType.JPG returns undefined. So the script in while is not run.
      • Please use MimeType.JPEG.
    • The script of this answer is used for exporting Google Document as Microsoft Word. Unfortunately, that script cannot be directly used for converting Jpeg file to Google Document.

    If you want to modify the script of this answer, how about modifying as follows?

    When you use this script, please enable Drive API at Advanced Google Services. By this, the API is automatically enabled at API console. The specification of Google Apps Script Project was Changed at April 8, 2019.

    Modified script:

    function convertJPGtoGoogleDocs() {
      var srcfolderId = "~~~~~~~~~Sv4qZuPdJgvEq1A~~~~~~~~~"; // <--- Please input folder ID.
      var dstfolderId = srcfolderId; // <--- If you want to change the destination folder, please modify this.
      var files = DriveApp.getFolderById(srcfolderId).getFilesByType(MimeType.JPEG); // Modified
      while (files.hasNext()) {
        var file = files.next();
        Drive.Files.insert({title: file.getName(), parents: [{id: dstfolderId}]}, file.getBlob(), {ocr: true}); // Modified
      }
    }
    

    Note:

    References:

    If I misunderstand your question, please tell me. I would like to modify it.