-1

I am using this script to print and email a pdf that is made from a google sheet. It was working and printing the image which is a company logo, but now it stopped and I can't figure out why. The only thing I can think I changed was the "function setTimeout" function to get around a "[ReferenceError: setTimeout is not defined]" problem I was having. Can anyone help with why this is not printing photos on the pdf anymore?

function deleteCreator_(blob) {
  const cdnjs = "https://cdn.jsdelivr.net/npm/pdf-lib/dist/pdf-lib.min.js";
  const pdfLibCode = UrlFetchApp.fetch(cdnjs).getContentText().replace(/pdf-lib \(https:\/\/github\.com\/Hopding\/pdf-lib\)/g, "My Company Encoding");

  eval(pdfLibCode);

  return new Promise(async (resolve, reject) => {
    try {
      const pdfDoc = await PDFLib.PDFDocument.load(new Uint8Array(blob.getBytes()), { updateMetadata: true });
      pdfDoc.setCreator("My Custom PDF"); // CHANGE THIS TO SET METADATA
      const bytes = await pdfDoc.save();
      const newBlob = Utilities.newBlob([...new Int8Array(bytes)], MimeType.PDF, blob.getName());
      resolve(newBlob);
    } catch (e) {
      reject(e);
    }
  });
}



function mailPdf(shNum, shRng, pdfName, email, subject, htmlbody) {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var ssId = ss.getId();
  var shId = shNum ? ss.getSheets()[shNum].getSheetId() : null;
  var url_base = ss.getUrl().replace(/edit$/, '');
  var url_ext = 'export?exportFormat=pdf&format=pdf'   //export as pdf
    + (shId ? ('&gid=' + shId) : ('&id=' + ssId))
    + (shRng ? ('&range=' + shRng) : '') // Modified to use the dynamic range
    + '&format=pdf'
    + '&size=letter'                      //A3/A4/A5/B4/B5/letter/tabloid/legal/statement/executive/folio
    //+ '&portrait=false'               //true= Potrait / false= Landscape
    //+ '&scale=1.1'                      //1= Normal 100% / 2= Fit to width / 3= Fit to height / 4= Fit to Page
    + '&top_margin=0.5'                 //All four margins set to 0.5 inches
    + '&bottom_margin=0.5'
    + '&left_margin=0.5'
    + '&right_margin=0.5'
    + '&gridlines=false'              //true/false
    //+ '&printnotes=false'             //true/false
    //+ '&pageorder=2'                  //1= Down, then over / 2= Over, then down
    //+ '&horizontal_alignment=CENTER'  //LEFT/CENTER/RIGHT
    + '&vertical_alignment=TOP'       //TOP/MIDDLE/BOTTOM
  //+ '&printtitle=false'             //true/false
  //+ '&sheetnames=false'             //true/false
  //+ '&fzr=false'                    //true/false frozen rows
  //+ '&fzc=false'                    //true/false frozen cols
  //+ '&attachment=false'             //true/false
  var options = {
    headers: {
      'Authorization': 'Bearer ' + ScriptApp.getOAuthToken(),
      'muteHttpExceptions': true
    }
  }
  var response = UrlFetchApp.fetch(url_base + url_ext, options);
  var blob = response.getBlob().setName(pdfName + '.pdf');
  if (email) {

    // --- I modified the below script.
    deleteCreator_(blob)
      .then(b => {
        var mailOptions = { attachments: [b], htmlBody: htmlbody }
        MailApp.sendEmail(
          // email + "," + Session.getActiveUser().getEmail() // use this to email self and others
          email,                                              // use this to only email users requested
          subject + ' (' + pdfName + ')',
          'html content only',
          mailOptions
        );
      })
      .catch(err => console.log(err));
    // ---

  }
}


// ADDED IN MYFUNCTION 
function myFunction() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var makerSheet = ss.getSheetByName("Maker");
  var pdfSheet = ss.getSheetByName("Maker");
  var sheetNameToExport = "PDF2"; // Replace this with the name of the sheet to export (e.g., "PDF")
  var lastRow = makerSheet.getRange('F1').getValue();
  var rangeToExport = "A1:F" + lastRow; // Replace this with the desired range address in A1 notation
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var makerSheet = ss.getSheetByName("Maker");
  var taxRate = makerSheet.getRange('B16').getValue()
  var priceList = makerSheet.getRange('B8').getValue()
  var pdfName = makerSheet.getRange('B6').getValue() + " Estimate"; // Gets the desired name for the PDF
  var recipientEmail = makerSheet.getRange('B7').getValue(); // Gets the email address of the recipient
  var emailSubject = makerSheet.getRange('B6').getValue(); // Gets the subject of the email
  var htmlBodyContent = "This is a test run<br><br> Price List Used " + priceList + " with a tax rate of " + taxRate + "<br><br>"; // body of the email

  // Find the index of the sheet by its name
  var sheets = SpreadsheetApp.getActiveSpreadsheet().getSheets();
  var sheetIndex = sheets.findIndex(function (sheet) {
    return sheet.getName() === sheetNameToExport;
  });

  if (sheetIndex !== -1) {
    // Call the mailPdf function with the provided parameters
    mailPdf(sheetIndex, rangeToExport, pdfName, recipientEmail, emailSubject, htmlBodyContent);
    Logger.log("Emailed " + sheetNameToExport);
  } else {
    Logger.log("Sheet not found: " + sheetNameToExport);
  }
}
function setTimeout(callback, delay) {
  Utilities.sleep(delay);
  callback();
}
  • I think that your showing script is from [my answer](https://stackoverflow.com/a/76742023) in your previous question. And, about `[ReferenceError: setTimeout is not defined]`, I think that you don't correctly use my proposed script. I have to apologize for this. Please add `const setTimeout = function (f, t) {Utilities.sleep(t); return f();};`. And, how will you do your previous question? https://stackoverflow.com/q/76739862 – Tanaike Aug 03 '23 at 23:51
  • Just updated the script, now a new problem. Sometimes, not always the photo on the header (company Logo) sometimes prints normal, sometimes prints in landscape. Probably the sizing of the .jpg that is in the cell but is there a setting to change so it won't do this? – John Velella Aug 04 '23 at 14:47
  • Thank you for replying. About your new question of `Just updated the script, now a new problem. Sometimes, not always the photo on the header (company Logo) sometimes prints normal, sometimes prints in landscape. Probably the sizing of the .jpg that is in the cell but is there a setting to change so it won't do this?`, I would like to support you. – Tanaike Aug 04 '23 at 23:28
  • But, that is a new question. So, can you post it as new question? If you can cooperate to resolve your new issue, I'm glad. Can you cooperate to resolve your new question? And, how will you do your previous question? And, how will you do your previous question? https://stackoverflow.com/q/76739862 Unfortunately, I couldn't understand the answer of my question from your reply. I deeply apologize for my poor English skill. – Tanaike Aug 04 '23 at 23:28

0 Answers0