My objective is to.
- fetch a base64 image string from a google doc
- save it to the drive as an image
- getblob from image and insert the new image into the same doc as a real image.
function getImage(doc) {
var tempBase64 = doc.getBody().getParagraphs()[doc.getBody().getParagraphs().length - 1].getText();
var base64 = tempBase64.replace("data:image/svg+xml;base64,", "");
var decoded = Utilities.base64Decode(base64);
return decoded;
}
function run() {
var doc = DocumentApp.getActiveDocument();
var img = getImage(doc); //returns decoded blob
var body = DocumentApp.getActiveDocument().getBody();
//gets the name of the current doc
var filename = DriveApp.getFileById(DocumentApp.getActiveDocument().getId());
var blobImg = Utilities.newBlob(img, MimeType.SVG, filename);
var currentFolder = DriveApp.getFolderById("1UuP2vZNXLVtgrZxAHLSNZUqVnx0xeSgW");
//saves image as same name
var newimg = currentFolder.createFile(blobImg).getId();
//wait for image to save
Utilities.sleep(5 * 1000);
// get blob
var blob = DriveApp.getFileById(newimg).getBlob();
var cursor = doc.getCursor();
if (cursor) {
//insert in to doc
cursor.insertInlineImage(blob);
}
}
function onOpen() {
run();
}
Currently it's reading the doc and fetching the base64 string ✓ eg:
image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+PCFET0NUWVBFIHN2ZyBQVUJMSUMgIi0vL1czQy8vRFREIFNWRyAxLjEvL0VOIiAiaHR0cDovL3d3dy53My5vcmcvR3JhcGhpY3MvU1ZHLzEuMS9EVEQvc3ZnMTEuZHRkIj48c3ZnIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgdmVyc2lvbj0iMS4xIiB3aWR0aD0iMTIiIGhlaWdodD0iMTUiPjxwYXRoIHN0cm9rZS1saW5lam9pbj0icm91bmQiIHN0cm9rZS1saW5lY2FwPSJyb3VuZCIgc3Ryb2tlLXdpZHRoPSIyIiBzdHJva2U9InJnYigwLCAwLCAxMzkpIiBmaWxsPSJub25lIiBkPSJNIDEgMyBsIDEgNCIvPjxwYXRoIHN0cm9rZS1saW5lam9pbj0icm91bmQiIHN0cm9rZS1saW5lY2FwPSJyb3VuZCIgc3Ryb2tlLXdpZHRoPSIyIiBzdHJva2U9InJnYigwLCAwLCAxMzkpIiBmaWxsPSJub25lIiBkPSJNIDggMSBsIDEgMSIvPjxwYXRoIHN0cm9rZS1saW5lam9pbj0icm91bmQiIHN0cm9rZS1saW5lY2FwPSJyb3VuZCIgc3Ryb2tlLXdpZHRoPSIyIiBzdHJva2U9InJnYigwLCAwLCAxMzkpIiBmaWxsPSJub25lIiBkPSJNIDMgMTAgYyAwLjAyIDAuMDcgMC4zMSAzLjU0IDEgNCBjIDAuODQgMC41NiAzLjg5IDAuNDcgNSAwIGMgMC44IC0wLjM0IDIgLTMgMiAtMyIvPjwvc3ZnPg==
It's saving as an image in a particular folder ✓
It's returning the id of the new image.✓
It's getting the image as a blob ✓
When it comes to inserting the image, i'm getting Invalid image data. (line 20, file "Code"). Literally no idea how to resolve. Anyone help?