Home > other >  How can I pass a base64 pdf to the server-side in Google Apps Script?
How can I pass a base64 pdf to the server-side in Google Apps Script?

Time:09-27

Overall Goal

  1. Generate a pdf of the currently displayed html page;
  2. Pass it to the server-side;
  3. Save into a specific Google Drive

Item 2 is the one I'm having trouble with!

I'm using this to try to get the converted file passed to the server-side:

Client Side

function saveToGDrive(){
var element = document.getElementById('pgBody');
var opt = {
  margin: 1,
  filename: 'myfile.pdf',
  image: {
    type: 'jpeg',
    quality: 0.98
  },
  html2canvas: {
    scale: 5
  },
  jsPDF: {
    unit: 'in',
    format: 'A4',
    orientation: 'landscape'
  }
};

const pg = html2pdf().set(opt).from(element).outputPdf().then(function(p) {
    console.log('PDF file: '   typeof btoa(p))
    return btoa(p);
});
google.script.run.savePdf(pg)
}

Item 2 gives me the error: Failed due to illegal value in property: state and I'm taking the variable pg is too large to be passed as a parameter like this.

Appreciate any help!

CodePudding user response:

When your showing script is modified, how about the following modification?

From:

const pg = html2pdf().set(opt).from(element).outputPdf().then(function(p) {
    console.log('PDF file: '   typeof btoa(p))
    return btoa(p);
});
google.script.run.savePdf(pg)

To:

html2pdf().set(opt).from(element).outputPdf().then(function(p) {
  google.script.run.savePdf(btoa(p));
});
  • When this script is run, the base64 data of btoa(p) is sent to the Google Apps Script side.

  • When savePdf is the following script, the base64 data is converted to a Blob and saved as a PDF file on Google Drive.

      const savePdf = e => DriveApp.createFile(Utilities.newBlob(Utilities.base64Decode(e), MimeType.PDF).setName("samplename.pdf"));
    
  • Related