skaarj
skaarj

Reputation: 100

Download PDF from google.script.run in web app

What I'm trying to achieve is to download sheet as .PDF file from google script web app, but I have a problem: output file has (probably) wrong encoding (UTF-8 also doesn't work).

Example:

Good file: downloaded from link with "export?exportFormat=pdf..."

%PDF-1.4
% âăĎÓ
4
0
obj
<<
/Type
/Catalog
/Names
<<
/JavaScript
3

...

Corrupted file:

%PDF-1.4
% ????
4
0
obj
<<
/Type
/Catalog
/Names
<<
/JavaScript
3

...

Did anyone experienced similar problem? How can I solve it? Thank you in advance.

Google script:

function doGet(e) {
    return HtmlService.createTemplateFromFile('index').evaluate();
}

function test() {
  var spreadsheet = SpreadsheetApp.getActiveSpreadsheet(),
      sheet = spreadsheet.getActiveSheet();

  var url = spreadsheet.getUrl().replace(/edit$/, '');
  var url_ext = 'export?exportFormat=pdf&format=pdf&gid=' + 
                 sheet.getSheetId();

  var options = {
    headers: {
      'Authorization': 'Bearer ' +  ScriptApp.getOAuthToken(),
    }
  };

  var response = UrlFetchApp.fetch(url + url_ext, options);
  var blob = response.getBlob();

  var charset = 'ISO-8859-1';
  var str = blob.getDataAsString(charset);

  return Utilities.base64Encode(str);
}

HTML JavaScript (index.html):

...

function downloadURI(uri, name) {
  var link = document.createElement('a');
  link.download = name;
  link.href = uri;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  delete link;
}

google.script.run.withSuccessHandler((data) => {

  var uri = 'data:application/pdf;charset=ISO-8859-1;base64,' + encodeURIComponent(data);
  downloadURI(uri, 'test.pdf');

}).withFailureHandler((err) => {
  console.log(err);
}).test();

https://docs.google.com/spreadsheets/d/1kCcxRbucbvKRSCMC4fNj9NJbjTJHTTBFXP7TLGmDNtQ/

Upvotes: 0

Views: 3119

Answers (1)

Tanaike
Tanaike

Reputation: 201378

When the blob of var blob = response.getBlob() is created as a PDF file using DriveApp.createFile(blob), if you can see the PDF completely, how about this modification?

From :

var blob = response.getBlob();
var charset = 'ISO-8859-1';
var str = blob.getDataAsString(charset);
return Utilities.base64Encode(str);

To :

var blob = response.getBlob();
return Utilities.base64Encode(blob.getBytes());

Reference :

If this was not the direct solution for your issue, I'm sorry.

Upvotes: 1

Related Questions