0

Needing users to view PDF version of the Google Sheet they have just saved to Google Drive via the function below. How do I add in a view PDF function within this code? Online suggestions are not working entirely.

function checkSheet() {
  var sheetName = "POTemplate";
  var folderID = "Eric";
  var sourceSpreadsheet = SpreadsheetApp.getActive();
  var sourceSheet = sourceSpreadsheet.getSheetByName(sheetName);
  var poNo = sourceSheet.getRange("b2").getValue();
  var pdfName = "Sample PO Hi Eric - Happy Valentine's" + poNo;
  var folder = DriveApp.getFoldersByName(folderID);
  var destSpreadsheet = SpreadsheetApp.open(DriveApp.getFileById(sourceSpreadsheet.getId()).makeCopy(folder));
  var sheets = destSpreadsheet.getSheets();
  for (i = 0; i < sheets.length; i++) {
   if (sheets[i].getSheetName() != sheetName){
     destSpreadsheet.deleteSheet(sheets[i])}};                                                                                               
  var theBlob = 
destSpreadsheet.getBlob().getAs('application/pdf').setName(pdfName);
  var newFile = folder.next().createFile(theBlob);
  DriveApp.getFileById(destSpreadsheet.getId()).setTrashed(true);
}
Eric K.
  • 121
  • 3
  • 17
  • The Drive API has the following function like [Open Files](https://developers.google.com/drive/v3/web/integrate-open) and [Download Files](https://developers.google.com/drive/v3/web/manage-downloads) that I think you can utilize, but, as what this [SO post](https://stackoverflow.com/questions/42367384/view-pdf-file-on-local-server-using-google-api) implied, you cannot view files without downloading it. Hope this helps. – MαπμQμαπkγVπ.0 Feb 15 '18 at 10:51

1 Answers1

0

To add a view function you can get the link to the new file using file.getUrl() and present the link to the user in a dialog box like so

  var strUrl = newFile.getUrl()
  var html = HtmlService.createTemplateFromFile("NewTab")
  html.strUrl = strUrl
  SpreadsheetApp.getUi().showModelessDialog(html.evaluate(), "Pdf Link")

You Html file NewTab will be coded like so

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
    <a href ="<?!= strUrl ?>"> Link </a> to your PDF File
  </body>
  <script>
    var evLink = document.getElementsByTagName('a')[0]
    //evLink.click();  //If you try to programmatically activate link,
    // pop-up blocker stops the link from opening.
   </script>
</html>

Reference:
file.getUrl()
Dialog box
SO query on opening new tab/link

Jack Brown
  • 5,802
  • 2
  • 12
  • 27
  • Thanks, Jack! Just a quick question...is it possible to view the Google Sheet (in PDF format) before saving to Google Drive via script? If yes, I will post a question on this separately. – Eric K. Feb 16 '18 at 15:18
  • Yes, it can be done. Also, if this answers your question consider accepting the answer as mentioned [here](https://stackoverflow.com/help/someone-answers) – Jack Brown Feb 16 '18 at 18:16