To download (or print) in [[Google Sheets]], you can either create a [[print link]] and embed the link in rich text within a cell, or use this function. However, you cannot assign this script to a button in Google Sheets. Instead, you must launch a dialog box with a button for the user to download the document. You'll use [[scriptlets]] to pass the download link to the HTML.
First, the function to construct a print link for a spreadsheet.
```javascript
function getDownloadURL() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheetId = ss.getActiveSheet().getSheetId();
var url = "https://docs.google.com/spreadsheets/d/"
+ ss.getId() + "/export?exportFormat=pdf&gid=" + sheetId
+ "&range=" + PRINT_RANGE_NAME
+ "&size=letter"
+ "&portrait=true"
+ "&fitw=true"
+ "&gridlines=false"
+ "&printnotes=false"
+ "&printtitle=true"
+ "&pagenum=RIGHT";
return url
}
```
Next, the function to launch the dialog box. You can create a [[custom menu]] item or [[assign the script to a button]].
```javascript
function downloadSheetAsPDF() {
// populate and show modal with download button
let url = getDownloadURL();
const tmp = HtmlService.createTemplateFromFile('download');
tmp.url = url;
let html = tmp.evaluate()
.setWidth(400)
.setHeight(350)
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
SpreadsheetApp.getUi().showModalDialog(html, 'Click to Download');
}
```
Finally, the download link in the dialog box, which is stored in this example in a file called `download.html`. The scriptlet `<?= url>` gets the URL constructed by `getDowloadURL()` and passed to the HTML template in `downloadSheetAsPDF`.
```html
<a href=<?= url ?>>Click to Download</a>
```
You'll need to build out the rest of the dialog box as a full HTML file. You can also assign the link to a button (hint: try [[Bootstrap]]).