Error retrieving image from URL with SpreadsheetApp.newCellImage() builder - image

My application is trying to insert images to google drive sheet using google app script.
It works fine...
but it hang up intermittently with the response error from google script:
Exception: Error retrieving image from URL or bad URL:
https://drive.google.com/uc?id=1uvjg9_ZZg2sI5RYbPMEn6xXJhhnwuFyq&export=download.
The code is :
var fpm_mon_image = file_from_folder(id_folder_images , image_AR ) ; // get "image_AR" from folder
var url_mon_image = fpm_mon_image.getDownloadUrl() ;
var image = SpreadsheetApp.newCellImage().setSourceUrl(url_mon_image).setAltTextTitle(titre).toBuilder().build() ;
Utilities.sleep(1000); // for testing ...
SpreadsheetApp.flush();
Utilities.sleep(1000);
var rangeIma= fpm_sp.getRange(scal_li_SP +1, 2) ;
rangeIma.setValue(image).setVerticalAlignment('bottom') ; // stop here with error above
It works fine 5, 10 times then it hang up 2, 3, 5 times and then works fine again.... (I start loosing my hairs ;-))
I tried :
var srcfile = DriveApp.getFileById(id_mon_image);
srcfile.setSharing(DriveApp.Access.ANYONE_WITH_LINK, DriveApp.Permission.VIEW);
var image = fpm_sp.insertImage(srcfile.getBlob(), my_col , my_row);
but the image in not inserted in a cell...
Could you help please ?
Many thanks.

Unfortunately, I cannot replicate your situation of Exception: Error retrieving image from URL or bad URL:. So, although I'm not sure about your actual situation, how about the following modification?
Modified script:
Before you use this script, please enable Drive API at Advanced Google services.
var fileId = "###"; // Please set the file ID of your image.
var url = Drive.Files.get(fileId).thumbnailLink.replace(/\=s.+/, "=s512");
var title = "sample title";
var image = SpreadsheetApp.newCellImage().setSourceUrl(url).setAltTextTitle(title).build();
var sheet = SpreadsheetApp.getActiveSheet();
sheet.getRange("A1").setValue(image);
When this script is run, a thumbnail link is retrieved from the image file using Drive API. And, the image size of the image is changed. And, the image is put to the cell "A1" of the active sheet.
In this case, if the issue of image size occurs, this issue can be removed. And, if the issue of sharing the file occurs, this issue can be also removed. By this, I thought that your issue might be able to be removed.

Related

Google Advanced Drive API fails on insert of some PDFs but not others

function extractTextFromPDF() {
// PDF File URL
// You can also pull PDFs from Google Drive
// this Fall2019_LLFullCatalog.pdf will not insert - internal error on insert is all the feedback that gets logged"
// doesn't matter if I retrieve it from the university website or if I first copy it to my google drive and then retrieve it from there
//var url = "https://uwf.edu/media/university-of-west-florida/offices/continuing-ed/leisure-learning/docs/Fall2019_LLFullCatalog.pdf";
//var url = "https://drive.google.com/drive/u/0/my-drive/Fall2019_LLFullCatalog.pdf";
// both of these pdfs will insert just fine. Size is not the issue because this one is much larger than the one I need to insert
var url = "https://eloquentjavascript.net/Eloquent_JavaScript_small.pdf";
//var url = "https://img.labnol.org/files/Most-Useful-Websites.pdf";
var blob = UrlFetchApp.fetch(url).getBlob();
var size = blob.getBytes().length;
var resource = {
title: blob.getName(),
mimeType: blob.getContentType()
};
// Enable the Advanced Drive API Service
var file = Drive.Files.insert(resource, blob, {ocr: true, ocrLanguage: "en"});
// Extract Text from PDF file
var doc = DocumentApp.openById(file.id);
var text = doc.getBody().getText();
return text;
}
See comments in code above that describe the problem.
The PDF that I need to insert with OCR is not working - regardless of whether I retrieve it from the original site or retrieve a copy that I put on google drive. However, two other PDF urls will insert just fine and one of them is considerably larger than the one that fails.
What else could be the issue, if not size limitation?
Thanks,
Steve
It could very well be a bug in the Chrome API. Not all PDF software is created equal, check if the PDF can be read in Adobe Acrobat as a simple test.

Deleting images in Google sheet via script error

I probably will get downvoted for this but I can't do anything else. I searched, read and tried SOOOO many things. I am new at both Javascript and Google platform.
I have this piece of code that keeps telling me
"Missing name after . operation".
Even though .delete and .getAltTextTitle are both shown in autocomplete suggestion
var images = sheet.getImages();
var img = images[0];
Logger.log(img.getAltTextTitle()); //This is fine
img.delete(); //This throw error
In the meanwhile, I have this piece of code working totally fine. I don't know what to do. They look the same to me.
var img = sheet.getImages()[0];
var imgH = img.getHeight();
var imgW = img.getWidth();
var maxW = 700;
var newImgH = Math.round(imgH*(maxW/imgW));
img.setWidth(maxW);
img.setHeight(newImgH);
Unrelated topic, where do I get the documentation for sheet.getImages() because I just couldn't find it here
You want to delete the image on Spreadsheet using Google Apps Script.
If my understand is correct, I think that delete() might be new method which will be added for Spreadsheet in the near future. So the document is not updated and it might not complete yet. But from the error message, if you want to use the current delete() method, how about this sample script?
Sample script:
var images = sheet.getImages();
var img = images[0];
img["delete"](); // this one
Note:
I think that the detail infomation might be added to this document.
In my environment, I could confirm that the image can be deleted by img["delete"](). I think that this is one of new methods.
If I misunderstand your question, I'm sorry.
Update at 2018 October 13:
Now in order to delete the image, the following method can be used. This was confirmed at 2018 October 13.
var images = sheet.getImages();
var img = images[0];
img.remove(); // Here
Update at 2018 October 31:
This was officially released at October 30, 2018.
You can see the document at Class OverGridImage.

