Gists
This is a sample script for splitting an array by n elements using Google Apps Script.
Sample script 1:
var limit = 3;
var ar = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var res = [];
while (ar.length > 0) res.push(ar.splice(0, limit));
Logger.log(res); // [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0], [7.0, 8.0, 9.0], [10.0]]
Above sample script is a simple. But at Google Apps Script, the process cost of “while” is higher than the for loop as shown in this report. So I recommend the following sample script for Google Apps Script.
Gists
This is a sample script for overwriting several Google Documents by 2 text files using Google Apps Script.
Before you run this sample script, please install a GAS library of FetchApp.
As a sample situation, it supposes to overwrite 2 existing Google Documents by 2 text files using the method of files.update Drive API v3. In the current stage, the batch request of Drive API cannot use the file media. This sample script might become a workaround for updating files by quasi batching request with the asynchronous process.
Gists
This is a sample script for creating Google Document by converting PDF and image files with OCR using Google Apps Script.
Before you run this sample script, please install a GAS library of FetchApp.
function sample() {
var fileId = "### fileId of PDF file and image files ###";
var metadata = {
name: "sampleDocument", // Filename of created Google Document
mimeType: MimeType.GOOGLE_DOCS // MimeType of Google Document
};
var fileBlob = DriveApp.getFileById(fileId).getBlob();
var form = FetchApp.createFormData(); // Create form data
form.append(
"metadata",
Utilities.newBlob(JSON.stringify(metadata), "application/json")
);
form.append("file", fileBlob);
var url =
"https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart";
var params = {
method: "POST",
headers: { Authorization: "Bearer " + ScriptApp.getOAuthToken() },
body: form
};
var res = FetchApp.fetch(url, params);
Logger.log(res);
// DriveApp.createFile(blob) // This comment line is used for automatically detecting scope for running this sample script.
}
Overview
This is a GAS library for creating and requesting the type of multipart/form-data using Google Apps Script. This library enhances Class UelFetchApp of Google Apps Script.
Description
In order to fetch data from URL, there is Class UrlFetchApp in Google Apps Script. As the method for fetching, there is the method of fetch(url, params). In the current stage which was released this library, when user want to request with the type of multipart/form-data, the request body is required to be created by the user. But it is a bit difficult to create the request body. I thought that if the request body for the type of multipart/form-data can be easily created, it might be also useful for other users. So I created this as a GAS library.
Gists
This is a sample script for converting a lot of files to Google Docs (Spreadsheet, Document and Slides).
- Batch request can be used for converting files. In this sample script, the files are converted using the batch request.
- Batch request can request 100 API by one API call.
- This sample script uses the fetchAll method. So even if there are over 100 files, this script can process them.
Sample script:
Before you run the script, please set the variables at main(). And, please enable Drive API at Advanced Google services.
ImgApp was updated to v1.2.2.
You can see the detail information here https://github.com/tanaikech/ImgApp
Gists
When an image is inserted to Google Docs (Spreadsheet, Document and Slides) using the method of insertImage using Google Apps Script, there is the case that the error occurs. The error messages are “server error” and “invalid image data”. Here, I would like to introduce the limitations for inserting images to Google Docs. As the result, it was found that the limitation is due to both the mimeTypes and the area of image rather than the file size.
Gists
This is a sample Node.js script to retrieve access token from Service Account of Google without using googleapis.
const cryptor = require('crypto');
const request = require('request');
const privateKey = "###"; // private_key of JSON file retrieved by creating Service Account
const clientEmail = "###"; // client_email of JSON file retrieved by creating Service Account
const scopes = ["https://www.googleapis.com/auth/drive.readonly"]; // Sample scope
const url = "https://www.googleapis.com/oauth2/v4/token";
const header = {
alg: "RS256",
typ: "JWT",
};
const now = Math.floor(Date.now() / 1000);
const claim = {
iss: clientEmail,
scope: scopes.join(" "),
aud: url,
exp: (now + 3600).toString(),
iat: now.toString(),
};
const signature = Buffer.from(JSON.stringify(header)).toString('base64') + "." + Buffer.from(JSON.stringify(claim)).toString('base64');
var sign = cryptor.createSign('RSA-SHA256');
sign.update(signature);
const jwt = signature + "." + sign.sign(privateKey, 'base64');
request({
method: "post",
url: url,
body: JSON.stringify({
assertion: jwt,
grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer",
}),
}, (err, res, body) => {
if (err) {
console.log(err);
return;
}
console.log(body);
});
Gists
There are 2 sample scripts.
- Create new Spreadsheet using a text value as CSV data.
- Overwrite the existing Google Document using a text value.
When you use these script, please enable Drive API and retrieve your access token.
Create New Spreadsheet using Text Value
const request = require('request');
const textData = "a1, b1, c1, d1, e1"; // This is used as CSV data.
const orgMimeType = "text/csv";
const orgFileName = "sample.csv";
const accessToken = "###"; // Access token
const metadata = {
name: "convertedSampleCSV",
mimeType: "application/vnd.google-apps.spreadsheet",
};
const url = "https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart";
const boundary = "xxxxxxxxxxx";
var data = "--" + boundary + "\r\n";
data += "Content-Disposition: form-data; name=\"metadata\"\r\n";
data += "Content-Type: application/json; charset=UTF-8\r\n\r\n";
data += JSON.stringify(metadata) + "\r\n";
data += "--" + boundary + "\r\n";
data += "Content-Disposition: form-data; name=\"file\"; filename=\"" + orgFileName + "\"\r\n";
data += "Content-Type: " + orgMimeType + "\r\n\r\n";
var payload = Buffer.concat([
Buffer.from(data, "utf8"),
new Buffer(textData, 'binary'),
Buffer.from("\r\n--" + boundary + "--", "utf8"),
]);
const options = {
method: 'post',
url: url,
headers: {
"Content-Type": "multipart/related; boundary=" + boundary,
'Authorization': 'Bearer ' + accessToken,
},
body: payload,
};
request(options, (error, response, body) => {
console.log(body);
});
Overwrite Existing Google Document using Text Value
This can be used when you don’t want to update the existing Google Docs without changing the file ID.
Gists
This is a sample script for deleting the positioned images on Google Document using Google Apps Script. In the current stage, unfortunately, there are no methods for deleting the positioned images in Class PositionedImage, yet. But when Google Docs API is used, the positioned images can be deleted.
When you use this script, please enable Google Docs API at Advanced Google Services and API console. You can see how to enable them at here