How to autodownload HTML as PDF file to desktop without export to GDrive using Appscript

Viewed 38

Let's use this as the HTML :

<html>
    <body>
       <h1>$custName Invoice</h1>
<table>
  <tr style="background-color: black;">
    <th>PRODUCT</th>
    <th>SIZE</th>
    <th>PRICE</th>
    <th>DISCOUNT</th>
    <th>QTY</th>
    <th>SUBTOTAL</th>
  </tr>
  $custData
</table>
    </body>
</html>

As i have many customers i want to build a report for each customer's invoice as PDF and save them in my local drive (without export them to GDrive). Here is my function as far as i can get :

function createPDF() {
    var ws = SpreadsheetApp.getActiveSpreadsheet();
    var xs = ws.getSheetByName('Nota');
    var lr = xs.getLastRow();
    var list = xs.getRange('B2:C'+lr).getValues();
    var allList = list.map(function(r){return r[0]});
    var filtered = list.filter(list => list[0]!='' && list[1] === '');
    var nota = filtered.map(function(r){return r[0]});

    nota.forEach(function(invoice){
      
     downloadPdfToDesktop(noInvoice) 

    });

}

function downloadPdfToDesktop(noInvoice) {

  var val = noInvoice;//custom pdf name here 
  val += '.pdf';
  // Creat PDF file as a temporary file and create URL for downloading.
  var htmlBody = HtmlService.createHtmlOutputFromFile('report').getContent().replace($custName,noInvoice);
  var blob = Utilities.newBlob(htmlBody, 'text/html').getAs('application/pdf').setName(val);
  
  DriveApp.createFile(blob);
  var file = DriveApp.createFile(blob);
  var url = "https://drive.google.com/uc?export=download&id=" + file.getId();
  
  //can't download with a different filename directly from server
  //download and remove content-disposition header and serve as a dataURI
  //Use anchor tag's download attribute to provide a custom filename
  var res = UrlFetchApp.fetch(url, {
    headers: { Authorization: 'Bearer ' + ScriptApp.getOAuthToken() },
  });
  SpreadsheetApp.getUi().showModelessDialog(
    HtmlService.createHtmlOutput(
      '<a target ="_blank" download="' +
        val +
        '" href = "data:application/pdf;base64,' +
        Utilities.base64Encode(res.getContent()) +
        '">Click here</a> to download, if download did not start automatically' +
        '<script> \
        var a = document.querySelector("a"); \
        a.addEventListener("click",()=>{setTimeout(google.script.host.close,10)}); \
        a.click(); \
        </script>'
    ).setHeight(50),
    'Downloading PDF..'
  );
}

But the result of those function are store the PDF files in my Gdrive with the PDF's content as i created and did download in my local device but the PDF is error (Failed to load PDF Document*). *image attached enter image description here

Hope someone can help me with my problem. God bless us :).

1 Answers

Maybe it has something to do with a delay.

Last week I created a PDF in a Google Apps Script using UrlFetchApp() and had to insert a short delay between filling the tempSheet and creating the pdf:

My code:

  //Cleans up and creates PDF.
  SpreadsheetApp.flush();
  Utilities.sleep(500); // Using to offset any potential latency in creating .pdf
  var url = ssTemp.getUrl();

I think you need to adapt this code for your situation and then insert it before creating pdf

Related