server error inserting image into google sheets

I continually get this error:
"We're sorry, a server error occurred. Please wait a bit and try again."
When trying to run the following code:
function insertSig(){
//get the folder
var sigFolder = DriveApp.getRootFolder().getFoldersByName("Signature").next()
//get the file
var sig = sigFolder.getFilesByName("Signature.png").next()
//get the blob data
var sigBlob = sig.getBlob();
//access the sheet
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet()
//insert image into sheet
sheet.insertImage(sigBlob, 1, 1)// throws error
}
I don't believe its an issue with the blob data as I have been able to log and print data from the blob and create a new file in other places on my google drive using the blob data.
I've also been able to access and edit other data on the spreadsheet.
I'm not sure what else to test/try and i'm quite stumped.
Thanks in advance,
-L
I figured out the issue.
After further testing with multiple locations and images, I found that the image was too big to be inserted.
I didn't test to find the max, but 1321 x 1002 was too big.
Regards,

PhantomJS - Rendering fails to show all images

I have a phantomjs script that is stepping through the pages of my site.
For each page, I use page = new WebPage() and then page.close() after finishing with the page. (This is a simplified description of the process, and I'm using PhantomJS version 1.9.7.)
While on each page, I use page.renderBase64('PNG') one or more times, and add the results to an array.
When I'm all done, I build a new page and cycle through the array of images, adding each to the page using <img src="data:image/png;base64,.......image.data.......">.
When done, I use page.render(...) to make a PDF file.
This is all working great... except that the images stop appearing in the PDF after about the 20th image - the rest just show as 4x4 pixel black dots
For troubleshooting this...
I've changed the render to output a PNG file, and have the same
problem after the 19th or 20th image.
I've outputted the raw HTML. I
can open that in Chrome, and all the images are visible.
Any ideas why the rendering would be failing?
Solved the issue. Turns out that PhantomJS was still preparing the images when the render was executed. Moving the render into the onLoadFinished handler, as illustrated below, solved the issue. Before, the page.render was being called immediately after the page.content = assignment.
For those interested in doing something similar, here's the gist of the process we are doing:
var htmlForAllPages = [];
then, as we load each page in PhantomJS:
var img = page.renderBase64('PNG');
...
htmlForAllPages.push('<img src="data:image/png;base64,' + img + '">');
...
When done, the final PDF is created... We have a template file ready, with all the required HTML and CSS etc. and simply insert our generated HTML into it:
var fs = require('fs');
var template = fs.read('DocumentationTemplate.html');
var finalHtml = template.replace('INSERTBODYHERE', htmlForAllPages.join('\n'));
var pdfPage = new WebPage();
pdfPage.onLoadFinished = function() {
pdfPage.render('Final.pdf');
pdfPage.close();
};
pdfPage.content = finalHtml;

Photoshop javascript save error 8800

In my javascript, in Windows 7, Photoshop CS2 & Photoshop CS5, it throws an error:
Error 8800: General Photoshop error occurred. This functionality may not be available in this version of Photoshop.
- Could not save a copy as "C:...\wcb-010B-11Y.jpg" because the file could not be found.
Line: 458
-> docRef.saveAs( saveFile, jpgSaveOptions, true, Extension.LOWERCASE );
here is a summary of the code to save the image:
var selectedSaveDir = "~/Desktop/";
var sFileNamePreFix = "wcb-";
var docRef = app.activeDocument;
var docName = app.activeDocument.name;
var docNewName = docName.substr( 0, docName.length - 4 ); // strip file extension
var sNewDocName = sFileNamePreFix + docNewName + ".jpg"
var sNewFileName = selectedSaveDir + sNewDocName;
//alert( "sNewFileName = " + sNewFileName ); // test to verify correct location
var saveFile = new File(sNewFileName);
jpgSaveOptions = new JPEGSaveOptions();
jpgSaveOptions.quality = 12;
docRef.saveAs(saveFile, jpgSaveOptions, true, Extension.LOWERCASE);
In Windows XP, this script works very well in CS2 with no problems.... just in Windows 7 is where this issue occurs using CS2 or CS5.
The problem seems to be similar to : Photoshop Javascript scripting saving and closing document
But I don't know his OS.
I've added the "alert(" and confirmed the save folder & name is correct and can be saved to, but same issue.
Could it be a UAC issue in Windows 7 ? and how do you Fix it ? I've turned off all UAC settings (I think I did it correctly), but it still occurs.
Any Help ?
You missed out " var docRef = app.activeDocument;" (which i've added); but apart from that, in CS2 the script saves out a jpeg to the desktop (wcb-text test.jpg). It's obvious, but have you made sure the image is flattened or doesn't contain any information that cannot be stored in a jpeg - like paths for example.
Try forcing a flatten before saving
//flatten the image
docRef.flatten();
Another thing to try is to save out the file to another directory. I know that long file names (especially with spaces in) can cause problems - I think there's a limit to 300 characters in the file path.
I just found that, in new versions of PS this particular path variable gives the error 8800:
var selectedSaveDir = "~/Desktop/";
Use full path instead and use apostrophes instead of quotes:
var selectedSaveDir = 'C:/Users/yourname/Desktop/';

Resources