Convert a specific google sheets tab into a pdf - javascript

For a project I am currently working on I'm trying to find a way that lets me turn a specific google sheets tab into a pdf using javascript

You have to put your own id in this script
function savePDF(){
const docID = '______id of the spreadsheet________';
const feuilleID = '___id of the sheet______';
const dossier = DriveApp.getFolderById('______id of the folder_______');
const fichier = 'name of the file.pdf'
const url = 'https://docs.google.com/spreadsheets/d/' + docID + '/export?';
const exportOptions =
'exportFormat=pdf&format=pdf' +
'&size=A4' +
'&portrait=true' +
'&fitw=false' +
'&sheetnames=false&printtitle=false' +
'&pagenumbers=false&gridlines=false' +
'&fzr=false' +
'&gid=' + feuilleID;
var params = {method:"GET",headers:{"authorization":"Bearer "+ ScriptApp.getOAuthToken()}};
var reponse = UrlFetchApp.fetch(url + exportOptions, params).getBlob();
dossier.createFile(reponse.setName(fichier));
}

Related

How to get my Google App Script to skip an error and go to the next item

Help Needed...
I have a script that basically sends out multiple emails (reports) to various recipients. However, when there is an error with a recipient's email address the script stops (eg if no email address is provided or an invalid email address for a recipient).
I need help in putting a line(s) of code that tells the script to skip over the one with the error and continue on to the next recipient.
I would appreciate any guidance provided.
Respectfully, Kareem
This is the code below...
function emailALL() {
var ui = SpreadsheetApp.getUi();
var response = ui.alert('Confirm', 'Are you sure you want to email all the reports for this
class?', ui.ButtonSet.YES_NO);
if (response == ui.Button.YES) {
const ss = SpreadsheetApp.getActiveSpreadsheet();
const studentTerm = ss.getSheetByName("Student Report");
const sheetId = studentTerm.getSheetId();
const sheet = ss.getSheetByName("Marks Master");
const students = sheet.getRange("Ao2:Ao41").getValues();
var loopCount= sheet.getRange("Ao1").getValues();
var url_base = "https://docs.google.com/spreadsheets/d/" + ss.getId() + "/";
let url = ss.getUrl();
url += '#gid=';
url += sheetId;
Logger.log("Url: ", url);
ss.setActiveSheet(studentTerm);
for(var i=0; i<loopCount +1; i++){
ss.getRange('C7').setValue(students[i]);
// const sheet = ss.getRange(1, 1, 46, 16);
// Subject of the email message
const words = ss.getRange('C7');
const title = words.getValues()[0];
const term = ss.getRange("D9");
const terms = term.getValues()[0];
const email = ss.getRange('c3').getValues()[0];
const school = ss.getRange('C1').getValues()[0];
const subject = school + ": " + title + "_Term_"+ terms +" Report";
const motto = ss.getRange('C2').getValues()[0];
const body = "Good day Parent/Guardian, \n\nPlease find attached, school term report for " + title + "."+ "\n\nRegards, \n" + school + "\n" + motto + "\n";
//"Good day Parent/Guardian," & vbLf & vbLf _
// & "Please find attached, " & Title & "'s School Term Report." & vbLf & vbLf _
// & "Regards," & vbLf _
//& School & vbLf _
// & Motto & vbLf
// Email Text. You can add HTML code here - see ctrlq.org/html-mail
// let sheet = ss.getSheetName("Student-Term");
// const unformattedUrl = studentTerm.getUrl();
// Logger.log("SpreadSheet Url " + unformattedUrl);
// let formattedUrl = unformattedUrl.split("/");
// formattedUrl = formattedUrl.slice(0, formattedUrl.length - 1);
// formattedUrl = formattedUrl.join("/");
// formattedUrl = formattedUrl + "/export?";
const exportOptions ='export?exportFormat=pdf&format=pdf' //export as pdf
// Print either the entire Spreadsheet or the specified sheet if optSheetId is provided
+ (sheetId ? ('&gid=' + sheetId) : ('&id=' + spreadsheetId))
// following parameters are optional...
+ '&size=letter' // paper size
+ '&portrait=true' // orientation, false for landscape
+ '&fitw=false' // fit to width, false for actual size
+ '&sheetnames=false&printtitle=false&pagenumbers=true' //hide optional headers and footers
+ '&gridlines=false' // hide gridlines
+ '&fzr=false'; // do not repeat row headers (frozen rows) on each page
var params = {method:"GET",headers:{"authorization":"Bearer "+ ScriptApp.getOAuthToken()}};
Logger.log(url+exportOptions);
var response = UrlFetchApp.fetch(url_base+exportOptions, params);
var blob = response.getBlob().setName(title + '.pdf')
var mailOptions = {
attachments:blob
}
//var pdfFile = ss.getBlob().getAs('application/pdf').setName("Pdf1");
//// Send the PDF file as an attachement
GmailApp.sendEmail(email, subject, body, mailOptions);
Utilities.sleep(1000)
}
}
else {}
}
After
const email = ss.getRange('c3').getValues()[0];
add
if(email === '') continue;
The above will handle those cases where the cell used to enter the email is blank (empty). A simple way to handle all other cases is by using try .. catch
Replace
GmailApp.sendEmail(email, subject, body, mailOptions);
by
try {
GmailApp.sendEmail(email, subject, body, mailOptions);
} catch(error) {
console.log(error.message, error.stack);
continue;
}
For a more sophisticated approach take a checkout What's the best way to validate an email address in JavaScript?
References
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/continue
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch
Related
-

I Got A Problam In Whatsapp Sharing Using Javascript

i have a button when i click on this button then whatsapp opens and when i click in a chat and want to send massege then all things come properly but full url not come because & included in my url.
My Url is like this
www.yoururl.com?1st=1&2nd=2&3rd=2&4th=1&5th=2&6th=2&7th=2&8th=2&9th=2&10th=2&share=share&name=s
But sharing in whatsapp then comes only
www.yoururl.com?1st=1
when i remove first & Then url is comes
www.yoururl.com?1st=12nd=2
so i want to share full url with &
Here Is javascript code Code
var url1 = "?1st=" + encodeURIComponent(selectedOption1) + "&2nd=" + encodeURIComponent(selectedOption2) + "&3rd=" + encodeURIComponent(selectedOption3) + "&4th=" + encodeURIComponent(selectedOption4) + "&5th=" + encodeURIComponent(selectedOption5) + "&6th=" + encodeURIComponent(selectedOption6) + "&7th=" + encodeURIComponent(selectedOption7) + "&8th=" + encodeURIComponent(selectedOption8) + "&9th=" + encodeURIComponent(selectedOption9) + "&10th=" + encodeURIComponent(selectedOption10);
section3.style.display="none";
section4.style.display="block";
var u = "www.yoururl.com";
var input = document.getElementById("1nameInput").value;
var inputt = document.getElementById("copytxt");
var inputname = "&name=";
var share = "&share=share";
var text = u + url1 + share + inputname + input;
inputt.value = text;
var $whatsApp = $('.whatsapp a');
decorateWhatsAppLink(text, input);
function decorateWhatsAppLink(text, input) {
// Getting user input
var message = "text";
// Opening URL
var url = 'whatsapp://send?text=';
//define the message text
var textttt = 'dare take this Challenge Now ';
//encode the text
//find the link
var $whatsApp = $('.whatsapp a');
//set the href attribute on the link
$whatsApp.attr('href', url + input + textttt + text);
}
url come from text variable
please tell me how to do
use encodeURIComponent on the whole URI not only the parameter values
so that & gets encoded as well ...
foo = "www.yoururl.com?1st=1&2nd=2&3rd=2&4th=1&5th=2&6th=2&7th=2&8th=2&9th=2&10th=2&share=share&name=s"
foo_final = encodeURIComponent(foo);

Web Firebase Get Download URL of image from Storage to Display in Table

I want to download the image from the Firebase storage, but I want it to be a button in a table, but I am not sure how to do that? Below is my JS:
var email = sessionStorage.getItem("email");
var rootRef = firebase.database().ref().child("users");
rootRef.on("child_added", snap => {
var medname = snap.child("MedName").val();
var description = snap.child("description").val();
var end = snap.child("End").val();
var start = snap.child("Start").val();
var type = snap.child("Type").val();
var file = snap.child("fileName").val();
var storageRef = firebase.storage.ref("users/file");
storageRef.getDownloadURL().then(function(url) {
window.alert(url);
});
$("#demo").append("<tr><td>"+ medname +"</td><td>" + description +
"</td><td>"+ type + "</td><td>" + start +
"</td><td>" + end +"</td><td></td></tr>");
});
The name of the file gets saved into the database and file.name, then I retrieve that specific file.name and I want to get the URL download for that image from the storage and display that to the user in a table.
Since the image URL has to be loaded from the Firebase Storage servers, it may take some time. The easiest way to deal with this delay is to only add the row to the table once the URL is available:
var storageRef = firebase.storage.ref("users/file");
storageRef.getDownloadURL().then(function(url) {
$("#demo").append("<tr><td>"+ medname +"</td><td>" + description +
"</td><td>"+ type + "</td><td>" + start +
"</td><td>" + end +"</td><td> " + url + "</td></tr>");
});
});

