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$/,'');
Related
I am trying to save a selection of cells to a pdf. Everything is working except when I open the pdf it looks like html.
What am I doing wrong?
var ss = SpreadsheetApp.getActiveSpreadsheet();
var token = ScriptApp.getOAuthToken();
sheet2.getRange('A1:N50').activate(); *// I realise this could be the problem but not sure how to correct it*
var url = "https://docs.google.com/spreadsheets/d/1roKWtpNPsfaQDxW82WZCfQzek77HEV4ihuC52radoXU/edit#gid=2092984379".replace("SS_ID", sheet2.getName());
var reqFolder = '1sIxddxsPHKLKjuiArZdtrckCMxAePHR6'
var folder = DriveApp.getFolderById(reqFolder);
var paymentreq = sheet1.getRange("B7").getValue();
var creditor = sheet2.getRange("D9").getValue();
var pdfName = 'Req ' + paymentreq + " " + creditor + " " + Utilities.formatDate(new Date(),"GMT+1","dd.MM.yyyy");
var url_ext = 'exportFormat=pdf&format=pdf' + '&size=A4' + '&portrait=false' + 'fitw=true';
var response = UrlFetchApp.fetch(url + url_ext + sheet2.getSheetId());
headers: {
Authorisation:'Bearer' + token
}
var blob = response.getBlob().setName(pdfName + '.pdf');
folder.createFile(blob);
};
Thank you
I have tried removing the selection section but it still only gives me html. The file when I hover over it starts with HTML: "filename.pdf"
Modification points:
In your script, ss, sheet1, and sheet2 are not declared.
headers: { Authorisation:'Bearer' + token} is not included in UrlFetchApp.fetch
Authorisation is not correct. It's Authorization.
In your endpoint is required to be modified.
There are 2 gid in your query parameter.
I think that this might be the reason for the issue with your 2nd script.
When these points are reflected, it becomes as follows.
Modified script:
From:
var sourceSheet = ss.getSheetByName("Payment Req")
var url = "https://docs.google.com/spreadsheets/d/18JPPgqLe5W8pQ_oGP-8oC3Ar4DRfbqrXbUwDfrxy1pM/edit#gid=2092984379" + '/export?exportFormat=pdf&format=pdf' + '&size=A4' + '&portrait=false' + '&fitw=true' + '&sheetnames=true&printtitle=false' + '&pagenum=RIGHT&gridlines=false' + '&fzr=false' + '&horizontal_alignment=CENTER' + '&vertical_alignment=MIDDLE' + '&gid=' + sourceSheet.getSheetId();
var reqFolder = '1sIxddxsPHKLKjuiArZdtrckCMxAePHR6'
var folder = DriveApp.getFolderById(reqFolder);
var paymentreq = sheet1.getRange("B7").getValue();
var creditor = sheet2.getRange("D9").getValue();
var pdfName = 'Req ' + paymentreq + " " + creditor + " " + Utilities.formatDate(new Date(),"GMT+1","dd.MM.yyyy");
var response = UrlFetchApp.fetch(url, {headers: {"Authorisation":'Bearer ' + ScriptApp.getOAuthToken()}});
var theblob = response.getBlob().setName(pdfName + ".pdf");
const pdfFile = folder.createFile(theblob);
return pdfFile;
To:
var ss = SpreadsheetApp.getActiveSpreadsheet(); // Please set Spreadsheet object as ss.
var sheet1 = // Please set your sheet1.
var sheet2 = // Please set your sheet2.
var sourceSheet = ss.getSheetByName("Payment Req");
var url = ss.getUrl().replace(/\/edit/, "") + '/export?exportFormat=pdf&format=pdf' + '&size=A4' + '&portrait=false' + '&fitw=true' + '&sheetnames=true&printtitle=false' + '&pagenum=RIGHT&gridlines=false' + '&fzr=false' + '&horizontal_alignment=CENTER' + '&vertical_alignment=MIDDLE' + '&gid=' + sourceSheet.getSheetId();
var reqFolder = '1sIxddxsPHKLKjuiArZdtrckCMxAePHR6';
var folder = DriveApp.getFolderById(reqFolder);
var paymentreq = sheet1.getRange("B7").getValue();
var creditor = sheet2.getRange("D9").getValue();
var pdfName = 'Req ' + paymentreq + " " + creditor + " " + Utilities.formatDate(new Date(), "GMT+1", "dd.MM.yyyy");
var response = UrlFetchApp.fetch(url, { headers: { "Authorization": "Bearer " + ScriptApp.getOAuthToken() } });
var theblob = response.getBlob().setName(pdfName + ".pdf");
const pdfFile = folder.createFile(theblob);
return pdfFile;
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 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);
}
}
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][