Generate and download pdf file using google apps script to local PC - google-apps-script

I wrote a Google Apps script in a Spreadsheet that convert the Spreadsheet to pdf. This works.
How can I copy this generated pdf file automatically using the same script to PC's local folder (Desktop f.e.)
Code.gs
function onOpen() {
var submenu = [{name:"Save PDF", functionName:"generatePdf"}];
SpreadsheetApp.getActiveSpreadsheet().addMenu('Export', submenu);
}
function generatePdf() {
var sourceSpreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var pdfName = Browser.inputBox("Name of generated pdf");
var save2folder = DriveApp.getRootFolder();
var theBlob = sourceSpreadsheet.getBlob().getAs('application/pdf').setName(pdfName);
var pdfFile = save2folder.createFile(theBlob);
}
Thanks

Related

Is there a way to copy a specific sheet from one workbook to a specific (and different) folder as its own stand alone sheet in google?

I am not a developer or coder, just trying to learn and automate tasks*. This is what I have so far:
function saveAsSpreadsheet() {
var source = SpreadsheetApp.getActiveSpreadsheet();
var sheet = source.getSheets()[6];
var destFolder = DriveApp.getFolderById("xxxxxxxxxxxxxxxxxx");
DriveApp.getFileById(sheet.getSheetId()).makeCopy("desired file name", destFolder);
} //END function saveAsSpreadsheet
I get the error "Exception: Unexpected error while getting the method or property getFileById on object DriveApp."
Any tweaks that might make this work?
Issues:
You are trying to use the sheet id instead of spreadsheet id in DriveApp.getFileById(file id).
Using makeCopy(name, destination) will copy the content of the whole spreadsheet.
Try this:
function saveAsSpreadsheet() {
var folderId = "id";
var fileName = "new File";
var file = Drive.Files.insert({title: fileName, mimeType: MimeType.GOOGLE_SHEETS, parents: [{id: folderId}]});
var newFile = SpreadsheetApp.openById(file.id);
var source = SpreadsheetApp.getActiveSpreadsheet();
var sheet = source.getSheets()[0];
var sheetName = sheet.getSheetName();
sheet.copyTo(newFile).setName(sheetName);
}
Note: Make sure to add Drive API to the project Services. See how to add Services in Apps Script.
Example:
Source file:
Destination:
Reference:
Drive.Files.insert()

Google Apps Script how to export specific sheet as csv format

In MIT Inventor II, I use web component to get SpreadsheetID and SheetID through doGet() of google apps script. After I get the information I use another web component to set url as below to get csv-formatted file from specific sheet. My question is how to make GAS to get SpreadsheetID & SheetID and then export csv file at one time, so that I don't have to use 2 web components in Inventor side?
GAS codes is as below. This is to "return" spreadsheetID and sheetID.
function doGet(e) {
filename = e.parameter.account;
fileList = DriveApp.getFilesByName(filename);
while (fileList.hasNext()) {
var fileID = fileList.next().getId()
}
var file = SpreadsheetApp.openById(fileID) ;
sheet = file.getSheetByName("Message").activate()
var messageID = sheet.getSheetId();
return ContentService.createTextOutput([fileID,messageID]);
After I got SpreadsheetID & SheetID, I have to set 2nd web component from Inventor side to get csv file, see below.
https://docs.google.com/spreadsheets/d/xxxxSpreadsheetIDxxxx/edit#gid=sheetID
Here is how you can create a csv file of a selected sheet in google drive:
function sheetToCsv()
{
var ssID = SpreadsheetApp.getActiveSpreadsheet().getId();
var sheet_Name = "Sheet1"
var requestData = {"method": "GET", "headers":{"Authorization":"Bearer "+ScriptApp.getOAuthToken()}};
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheet_Name)
var sheetNameId = sheet.getSheetId().toString();
params= ssID+"/export?gid="+sheetNameId +"&format=csv"
var url = "https://docs.google.com/spreadsheets/d/"+ params
var result = UrlFetchApp.fetch(url, requestData);
var resource = {
title: sheet_Name+".csv",
mimeType: "application/vnd.csv"
}
var fileJson = Drive.Files.insert(resource,result)
}
The code creates a csv file that has the content of Sheet1.
In order to run the aforementioned function you need to activate the Advanced Drive Service.
Explanation:
Go to Resources => Advanced Google Services => activate Drive API
Another option is to create the csv file to a particular folder, then you need to replace the resource part of the code with this:
var folder_id ='id';
var resource = {
title: sheet_Name+".csv",
mimeType: "application/vnd.csv",
parents: [{ id: folder_id }]
}
My application was how to save a tab of a Google sheets spreadsheet to a CSV file in a shared drive. Doing it to the default "My Drive" was relatively easy based on Marios' answer in this post, but I struggled with this for a shared drive while until I came across ziganotschka's example which solved my problem.
Code for my simple App Script is:
function sheetToCsv()
{
var ssID = SpreadsheetApp.getActiveSpreadsheet().getId();
var sheet_Name = "[Your sheet name goes here]";
var requestData = {"method": "GET", "headers":{"Authorization":"Bearer "+ScriptApp.getOAuthToken()}};
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheet_Name);
var sheetNameId = sheet.getSheetId().toString();
params= ssID+"/export?gid="+sheetNameId +"&format=csv";
var url = "https://docs.google.com/spreadsheets/d/"+ params;
var result = UrlFetchApp.fetch(url, requestData);
var resource = {
title: sheet_Name+".csv",
mimeType: "MimeType.CSV",
parents:[{
"id": "[Your Shared Drive Folder ID goes here]"
}]
}
var optionalArgs={supportsAllDrives: true};
var fileJson = Drive.Files.insert(resource, result, optionalArgs);
}
I added a timestamp to the file name and a trigger to cause the script to execute daily via a timer.

Export a Google sheet range as pdf using Apps script and store the pdf in drive

need some help and hope you can help me :)
I have a google spreadsheet document and need to do some actions per script:
Sheet: "Sheet1"
Range: "A1:J39"
print out with settings (landscape, perfect width)
save as PDF document in a folder in a shared google drive (same settings like no 1)
send PDF file per mail to adresses which listed in an other sheet
hope you can help me with this problem....
thx
I'm giving below code I use to send a full sheet as PDF.
You can modify it slightly to
1.Hide unwanted rows and columns
2.Include PDF export options
function send_sheet(){
var today=new Date();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var ltrsht = ss.getSheetByName("Letter");
var sheets=SpreadsheetApp.getActiveSpreadsheet().getSheets();
for(var i =0;i<sheets.length;i++){
if(sheets[i].getName()!="Letter"){ sheets[i].hideSheet() }
}
var pdf = DriveApp.getFileById(ss.getId());
var theBlob = pdf.getBlob().getAs('application/pdf').setName(ltrsht.getRange("C16").getValue()+".pdf");
var folderID = ""; // Folder id to save in a folder
var folder = DriveApp.getFolderById(folderID);
var newFile = folder.createFile(theBlob);
var body = 'Dear ' + ltrsht.getRange("C16").getValue() +',\n\nPL. find your ' + ltrsht.getRange("C11").getValue() +' enclosed.\n\nHRD Megawin Switchgear';
GmailApp.sendEmail(ltrsht.getRange("E17").getValue(), ltrsht.getRange("C11").getValue() + " from Megawin HRD", body, {attachments: [theBlob]});
var empsht = ss.getSheetByName("Emp");
empsht.showSheet();
ltrsht.hideSheet();
}
First you have to hide all sheets other than the target sheet
Hide unwanted rows and columns
Convert to PDF
Save in folder
Send to email id which is stored some cell
See below how to format the PDF
https://support.google.com/docs/thread/3457043?hl=en

Save Google Slide as PDF using Google Apps Script

