Google Apps Script print sheet with margins - google-apps-script

There is a nice GAS script to print a Google sheet in google app script print button
As discussed on the Google Cloud Connect (https://www.cloudconnect.goog/message/77627), we are trying to identify a way to control the margins.
There is also a similar question over on the Google Product Forums at https://productforums.google.com/forum/#!topic/docs/DQxnJwoDn0c

You might find this script useful.
I think that it might answer your question on the margins plus it has a few other helpful settings that you can play with.
function printPdf() {
SpreadsheetApp.flush();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var gid = sheet.getSheetId();
var pdfOpts = '&size=A3&fzr=true&portrait=false&fitw=true&gridlines=false&printtitle=true&sheetnames=true&pagenumbers=true&attachment=false&gid='+gid;
var url = ss.getUrl().replace(/edit$/, '') + 'export?format=pdf' + pdfOpts
var app = UiApp.createApplication().setWidth(300).setHeight(100);
app.setTitle('Your Print Preview is Ready');
var link = app.createAnchor('Open Print Preview', url).setTarget('_new');
app.add(link);
ss.show(app);
}
See also: Printing a sheet to PDF

This was also reported in this thread. I suggest to file a feature request for this.

Your first link uses the UiApp which has been depricated but I think I'd look in the following if you still wish to use it.
var pdfOpts = '&size=A4&fzr=false&portrait=false&fitw=true&gridlines=false&printtitle=false&shee tnames=false&pagenum=UNDEFINED&attachment=false&gid='+gid;

it is (currently) neither possible through App Script API ...nor the Macro Recorder
therefore, I'd suggest to utilize some Chrome extension, alike Automation.
the key-codes to open the page setup dialog and enter the desired values and then proceed to hit the Next button, should be about alike this: <Alt> + F, P, (select margins, then select custom numbers, then select the top margin entry field, that can be reached by <Tab>, <Cursor Down> and <Space>)... and then 0.25", <Tab>, 0.25", <Tab>, 0.25", <Tab>, 0.25" ... <Tab>, <Tab>, <Enter>.
from within a spreadsheet (and not even from within client-side JavaScript), without any browser extension, which can send key-codes, there is no access to these properties - because otherwise scripts could easily mess up custom local printer settings.

Related

Unexpected value of Google PageSpeed insights API when used with Google Sheets

I'm using the PageSpeed API to pull data using Google Script into Google Sheets.
However, when I execute the script and fetch data from the PageSpeed URL, the time-to-first-byte numeric value is substantially higher than when I run it in my regular browser window.
For example, when I fetch the URL within Google Sheets with the code below, my average Time-to-first-byte is 500-510ms. While if I use the exact same URL in chrome on my desktop, it's generally 60-70ms.
This is the code I use to pull in the data:
function callPageSpeed(strategy) {
var pageSpeedUrl = 'https://www.googleapis.com/pagespeedonline/v5/runPagespeed?url=' + pageSpeedMonitorUrl + '&key=' + pageSpeedApiKey + '&strategy=' + strategy;
var response = UrlFetchApp.fetch(pageSpeedUrl);
var json = response.getContentText();
return JSON.parse(json);}
I then push it into my sheet using:
function monitor() {
var desktop = callPageSpeed('desktop');
var mobile = callPageSpeed('mobile');
var spreadsheet = SpreadsheetApp.getActiveSpreadsheet();
var sheet = spreadsheet.getSheetByName('results');
sheet.appendRow([
Utilities.formatDate(new Date(), 'GMT+1', 'yyyy-MM-dd'),
desktop['lighthouseResult']['audits']['time-to-first-byte']['numericValue'].toFixed(0) + " ms"
//some other metrics go here
]);
Does anybody know what might cause this, and how I can overcome it?
The difference in the time average between your direct Browser execution call and the one in your Apps Script execution is due to Apps Script code runs in Google's servers and not in your local machine as the Docs say:
There's nothing to install—we give you a code editor right in your
browser, and your scripts run on Google's servers.
Take that into consideration when calling external APIs because it can have other side effects, besides time average differences like having an IP address that you can't assign.

How do I convert this google script to work offline?

I am trying to automate data entry while roaming offline using my Chromebook.
I know that google drive is enabled offline and a standalone script in GAS should in theory do the trick but im not sure how to put the pieces together. So far I have the below code which works perfectly online (gets stuck in "running" offline) and I've got the GAS app installed. Any guidance would be greatly appreciated!
function onOpen() {
var ui = SpreadsheetApp.getUi();
// Or DocumentApp or FormApp.
ui.createMenu('Invoice/Receipt System')
// creates a menu item "Submit Order"
.addItem('Record Invoice', 'menuItem1')
.addToUi();
}
function menuItem1() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var is = ss.getSpreadsheetByName("Template_Invoice");
var lastID = is.getRange("j6");
var nextID = is.getRange("j7");
var lastIDValue = lastID.getValue();
var source = ss.getSpreadsheetByName("Key_Invoice");
// sets the 'Key_DailyInput' Sheet as source
var target = ss.geSpreadsheetByName("DataBase_Invoice");
// sets 'Key_DailyInput' sheet as the target for copying data to.
var sourceData = source.getSheetValues(5,1,source.getLastRow(),15);
// sets range to gather source 'Key_DailyInput' data by finding last row, and Line 5 to Column 15
target.getRange(target.getLastRow()+1, 1, sourceData.length,15).setValues(sourceData);
// finds last row of target 'Orders' and writes to +1 row past last row up to column 15 using setValues of sourceData
// Following simply clears DailyInput so new data can be entered
is.getRange('C5:c8').clearContent();
is.getRange('G7:G8').clearContent();
is.getRange('B12:h28').clearContent();
is.getRange('b31:b34').clearContent();
// increases value by +1 so next Sales Order ID is incremented by 1
var cell = is.getRange("j6");
var cellValue = cell.getValue();
cell.setValue(cellValue + 1);
nextID.setValue(lastIDValue + 1);
}
As stated in other responses, the answer appears to be 'No'. However, while researching I did find the Command Line Interface for Apps Script (clasp) to manage and edit your projects offline. I'll post it here hoping it will be helpful to Apps Script developers.
CLASP Features
Develop Locally. clasp lets you write code on your own computer and upload it to Apps Script via command line when you're done. You can also download existing Apps Script projects and then edit them locally. Once the code is local, you can use your favorite development tools like git to work on Apps Script projects.
* Manage Deployment Versions.
* Create, update, and view multiple deployments of your project.
* Structure Code. clasp automatically converts your flat project on script.google.com into folders.
You can find more information on clasp at https://developers.google.com/apps-script/guides/clasp. However, you'll also need to activate the Linux(beta) on your Chromebook utilizing these instructions.
Short answer
Google Apps Script can't be ran offline because they run on the server-side.
Explanation
From https://developers.google.com/apps-script/overview
Google Apps Script is a scripting language based on JavaScript that
lets you do new and cool things with Google Apps like Docs, Sheets,
and Forms. There's nothing to install — we give you a code editor
right in your browser, and your scripts run on Google's servers.

edit google document remotely

I'm trying to add a feature to my website as follows:
Clicking a button appends text to a Google document.
Obviously I will need to create an Apps Script in the drive. The question is how to trigger the Apps Script from my website. You can assume that I am the owner of the drive/document and so have permissions to edit it in any way I like.
I have looked at these topics:
Workarounds : How to edit native google documents programatcally?item
How to programmatically manipulate native google doc files
It seems they are all actions performed from the drive itself and not triggered remotely.
I have also looked up the Apps Script API in Google but have not found a way to do this. Is it even possible?
Yes, it is possible.
First write an Apps script that changes your desired document. Then deploy it as a web-app running as you that anyone has access, even anonymous. Check out the guides at Apps Script page to see how to write your script as a web-app.
Your script will then have a public url, which you can call from your website and have it run "remotely" normally.
To provide an example of what Henrique suggests, here is a small webapp that adds text to a publicly viewable document I own (it doesn't need to be public except for anyone here to check it works !)
I wrote it using UiApp but you could of course use HTMLService if you prefer...
The app runs as me but is accessible to anyone even anonymous.
// publicly viewable test doc url : https://docs.google.com/document/d/1THzBTURxGr2CdUmcZ7i2zD-RM8I3im2JCSHI3BHlkeM/edit
function doGet(){
var app = UiApp.createApplication().setTitle('docEdit');
var panel = app.createAbsolutePanel().setSize('100%','100%').setStyleAttributes({'padding':'40px','backgroundColor':'lightBlue'});
var text = app.createTextArea().setName('text').setPixelSize(500,300);
var grid = app.createFlexTable().setId('grid');
grid.setText(0,0,'Add your text').setWidget(1,0,text);
var handler = app.createServerHandler('writeText').addCallbackElement(panel);
grid.setWidget(2,0,app.createButton('update document',handler).setId('btn'));
app.add(panel.add(grid));
return app;
}
function writeText(e){
var doc = DocumentApp.openById('1THzBTURxGr2CdUmcZ7i2zD-RM8I3im2JCSHI3BHlkeM');
var now = Utilities.formatDate(new Date(),Session.getScriptTimeZone(),'MMM/dd/yyyy # hh:mm:ss');
var body = doc.getBody();
body.appendParagraph('Append text on '+now+' : '+e.parameter.text);
doc.saveAndClose();
var app = UiApp.getActiveApplication();
var grid = app.getElementById('grid');
grid.setWidget(3,0,app.createHTML('Thanks,<br>Your text has been added to the document'));
app.getElementById('btn').setEnabled(false).setHTML('Button disabled');
return app;
}

Opening spreadsheet in google sheets

I'm trying to automate the creation of a spreadsheet in Google. I'm able to create and edit the spreadsheet just fine. The problem I'm having is opening.
function CoS(){
var Sheet = SSheet.getActiveSheet();
var bill = Sheet.getActiveCell().getValues();
var nSheet = NewCoS(bill);
var file = DocsList.getFileById(nSheet.getId());
var ss = SpreadsheetApp.open(file); //Doesn't work the way I need it to
Browser.msgBox(ss.getName());
}
I've tryed .openByUrl and .openById. In the documentation I read that these are for opening in the background but .open seems to do the same thing. However the documentation doesn't state explicitly that that is what it's meant for. Browser.msgbox() works so it seems logical that the file is getting opened in the background. I also can't find anything like Spreadsheet.visiblity() or Spreadsheet.show() as I would expect in excel.
I've even looked in other libraries like Drive and DocsList.
Is there a way to open my spreadsheet through script so that the user can see it?
Opening a spreadsheet means "get read and write access to that sheet", it does not mean "show this spreadsheet in my browser".
If you need to get such a functionality then use a href link (in HTMLService) or an anchor widget (in UiApp) that will redirect you to another browser tab/window with that spreadsheet.
Note also that there is no SpreadsheetApp.open method, use the autocompletion in the script editor to be sure about available methods in Google Apps Script.

How do I get a remote source to work with an autocomplete?

Is it possible to add an autocomplete in a google spreadsheet script with a remote source?
Below is one of my attempts to do so but I have no idea where to go from here (I am a newb to google scripts):
function my_autocomplete(){
var list = ['dog','doog'];
var app = UiApp.createApplication();
var suggestBox = SuggestBoxCreator.createSuggestBox(app,'autocompleter',200,list);
app.add(suggestBox);
var doc = SpreadsheetApp.getActive();
doc.show(app);
}
I've googled my heart out but can't find a single example of an autocomplete with a remote source that is compatible with Google Scripts...is it even possible?
(I don't have to use/modify the autocomplete example I have above, so if there's another approach I'm all ears! thx!)
Google suggestboxcreator and you will find this https://sites.google.com/site/scriptsexamples/learn-by-example/uiapp-examples-code-snippets/suggest-box. Use that library, thou it does the search server side. Make one with htmservice and do it client side so its faster. Write the selected value into the active cell of the active spreadsheet.