Skip to content
Advertisement

Problems downloading base64 as pdf JavaScript

I’m writing a Google Apps Script Web App, I’m facing a problem.

From server side I return the base64 encoded html code of a page:

function getRAW() { 
  var formText = 'https://www.google.com/';
  var response = UrlFetchApp.fetch(formText);
  var pdf1 = response.getAs('application/pdf');
  //var myNewFile = DriveApp.createFile(pdf1);
  var blob = response.getBlob()
  var bytes = blob.getBytes();
  var encoded = Utilities.base64Encode(bytes);
  return encoded
}

And that works well. Now, from client side, I want to download the base64 (is an html RAW content) as a pdf file (or .html if it is possible), but If I try to do like this I obtain a blank pdf page

function downloadRAW() {
  var encoded = window.value;
  var element = document.createElement('a');

  element.setAttribute('href', 'data:application/pdf;base64,' + encoded);
  element.setAttribute('download', 'prova');
  element.style.display = 'none';
  document.body.appendChild(element);

  element.click();

  document.body.removeChild(element);
}

Note that If I try to obtain a text/plain;base64, works perfectly (return a .txt) file; but this is not what I want.

How can I achieve it?

Advertisement

Answer

Even if the proposed solution by @Tanaike is very good, I do not want to use additional permission on writing file in the Google Drive of the user (since my script is executed as “Run as user”), so I decided to use JsPDF.

Client-side code:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.2/jspdf.min.js"></script>

function downloadRAWPDF() {
    // window.value is a global variable that contains base64 encoded content (passed from server)
    var encoded = window.value;
    var decoded = atob(encoded);
    
    var doc = new jsPDF();

    // Resize text to fit in an A4 page
    var splitTitle = doc.splitTextToSize(decoded, 270);
    var pageHeight = doc.internal.pageSize.height;
    doc.setFontType("normal");
    doc.setFontSize("11");
    var y = 7;
    for (var i = 0; i < splitTitle.length; i++) {                
        if (y > 280) {
            y = 10;
            doc.addPage();
        }
        doc.text(15, y, splitTitle[i]);
        y = y + 7;
    }

    doc.save('myPDF.pdf');
}

Server-side code (Google Apps Script):

// @return RAW Response base64 encoded (without response headers)
function getRAW(formObject) { 
  // contains the value of an Input Field
  var formText = formObject.myInput;
  
  var response = UrlFetchApp.fetch(formText);
  var blob = response.getBlob()
  var bytes = blob.getBytes();
  var encoded = Utilities.base64Encode(bytes);
  
  return encoded
}

To convert the file in a html file the approach suggested by @Tanaike is perfect: data:text/html;base64, + encoded

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement