3
votes

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.

1
In order to correctly understand about your situation, can I ask you about your issue? 1. About I would like to open an image (with some text) with Google Docs., do you want to insert an image to Google Document? About this, can you provide a sample result you want? 2. What is file_url of var doc = DocumentApp.openByUrl(file_url);?Tanaike
@Tanaike, I have updated my question to show what I need to achieve. The file_url is just a url of an image file in Google Drive.Sep
Thank you for replying and updating your question. I proposed a modified script. Could you please confirm it? If I misunderstood your question, I apologize.Tanaike

1 Answers

1
votes
  • 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: