I use this code for generating a pdf file and save it in a folder of my invoice but it saves two copy one in the folder and one in google drive out of all folders, how to remove send copy of pdf in drive but not in folder.
the code is
function runBothfunctions(){
//function 1
var ss = SpreadsheetApp.getActiveSpreadsheet()
var ss1 = ss.getSheetByName('sheet1')
var ss1Id = ss1.getSheetId()
var ss2 = ss.getSheetByName('sheet2')
var ssId = ss.getId()
var clientName = ss1.getRange(3,3).getValue()
var invoiceNumber = ss1.getRange(4,3).getValue()
var totalBill = ss1.getRange(29,9).getValue()
var d = new Date();
var fullDate = ('0' + d.getDate()).slice(-2) +"/"+ ('0' + (d.getMonth() +1)).slice(-2) +"/"+ (d.getYear().toString()).slice(-2)
var invoiceFileName = invoiceNumber + '_' + fullDate + '_' + clientName +'_'+ totalBill
var url = ss.getUrl()
url = url.replace(/edit$/,'')
var url_ext = 'export?exportFormat=pdf&format=pdf'
+ '&size=A4' // paper size: "legal" / "letter" / "A4"
+ '&fitw=true' // fit to width, false for actual size
+ '&sheetnames=false&printtitle=false' // hide optional headers and footers
+ '&gridlines=false' // hide gridlines
+ '&gid=' + ss1Id // the sheet's Id
var token = ScriptApp.getOAuthToken()
// Convert sheet1 to PDF
var response = UrlFetchApp.fetch(url + url_ext, { headers: { 'Authorization': 'Bearer ' + token }})
var blob = response.getBlob().setName(invoiceFileName + '.pdf')
// Add the folder ID of the Drive folder where the PDF should be saved. Create a folder and copy this ID: www.goo.gl/TfgqrN
var invoiceURL = DriveApp.getFolderById('19_cTkcDHlekS- 7Y32BEzUVlhghC0UHMZ').createFile(blob).getUrl()
ss2.getRange(ss2.getLastRow() +1, 1).setFormula('=HYPERLINK("' + invoiceURL + '";"' + invoiceFileName + '")')
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
var lastRow = sheet.getLastRow();
var lastColumn = sheet.getLastColumn();
//create an array of the invoice numbers already created
var colArray = sheet.getRange(4, 3).getValues();
//sort the array values to find max
var maxInColumn = colArray.sort(function(a,b){return b-a})[0][
Related
I'm trying to work out how to create a PDF document through Google Apps Script which is displayed in landscape orientation (A4 size). This is the code I'm using to create the PDF so far, which comes out in portrait orientation.
function pdfSheet() {
var d = new Date();
var cdate = d.getDate();
var cmonth = d.getMonth() + 1;
var cyear = d.getFullYear();
var current = [cdate + "-" + cmonth + "-" + cyear];
var imageBlob = UrlFetchApp.fetch("https://sites.google.com/site/mysite/smalllogo.png").getBlob();
var base64EncodedBytes = Utilities.base64Encode(imageBlob.getBytes());
var logo = "<img src='data:image/png;base64," + base64EncodedBytes + "' width='170'/>";
var html = "<table width='100%'><tr><td align='right'>" + logo + "<br><br><b>Date:</b> " + current + "</td></tr></table>"; //PDF content will carry on here.
var gmailLabels = "PDF";
var driveFolder = "My Gmail";
var folders = DriveApp.getFoldersByName(driveFolder);
var folder = folders.hasNext() ?
folders.next() : DriveApp.createFolder(driveFolder);
var subject = 'Test PDF';
var tempFile = DriveApp.createFile("temp.html", html, "text/html");
var page = folder.createFile(tempFile.getAs("application/pdf")).setName(subject + ".pdf")
tempFile.setTrashed(true);
var link = page.getUrl();
Logger.log(link);
}
I took most of this from another user and edited to have the current days date (in EST) in the email subject and the PDF name. Hope it helps!
// Simple function to send Daily Status Sheets
// Load a menu item called "Project Admin" with a submenu item called "Send Status"
// Running this, sends the currently open sheet, as a PDF attachment
function onOpen() {
var submenu = [{name:"Send Status", functionName:"exportSomeSheets"}];
SpreadsheetApp.getActiveSpreadsheet().addMenu('Project Admin', submenu);
}
function creatPDF() {
SpreadsheetApp.flush();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
//Date set with format in EST (NYC) used in subject and PDF name
var period = Utilities.formatDate(new Date(), "GMT+5", "yyyy.MM.dd");
var url = ss.getUrl();
//remove the trailing 'edit' from the url
url = url.replace(/edit$/, '');
//additional parameters for exporting the sheet as a pdf
var url_ext = 'export?exportFormat=pdf&format=pdf' + //export as pdf
//below parameters are optional...
'&size=letter' + //paper size
'&portrait=false' + //orientation, false for landscape
'&fitw=true' + //fit to width, false for actual size
'&sheetnames=false&printtitle=false&pagenumbers=false' + //hide optional headers and footers
'&gridlines=false' + //hide gridlines
'&fzr=false' + //do not repeat row headers (frozen rows) on each page
'&gid=' + sheet.getSheetId(); //the sheet's Id
var token = ScriptApp.getOAuthToken();
var response = UrlFetchApp.fetch(url + url_ext, {
headers: {
'Authorization': 'Bearer ' + token
}
});
var blob = response.getBlob().setName(ss.getName() + " " + period + '.pdf');
//from here you should be able to use and manipulate the blob to send and email or create a file per usual.
var email = 'email#co-email.com';
var subject = "subject line " + period ;
var body = "Please find attached your Daily Report.";
//Place receipient email between the marks
MailApp.sendEmail( email, subject, body, {attachments:[blob]});
}
I'm trying to work out how to create a PDF document through Google Apps Script which is displayed in landscape orientation (A4 size). This is the code I'm using to create the PDF so far, which comes out in portrait orientation.
function pdfSheet() {
var d = new Date();
var cdate = d.getDate();
var cmonth = d.getMonth() + 1;
var cyear = d.getFullYear();
var current = [cdate + "-" + cmonth + "-" + cyear];
var imageBlob = UrlFetchApp.fetch("https://sites.google.com/site/mysite/smalllogo.png").getBlob();
var base64EncodedBytes = Utilities.base64Encode(imageBlob.getBytes());
var logo = "<img src='data:image/png;base64," + base64EncodedBytes + "' width='170'/>";
var html = "<table width='100%'><tr><td align='right'>" + logo + "<br><br><b>Date:</b> " + current + "</td></tr></table>"; //PDF content will carry on here.
var gmailLabels = "PDF";
var driveFolder = "My Gmail";
var folders = DriveApp.getFoldersByName(driveFolder);
var folder = folders.hasNext() ?
folders.next() : DriveApp.createFolder(driveFolder);
var subject = 'Test PDF';
var tempFile = DriveApp.createFile("temp.html", html, "text/html");
var page = folder.createFile(tempFile.getAs("application/pdf")).setName(subject + ".pdf")
tempFile.setTrashed(true);
var link = page.getUrl();
Logger.log(link);
}
I took most of this from another user and edited to have the current days date (in EST) in the email subject and the PDF name. Hope it helps!
// Simple function to send Daily Status Sheets
// Load a menu item called "Project Admin" with a submenu item called "Send Status"
// Running this, sends the currently open sheet, as a PDF attachment
function onOpen() {
var submenu = [{name:"Send Status", functionName:"exportSomeSheets"}];
SpreadsheetApp.getActiveSpreadsheet().addMenu('Project Admin', submenu);
}
function creatPDF() {
SpreadsheetApp.flush();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
//Date set with format in EST (NYC) used in subject and PDF name
var period = Utilities.formatDate(new Date(), "GMT+5", "yyyy.MM.dd");
var url = ss.getUrl();
//remove the trailing 'edit' from the url
url = url.replace(/edit$/, '');
//additional parameters for exporting the sheet as a pdf
var url_ext = 'export?exportFormat=pdf&format=pdf' + //export as pdf
//below parameters are optional...
'&size=letter' + //paper size
'&portrait=false' + //orientation, false for landscape
'&fitw=true' + //fit to width, false for actual size
'&sheetnames=false&printtitle=false&pagenumbers=false' + //hide optional headers and footers
'&gridlines=false' + //hide gridlines
'&fzr=false' + //do not repeat row headers (frozen rows) on each page
'&gid=' + sheet.getSheetId(); //the sheet's Id
var token = ScriptApp.getOAuthToken();
var response = UrlFetchApp.fetch(url + url_ext, {
headers: {
'Authorization': 'Bearer ' + token
}
});
var blob = response.getBlob().setName(ss.getName() + " " + period + '.pdf');
//from here you should be able to use and manipulate the blob to send and email or create a file per usual.
var email = 'email#co-email.com';
var subject = "subject line " + period ;
var body = "Please find attached your Daily Report.";
//Place receipient email between the marks
MailApp.sendEmail( email, subject, body, {attachments:[blob]});
}
I am trying to figure out how to have the PDF save in a specific folder instead of the root directory.
I have tried several different things, I have been able to create a new folder but even then it still ends up in the root directory.
function SaveAsPDF() {
var ss = SpreadsheetApp.getActive()
var sheet = SpreadsheetApp.getActiveSheet()
var cell = sheet.getRange('K1')
var cellContent = cell.getValue()
if(cellContent == 'JMB'){
SpreadsheetApp.flush();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sourceSpreadsheet = SpreadsheetApp.getActive(); // Get active spreadsheet.
var sheetName = sourceSpreadsheet.getActiveSheet().getName();
var pdfName = ss.getRange("H1").getValue() // Set the output filename as SheetName.
var theBlob = createblobpdf(sheetName, pdfName);
var newFile = Driveapp.createFile(theBlob);
sourceSpreadsheet.toast("Saved ", "Success");
}
function createblobpdf(sheetName, pdfName) {
var sourceSpreadsheet = SpreadsheetApp.getActive();
var sourceSheet = sourceSpreadsheet.getSheetByName(sheetName);
var url = 'https://docs.google.com/spreadsheets/d/' + sourceSpreadsheet.getId()
+ '/export'
+ '?format=pdf'
+ '&size=legal' // paper size legal / letter / A4
+ '&portrait=true' // orientation, false for landscape
+ '&scale=4' // 1= Normal 100% / 2= Fit to width / 3= Fit to height / 4= Fit to Page
+ '&fitw=true' // fit to width, false for actual size
+ '&top_margin=1.00' // All four margins must be set!
+ '&bottom_margin=1.00' // All four margins must be set!
+ '&left_margin=1.00' // All four margins must be set!
+ '&right_margin=1.00' // All four margins must be set!
+ '&sheetnames=true&printtitle=false' // hide optional headers and footers
+ '&pagenum=RIGHT&gridlines=false' // hide page numbers and gridlines
+ '&fzr=false' // do not repeat row headers (frozen rows) on each page
+ '&horizontal_alignment=CENTER' //LEFT/CENTER/RIGHT
+ '&vertical_alignment=TOP' //TOP/MIDDLE/BOTTOM
+ '&gid=' + sourceSheet.getSheetId(); // the sheet's Id
var token = ScriptApp.getOAuthToken();
// request export url
var response = UrlFetchApp.fetch(url, {
headers: {
'Authorization': 'Bearer ' + token
}
});
var theBlob = response.getBlob().setName(pdfName);
return theBlob;
}
};
Try this:
function SaveAsPDF() {
var ss = SpreadsheetApp.getActive()
var sh = SpreadsheetApp.getActiveSheet();
if (sh.getRange("K1").getValue() == 'JMB') {
var sheetName = sh.getName();
var pdfName = sh.getRange("H1").getValue();
var theBlob = createblobpdf(sheetName, pdfName);
const folder = DriveApp.getFolderById("FolderId");
var newFile = folder.createFile(theBlob);
ss.toast("Saved ", "Success");
}
}
I´ve been using this code for more almost a year, but all the sudden stop working
At the moment, instead of creating a PDF file, is creating an HTML file
function creatPDF() {
SpreadsheetApp.flush();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var Consecutivo = sheet.getRange(2,20).getValue();
var Proveedor = sheet.getRange(14,5).getValue();
var CenCos = sheet.getRange(7,7).getValue();
var TipoOC = sheet.getRange(2,10).getValue();
var Cuenta = sheet.getRange(9,7).getValue();
var PDF_FILE_NAME = Consecutivo + ' - ' + Proveedor;
var spreadsheet = SpreadsheetApp.getActive();
var spreadsheetId = spreadsheet.getId();;
var TargetFolder = DriveApp.getFolderById(DriveApp.getFileById(spreadsheetId).getParents().next().getId());
var url = ss.getUrl();
url = url.replace(/edit$/, '');
var url_ext = 'export?exportFormat=pdf&format=pdf' +
'&size=a4' +
'&portrait=true' +
'&fitw=true' +
'&top_margin=0.30' +
'&bottom_margin=0.3' +
'&left_margin=0.85' +
'&right_margin=0.85' +
'&sheetnames=false&printtitle=false&pagenumbers=false' +
'&gridlines=false' +
'&fzr=false' +
'&gid=' + sheet.getSheetId();
var token = ScriptApp.getOAuthToken();
var response = UrlFetchApp.fetch(url + url_ext, { headers: { 'Authorization': 'Bearer ' + token }});
newFile = DriveApp.createFile(response.getBlob()).setName(PDF_FILE_NAME);
var newFileSourceFolder = DriveApp.getRootFolder()
TargetFolder.addFile(newFile);
newFileSourceFolder.removeFile(newFile)
SpreadsheetApp.getUi().alert('Nuevo PDF creado para la orden ' + Consecutivo + '.')
}
}
It´s supposed to create just one PDF file, within the same folder where the sheet is.
Replace this
url = url.replace(/edit$/, '')
With this
url = url.substring(url.indexOf("edit?"), -100000) //url.replace(/edit$/,'');
I have a script that exports a sheet to a pdf file when function is run. This works fine when I run it from the account in which the script was created but when a shared user runs it returns the following error: Exception: Cannot retrieve the next object: iterator has reached the end. Line 9
The code is as below, i'm not sure what actually is wrong with this so would be glad of help:
function CreatePDF() {
var sourceSpreadsheet = SpreadsheetApp.getActive();
var ui = SpreadsheetApp.getUi();
var sheetName = "Stock List";
var sourceSheet = sourceSpreadsheet.getSheetByName(sheetName);
var sh = sourceSpreadsheet.getSheetByName("Product List");
var driveFile = DriveApp.getFileById("xxxxxxxxxxxxxxxxxxxxxxxxxxxxx");
var parentFolder = driveFile.getParents();
var folderName =parentFolder.next().getId();
var folder = DriveApp.getFolderById(folderName);
var numf = sourceSpreadsheet.getRangeByName("exportrange").getValue();
var anof = numf.split("/",2);
var pdfRange = sh.getRange("F1");
var pdfName = pdfRange.getValue();
// export url
var url = 'https://docs.google.com/spreadsheets/d/'+sourceSpreadsheet.getId()+'/export?exportFormat=pdf&format=pdf' // export as pdf / csv / xls / xlsx
+ '&size=A4'
+ '&portrait=true'
+ '&fitw=true'
+ '&top_margin=0.00'
+ '&bottom_margin=0.00'
+ '&left_margin=0.00'
+ '&right_margin=0.00'
+ '&sheetnames=false&printtitle=false'
+ '&pagenumbers=false&gridlines=false'
+ '&fzr=false'
+ '&gid='+sourceSheet.getSheetId();
var token = ScriptApp.getOAuthToken();
var response = UrlFetchApp.fetch(url, {
headers: {
'Authorization': 'Bearer ' + token
}
});
var theBlob = response.getBlob().setName(pdfName+'.pdf');
var files = folder.getFilesByName(pdfName);
while (files.hasNext())
{
files.next().setTrashed(true);
}
}