How to send an email with a PDF through a script inside google spreadsheets?

The script just works as I want, I didn't develop it, I forgot the author's site, sorry if I don´t mention he/she.
The big problem is that I´m unable or I can't figure out how can I send an email with the PDF created through the script, I don't want to sent it in Zip format and if you release, the PDF file name´s change every time you use the spreadsheet, here I leave the code:
function spreadsheetToPDF(){
var key = '1hBbCnmca_wx4wbQx93Vf4d9cfUwGbFSP9hKgv9Qu7Vk'; //docid
var index = 0; //sheet gid / number
var ss = SpreadsheetApp.getActiveSpreadsheet();
var ActiveSheet = ss.getSheetByName('Sheet 1');
var timestamp = Utilities.formatDate(new Date(), "GMT", "yyyy-MM-dd'-'HHmm");
var plainonum = ActiveSheet.getRange("C5").getValue(); //order number
var supp_name = ActiveSheet.getRange("C12").getValue(); //supplier
var onum = ('0000' + plainonum ).slice(-4); //sets leading zeros to order number
var description = ActiveSheet.getRange("C18").getValue(); //description
var email = ActiveSheet.getRange("D1").getValue(); //email
var name = 'Order-' + onum +'-' + supp_name + '-' + description + '-' + timestamp + '.pdf'; //makes pdf filename
SpreadsheetApp.flush(); //ensures everything on spreadsheet is "done"
//make the pdf from the sheet
var theurl = 'https://docs.google.com/spreadsheets/d/'
+ key
+ '/export?exportFormat=pdf&format=pdf'
+ '&notes=false'
+ '&size=letter'
+ '&portrait=true'
+ '&fitw=true' // fit to width, false for actual size
+ '&sheetnames=false&printtitle=false&pagenumbers=false'
+ '&gridlines=false'
+ '&fzr=false' // do not repeat frozen rows on each page
+ '&gid='
+ index; //the sheet's Id
var token = ScriptApp.getOAuthToken();
var docurl = UrlFetchApp.fetch(theurl, { headers: { 'Authorization': 'Bearer ' + token } });
var pdf = docurl.getBlob().setName(name).getAs('application/pdf');
//save the file to folder on Drive
var fid = '0B6iePPHdQRoxQVB3eERrb1c3MUE';
var folder = DriveApp.getFolderById(fid);
folder.createFile(pdf);
var pfd = DriveApp.getFileById(pdf.getId()).getAs('application/pdf').getBytes();
var attach = {fileName:name,content:pfd, mimeType:'application/pdf'};
// Here I need to send the email
// GmailApp.sendEmail(email, "The subject", "The body content") // AND The PDF File witch I can´t attach
//Show a Popup with a message that a file was created inside a folder
SpreadsheetApp.getUi().alert('New document created in' + ' ' + folder);
}
After getting the file from drive using the DriveApp.getFolderById(id), you may then send it as an attachment using MailApp.sendEmail(recipient, subject, body, options).
Here's the sample code that you can try:
// Send an email with two attachments: a file from Google Drive (as a PDF) and an HTML file.
var file = DriveApp.getFileById('1234567890abcdefghijklmnopqrstuvwxyz');
var blob = Utilities.newBlob('Insert any HTML content here', 'text/html', 'my_document.html');
MailApp.sendEmail('mike#example.com', 'Attachment example', 'Two files are attached.', {
name: 'Automatic Emailer Script',
attachments: [file.getAs(MimeType.PDF), blob]
});
Solution given in this SO post might also help.
As I suspected, I was emailing only the name of the file but without the content, so I made a little variation to the var under the folder creation:
var archivo = docurl.getBlob().getAs('application/pdf').getBytes();
// Create a PDF from the active sheet, save it under a specific directory and send the PDF by mail
function spreadsheetToPDF(){
var key = 'abcdefghijk1234567890'; //docid (actual spreadsheet)
var index = 0; //sheet gid / number
var ss = SpreadsheetApp.getActiveSpreadsheet();
var ActiveSheet = ss.getSheetByName('Hoja 1');
var timestamp = Utilities.formatDate(new Date(), "GMT", "yyyy-MM-dd'-'HHmm");
var plainonum = ActiveSheet.getRange("C5").getValue(); //order number
var supp_name = ActiveSheet.getRange("C12").getValue(); //supplier
var onum = ('0000' + plainonum ).slice(-4); //sets leading zeros to order number
var description = ActiveSheet.getRange("C18").getValue(); //description
var correo = ActiveSheet.getRange("D1").getValue(); //correo electrónico
var name = 'Order-' + onum +'-' + supp_name + '-' + description + '-' + timestamp + '.pdf'; //makes pdf filename
SpreadsheetApp.flush(); //ensures everything on spreadsheet is "done"
//make the pdf from the sheet
var theurl = 'https://docs.google.com/spreadsheets/d/'
+ key
+ '/export?exportFormat=pdf&format=pdf'
+ '&size=A4'
+ '&portrait=true'
+ '&fitw=true' // fit to width, false for actual size
+ '&sheetnames=false&printtitle=false&pagenumbers=false'
+ '&gridlines=false'
+ '&fzr=false' // do not repeat frozen rows on each page
+ '&gid='
+ index; //the sheet's Id
var token = ScriptApp.getOAuthToken();
var docurl = UrlFetchApp.fetch(theurl, { headers: { 'Authorization': 'Bearer ' + token } });
var pdf = docurl.getBlob().setName(name).getAs('application/pdf');
//save the file to folder on Drive
var fid = 'abcdefghij1234567890';
var folder = DriveApp.getFolderById(fid);
folder.createFile(pdf);
//get the file, name and content to send it by email
var archivo = docurl.getBlob().getAs('application/pdf').getBytes();
var attach = {fileName:name,content:archivo, mimeType:'application/pdf'};
// Send email with the PDF attached
GmailApp.sendEmail(correo, "The subject", "The body content", {attachments:[attach]});
//Show a Popup with a message that a file was created inside a folder
SpreadsheetApp.getUi().alert('Nuevo Documento creado en el folder' + ' ' + folder);
}