Is there a way to save a Google Slides as PDF file by using Google Apps Script?
I could only find solutions for saving Google Docs and Sheets.
How about this sample script? When Google Docs (Spreadsheet, Document and Slide) is saved and/or downloaded using DriveApp.createFile(), the file format automatically becomes PDF. So we can use the following script.
Sample script :
var blob = DriveApp.getFileById("### Slide file ID ###").getBlob();
DriveApp.createFile(blob);
Note :
In this case, the filename of created PDF file is the same to the slide.
Edit :
If you want to copy the slide file, please use a following script.
var file = DriveApp.getFileById("### Slide file ID ###");
file.makeCopy(DriveApp.getFolderById("### Destination folder ID ###"));
This could work by replacing DocumentApp with SlideApp
Beware it also deletes a previously created pdf of the same name if it exists in the drive folder.
function onOpen() {
var ui = DocumentApp.getUi();
ui.createMenu('Save PDF copy')
.addItem('Save PDF', 'SavePDF')
.addToUi();
}
function SavePDF() {
var theDoc = DocumentApp.getActiveDocument();
var id = DocumentApp.getActiveDocument().getId()
var ui = DocumentApp.getUi();
var folderString = DriveApp.getFileById(id).getParents().next().getName();
var folder = DriveApp.getFileById(id).getParents().next();
var theBlob = theDoc.getAs('application/pdf')
var thePDFName = theBlob.getName()
var theFiles = DriveApp.getFilesByName(theBlob.getName())
while (theFiles.hasNext()) {
var theFile = theFiles.next()
if (theFile.getParents().next().getName() == folderString) {
theFile.setTrashed(true)
}
}
var newFile = folder.createFile(theBlob);
ui.alert('Saved to ' + folderString + " " + theBlob.getName())
}
let pdf = DriveApp.getFileById(copySlide.getId())
.getBlob()
.getAs("application/pdf");
pdf.setName("filename.pdf");
let file = DriveApp.getFolderById(FOLDER_ID).createFile(pdf);

exporting spreadsheet to pdf then saving the file in google drive

I'm having problems saving to google drive after printing a google spreadsheet to pdf.
If i just put the "printurl" string into a browser, it will automatically give me the file. But I want it to be saved to google drive automatically. I've tried this code by borrowing code from other posts that emails a spreadsheet as PDF. But this produces a pdf that is unable to be opened. What am I doing wrong?
function printpdf() {
var spreadsheet_id="0Aiy1DTQRndx6dDRidXoxNzlXZFhxd2FITTlBbnUybnc";
var settings = '&fitw=true&portrait=false&exportFormat=pdf&gid=0&gridlines=false';
var printurl = 'https://spreadsheets.google.com/feeds/download/spreadsheets/Export? key=' + spreadsheet_id + settings;
var result=UrlFetchApp.fetch(printurl);
var content=result.getContent();
var file=DocsList.createFile("temp",content,"application/pdf");
}
Here is an update to this question under the new oauth2 format.
Printing spreadsheet to PDF then saving file in Drive using OAuth2
You can do it in a much simpler fashion
function printpdf(){
var spreadsheet_id="0Aiy1DTQRndx6dDRidXoxNzlXZFhxd2FITTlBbnUybnc";
var spreadsheetFile = DocsList.getFileById(spreadsheet_id);
var blob = spreadsheetFile.getAs('application/pdf');
DocsList.createFile(blob);
}
Note that the DocsList.createFile(blob) works only with Google Apps accounts.
did you mean it like that?
var id = SpreadsheetApp.getActiveSpreadsheet().getId();
var sheetName = getConfig(SHEET_NAME_CELL);
var dataSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
if (!dataSheet) {
Browser.msgBox("Can't find sheet named:" + sheetName);
return;
}
var dataSheetIndex = dataSheet.getSheetId();
//this is three level authorization
var oauthConfig = UrlFetchApp.addOAuthService("google");
oauthConfig.setAccessTokenUrl("https://www.google.com/accounts/OAuthGetAccessToken");
oauthConfig.setRequestTokenUrl("https://www.google.com/accounts/OAuthGetRequestToken?scope=https://spreadsheets.google.com/feeds/");
oauthConfig.setAuthorizationUrl("https://www.google.com/accounts/OAuthAuthorizeToken");
oauthConfig.setConsumerKey("anonymous");
oauthConfig.setConsumerSecret("anonymous");
//even better code
//oauthConfig.setConsumerKey(ScriptProperties.getProperty("consumerKey"));
//oauthConfig.setConsumerSecret(ScriptProperties.getProperty("consumerSecret"));
var requestData = {
"method": "GET",
"oAuthServiceName": "google",
"oAuthUseToken": "always"
};
var url = "https://spreadsheets.google.com/feeds/download/spreadsheets/Export?key=" + id + "&gid=" + dataSheetIndex + "&fitw=true&size=A4&portrait=true&sheetnames=false&printtitle=false&exportFormat=pdf&format=pdf&gridlines=false";
//Save File to Google Drive
var seplogoBlob = UrlFetchApp.fetch(url, requestData).getBlob().setName("Filename.pdf");
DocsList.createFile(seplogoBlob);