PDF file from selection in Google Sheets - google-apps-script

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;

Related

Print Google Sheet in Landscape as PDF to Folder [duplicate]

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]});
}

Google Apps Script - Exporting PDF in landscape format [duplicate]

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]});
}

TypeError: Cannot read property 'getResponseCode' of undefined doGet_Appraisal throws error but before it was executed properly how to resolve

It was actually a Google Sheets project, so I'm learning on the fly as best as I can, but I can't even format this code below correctly - ugh!)
The error I am receiving is this:
TypeError: Cannot read property 'getResponseCode' of undefined
doGet_Appraisal # Appraisal_Email.gs:64
And the code is below:
//1. Performing to generate the Payslip getting sheet contents
function doGet_Appraisal(range,shTabName) {
var blob,exportUrl,name,options,response,sheetTabId,ss,ssID,url_base,email,subject;
var folderId ="1o9WImzeKdzsek7DfZWD_qzFsI9yLoplz";
var milliseconds = 2000;
range = range ? range : "B1:R44";
ss = SpreadsheetApp.openById("sheet_ID");
shTabName = "Appraisal Payslip Template";
ssID = ss.getId();
sh = ss.getSheetByName(shTabName);
const body = "Dear Employee" + "\n\n" + "<p>" + "<b> Payslip for the month of January is Available </b>" + "</p>";
var htmlText = body.replace(/\n/g,'\n<br>');
var bioCode = sh.getRange('F12');
const values = [...new Set(bioCode.getDataValidation().getCriteriaValues()[0].getValues().flat())];
var first = values[0];
var number = values.length - 1;
bioCode.setValue(first);
//2. Looping the Emp_ID till null
for(i = 0;i < number;i++)
{
if (sh.getRange('F12').getValue().length > 0) {
var person = sh.getRange('F12').getValue();
sheetTabId = sh.getSheetId();
//3. Getting the Corresponfing EMail based on Emp_ID
email = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Appraisal Payslip Template').getRange('N12').getValue().toString();
Utilities.sleep(milliseconds);
url_base = ss.getUrl().replace(/edit$/,'');
name = sh.getRange("S1").getValue();
name = name + ""
subject = `${name}`;
Logger.log('email: ' + email)
Logger.log('body: ' + body)
//4. Exporting the sheet as PDF (contents)
exportUrl = url_base + 'export?exportFormat=pdf&format=pdf' +
'&gid=' + sheetTabId + '&id=' + ssID +
'&range=' + range +
'&size=A4' +
'&portrait=true' +
'&fitw=true' +
'&sheetnames=false&printtitle=false&pagenumbers=true' +
'&gridlines=false' +
'&fzr=false';
//5. Authorizing email setup OAuthToken
options = {
headers: {
'Authorization': 'Bearer ' + ScriptApp.getOAuthToken(),
}
}
//6. Getting the sheet url and export as PDF
options.muteHttpExceptions = true;
response = UrlFetchApp.fetch(exportUrl, options);
//var response2 = UrlFetchApp.fetch(exportUrl, options).getBlob();
Logger.log(response.getResponseCode())
const nextValue = values[values.indexOf(bioCode.getValue()) + 1] || values[0];
bioCode.setValue(nextValue);
}
else {const nextValue = values[values.indexOf(bioCode.getValue()) + 1] ||
values[0];
bioCode.setValue(nextValue);
}
//7. If response code is not 200 return error exporting PDF
if (response.getResponseCode() !== 200) {
console.log("Error exporting Sheet to PDF! Response Code: " + response.getResponseCode());
return;
}
blob = response.getBlob();
blob.setName(name + '.pdf')
GmailApp.sendEmail(email, subject, htmlText,
{
htmlBody: htmlText,
attachments: [{
fileName: `${name}` + ".pdf",
//content: response2.getBytes(),
mimeType: "application/pdf"
}]
});
//pdfFile = DriveApp.getFolderById(folderId).createFile(blob);
}
}
This was worked recently but now throws error
TypeError: Cannot read property 'getResponseCode' of undefined
doGet_Appraisal # Appraisal_Email.gs:64

Exporting a sheet to PDF suddenly stopped working

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$/,'');

how to remove two second copy of pdf

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][