Azure Account Shared Access Signiture

I am trying to construct an Account level Shared Access Signiture so my client can access all containers in a storage account. I am following these docs Account SAS. It seems straight forward enough but I keep getting the following error message:
"Signature did not match. String to sign used was accountname\nrl\nb\nsc\n\n2016-10-09\n\n\n2015-04-05\n".
My parameters are identical so I suspect it has something to do with how I am hashing the String to Sign. Below is how I construct the token.
var crypto = require('crypto');
var accountName = 'accountname';
var accountKey = 'tH37FTlG3TUT86caMrt2y5kOzof8nFqqA6spzg6r7HPRojE1zDiLJD/xE4oLFDh4RNqAmymvlV7fm8W4SF8cJg==';
var signedPermissions = "sp=rl";
var signedServcies = "ss=b";
var signedResourceType = "srt=sc";
var signedExpiry = "se=2016-10-09";
var signedVersion = "sv=2015-04-05";
var stringToSign = accountName + "\n" + signedPermissions + "\n" + signedServcies + "\n" + signedResourceType + "\n" + signedExpiry + "\n" + signedVersion + "\n";
var hmacsha256 = crypto.createHmac('sha256', accountKey).update(stringToSign).digest('base64');
var token = signedPermissions + "&" + signedServcies + "&" + signedResourceType + "&" + signedExpiry + "&" + signedVersion + "&sig=" + hmacsha256;
I have tried using crypto-js as well but to no avail. The final URL used to access a blob in a container is...
"https://accountname.blob.core.windows.net/containername/blobName?srt=sc&se=2016-10-09&api-version=2015-04-05&sp=rl&ss=b&sv=2015-04-05&sig=IFD2wyfRAsHGU5IFg3RbwSJW6tRE0m0%2FxgAYvJ%2FmnEk%3D"
I have been trying for days and really would appreciate knowing what I'm doing wrong. Thanks.
Benzene, for stringToSign, the value should NOT has the parameter name?
var signedPermissions = "rl";
var signedServcies = "b";
var signedResourceType = "sc";
var signedExpiry = "2016-10-09";
var signedVersion = "2015-04-05";
Please try the following (code shamelessly taken from Azure Storage Node.js library):
var hmacsha256 = crypto.createHmac('sha256', new Buffer(accountKey, 'base64')).update(stringToSign, 'utf-8').digest('base64');

Categories