Sep
Sep

Reputation: 382

Open an image in Google Docs

Just a little background: As you might know, if you have an image in Google drive and you try to open it with Google Docs, Google tries to extract the text within your image (OCR) and show the text alongside the image in a newly created Google Docs file.

I am writing a script and within that script I would like to open an image (with some text) with Google Docs.

When I try to do it through the following code, I just an Error message with no explanation on why it fails.

var file_url = file.getUrl();
try
{
    var doc = DocumentApp.openByUrl(file_url);
}catch (e) {
    Logger.log("Error Occurred: " + e.toString());
}

Any help would be appreciated.

Edit 1: Here is an actual scenario. I have the following .png image and I can open it with Google Docs.

enter image description here

When I open with Google Docs, I get the following document:

Document generated after opening the .png image with Google Doc.

Having the url of this .png file, I would like to do all this through my script so I can have the OCR generated text.

Upvotes: 3

Views: 3976

Answers (1)

Tanaike
Tanaike

Reputation: 201428

  • You want to convert a PNG file to Google Document by OCR using Google Apps Script.

If my understanding is correct, how about this modification? In this modification, Drive API is used.

When you use this script, please enable Drive API at Advanced Google Services and API console. You can see about this at here.

Modified script:

var fileId = "### file ID of PNG file ###";
var file = DriveApp.getFileById(fileId);
Drive.Files.insert(
  {title: file.getName(), mimeType: MimeType.GOOGLE_DOCS},
  file.getBlob(),
  {ocr: true}
);

Note:

  • When the URL of PNG file is like https://drive.google.com/file/d/#####/view?usp=sharing, ##### is the file ID.
  • In this modified script, the filename of created Document uses the filename of file retrieved by fileId. If you want to use other filename, please modify title: file.getName().

References:

Upvotes: 1

Related Questions