Google UI Apps Script: Blank PDF when converting spreadsheet to PDF - pdf

I have a piece of code I am testing, in an attempt to learn how to convert a spreadsheet into a pdf using Google UI Apps Script. The code creates and writes to the spreadsheet but the pdf attachment is blank. Would appreciate any help to get this to work. Thanks.
var newSpreadsheet = SpreadsheetApp.create("My Test Sheet");
var columnNames = ["First Name", "Last Name", "Department"];
newSpreadsheet.getSheetByName('Sheet1').activate();
var headersRange = newSpreadsheet.getActiveSheet().getRange(1, 1, 1, columnNames.length);
headersRange.setValues([columnNames]);
var pdf = DocsList.getFileById(newSpreadsheet.getId()).getAs('application/pdf').getBytes();
var attach = {fileName:'My Test PDF.pdf',content:pdf, mimeType:'application/pdf'};
// Send email
MailApp.sendEmail("myemail#email.com", "subject", "message", {attachments:[attach]});

You should not use DocList anymore. Use DriveApp instead. Below a solution with little modifications of your code:
function toPdf(id){
SpreadsheetApp.flush();
// var ssDoc = DriveApp.getFileById(SpreadsheetApp.getActiveSpreadsheet().getId());
var ssDoc = DriveApp.getFileById(id);
var pdf = DriveApp.createFile(ssDoc.getAs(MimeType.PDF));
return pdf.getBlob().getBytes();
}
function user2943227(){
var newSpreadsheet = SpreadsheetApp.create("My Test Sheet");
var columnNames = ["First Name", "Last Name", "Department"];
// newSpreadsheet.getSheetByName('Sheet1').activate();
var headersRange = newSpreadsheet.getActiveSheet().getRange(1, 1, 1, columnNames.length);
headersRange.setValues([columnNames]);
// var pdf = DocsList.getFileById(newSpreadsheet.getId()).getAs('application/pdf').getBytes();
var pdf = toPdf(newSpreadsheet.getId());
var attach = {fileName:'My Test PDF.pdf',content:pdf, mimeType:'application/pdf'};
// Send email
MailApp.sendEmail("myemail#email.com", "subject", "message", {attachments:[attach]});
}

Related

Why is my PDF showing multiple sheets from my workbook?

I put together a script to turn a google sheet into a pdf and email at the click of a button. Instead of just sending the front page, it is capturing all of the back end data as well leaving me with multiple page pdfs rather than the one front page I want.
Here is what I have right now.
function sendrequest() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var recipientsheet = ss.getSheetByName("ref")
var recipients = recipientsheet.getRange("I2:I3")
var pdfsheet = ss.getSheetByName("request_form")
var date = pdfsheet.getRange("B8")
var message = {
to: "ryan#email.com" ,
subject: "Inventory Movement Request" ,
body: "New Inventory Movement Request",
name: " ",
attachments: [ss.getAs(MimeType.PDF).setName("Movement Request")]
}
MailApp.sendEmail(message);

Saving one sheet as PDF in Google Drive (for all Users)

I made an Excel Sheet in Google Drive to be used by 15 Peoples. The function is that the macro should create a PDF from the Sheet and send it to peoples as Mail. But I want to make a copy as PDF in Google Drive where can I see all of this persons permissions to see all of the sent Mails.
I must say that I am a beginner for this macro thing, I tried 2 codes but I always get the same Error.
function TEST2()
{
var Datum = Utilities.formatDate(new Date(), "GMT+2", "dd.MM.YYYY HH:mm");
var as = SpreadsheetApp.getActive();
var newas = SpreadsheetApp.create("XX");
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("XX");
sheet = as.getSheetByName("XX");
sheet.copyTo(newas);
newas.getSheetByName('XX');
newas.deleteActiveSheet();
var pdf = DriveApp.getFileById(newas.getId()).getAs('application/pdf').getBytes();
var anhang = {fileName:("XX Order" + Datum + ".pdf"),content:pdf,mimeType:'application/pdf'};
var folderID = "TEST FOLDER";
var folder = DriveApp.getFolderById(folderID);
var newFile = DriveApp.createFile(folder);
newFile;
MailApp.sendEmail(
{
to: "Mail Adress",
subject: "XX Order " + Datum,
htmlBody: "XX - Order ",
attachments: anhang
})
SpreadsheetApp.getUi().alert('Mail wurde versendet ' + Datum)
//Delete the temporary sheet
DriveApp.getFileById(destSpreadsheet.getId()).setTrashed(true);
}
I always get the same Error message. That the script cannot find a document with this ID.
Ok i found the solution :)
var folderID = "XXX BESTELLUNG";
var folderID2 = "XXX Bestellung";
var folder = DriveApp.getFoldersByName(folderID);
var theblob = newas.getBlob().getAs('application/pdf').setName('XXX Bestellung ' + Datum);
var newFile = folder.next().getFoldersByName(folderID2).next().createFile(theblob);
when i change the code in this case, i get the solution whicht i want :)

Acumatica: How do I get an attachment file from SO Screen using Web API?

I'd folow the example From I200 pdf for a stock item, but I dont' know how to download the file from an Sales Order. Does anybody has a clue?
IN202500Content stockItemSchema = context.IN202500GetSchema();
var commands = new Command[]
{
new Value
{
Value = "AAMACHINE1",
LinkedCommand = stockItemSchema.StockItemSummary.InventoryID
},
new Value
{
FieldName = "T2MCRO.jpg",
LinkedCommand =
stockItemSchema.StockItemSummary.ServiceCommands.Attachment
}
};
var stockItemAttachment =
context.IN202500Export(commands, null, 1, false, true);
You were almost there, in the "stockItemAttachment" variable you should have the content of the file "T2MCRO.jpg" in byte format.
The only thing you have left to do is to write it to your file system.
You can use the following command :
File.WriteAllBytes(Path, Convert.FromBase64String(stockItemAttachment[0][0]));

Create PDF File with DriveApp.createFile with results of UrlFetchApp.fetch

I cannot create a PDF file in my Google Drive from content retrieved using UrlFetchApp.fetch
If I email the same file attached It arrives properly.
Here is my code:
var codigo ="1100016795766";
var url = "http://do.convertapi.com/Web2Pdf";
var headers = {"Content-Type":"multipart/form-data"
};
var payload= {"ApiKey":"xxxxxxxx",
"CUrl":"http://www.correos.cl/SitePages/seguimiento/seguimiento.aspx?envio="+codigo,
"LowQuality":true
}
var options = { "method":"POST",
"headers": headers,
"payload":payload,
"muteHttpExceptions":false
};
var pdf0=UrlFetchApp.fetch(url,options);
//trying several ways
var pdf=pdf0.getContent();
var pdf1=pdf0.getAs('application/pdf');
var pdf2=pdf0.getAs("application/pdf");
var pdf3=pdf0.getContentText();
//Trying several ways, none of them get a valid PDF file
DriveApp.createFile("8track_correos.pdf", pdf, 'application/pdf');
DriveApp.createFile("9track_correos.pdf", pdf0,'application/pdf');
DriveApp.createFile("1track_correos.pdf", pdf1, MimeType.PDF);
DriveApp.createFile("2track_correos.pdf", pdf1, MimeType.PDF);
DriveApp.createFile("4track_correos.pdf", pdf3);
DriveApp.createFile("7track_correos.pdf", pdf2);
DriveApp.createFile("6track_correos.pdf", pdf1);
//The attached file arrives as a good PDF file
MailApp.sendEmail("user#gmail.com", "prueba de enviar PDF", "k", {attachments:[{fileName:prefijo+p_nombre+p_apellido+"track_correos.pdf", content:pdf, mimeType:"application//pdf"}]});
The only createFile() configuration that allows a blob as the file source is:
DriveApp.createFile(blob);
So, you need to use:
var pdf0 = UrlFetchApp.fetch(url,options);
var pdf1 = pdf0.getAs('application/pdf');
var myNewFile = DriveApp.createFile(pdf1);
myNewFile.setName("track_correos.pdf");

Undefined merge field in google apps script

I have a Google Apps Script for a Google Spreadsheet based on a Google Form that clients fill out online. The script is triggered by OnFormSubmit and generates a pdf based on a Google Doc template and sends the pdf to me by email using MailApp.sendEmail.
This script has been working fine until recently. The script runs successfully but the pdf output is incorrect. It seems like fields that are left blank are now being ignored in the script and so my pdf output shows the value for the next non-blank field. Ugh!
Anybody know what's going on here?
Below is an example of my script:
var docTemplate = "1FZL4rVe0LLpvMtIsq_3-pwv5POllIsyYThjfemkbkfg";
var docName = "Travel Details";
function onFormSubmit(e) {
var last = e.values[1];
var first = e.values[2];
var order = e.values[3];
var date = e.values[4];
var gender = e.values[5];
var email = "example#gmail.com";
var copyId = DocsList.getFileById(docTemplate)
.makeCopy(docName+' for '+last + ', ' + first)
.getId();
var copyDoc = DocumentApp.openById(copyId);
var copyBody = copyDoc.getActiveSection();
copyBody.replaceText('keyLast', last);
copyBody.replaceText('keyFirst', first);
copyBody.replaceText('keyOrder', order);
copyBody.replaceText('keyDate', date);
copyBody.replaceText('keyGender', gender);
copyDoc.saveAndClose();
var pdf = DocsList.getFileById(copyId).getAs("application/pdf");
MailApp.sendEmail(email, subject, "", {htmlBody: office_message, attachments: pdf,
noReply:true});
DocsList.getFileById(copyId).setTrashed(true);
}
Example of the problem: If client leaves date field blank on the form, the gender value in the resulting pdf is put where the date value should be and the value for gender on the pdf shows "undefined".
Any ideas out there?
You should validate the values of all your variables.
if (last === undefined) {
last = 'No Data!'; //re-assign a different value
};
So, you are changing the value of the variable last if it somehow got set to undefined. That way, hopefully the pdf would still show the field.
If there is some bug that just showed up recently, you should report it as a bug. If everything was working fine, and now it's broken, Google may have changed something.
There might be something wrong with your code. I don't know. Have you looked under the "View" menu and the "Execution Transcript" to see if there are any errors? You should also use Logger.log statements: Logger.log('The value of last is: ' + last); to print output to the log. Then you can check what is actually going on.
I am no great coder but I use this script all the time to send pdf's I have never received an undefined if a field was missing. Typically if something is missing, the keygender is replaced with a blank spot and there is no error. In a spreadsheet, typically this means the columns were changed. It used to be timestamp(0), last(1), first(2), order(3), date(4), gender(5) and now their in a different order.
Try the below code it works
//commons errors -
//Triggers are not set
//spaces after Form questions
//e.values dont work when fields are not mandatory and left blank
//e.namedValues dont work for sending emails use e.values[#]
//place holder keys in template dont match
//spelling errors
//Note expect undefined error when de-bugging as values are not defined until form completed and submitted - run first with a small test form as per below
// Get Template
//from Google Docs and name it
var docTemplate = " "; // *** replace with new templae ID if new Template created***
var docName = "Test Script"; //replace with document name
// When Form Gets submitted
function onFormSubmit(e) {
//Get information from the form and set as variables
//var variablename = "static entry or form value"
//Note: var Variablename = e.namedValues["X"]; is taking the value from the spreadsheet by column name so update if spreadsheet or form questions change
//Additions to the form will be added to the end of the spreadsheet regardless of their position in the form
var Timestamp = e.namedValues["Timestamp"];
var full_name = e.namedValues["Name"];
var position = e.namedValues["Position"]
var contact_email = e.namedValues["Contact Email"];
var phone_number = e.namedValues["Telephone Number"];
// Get document template, copy it as a new doc with Name and email, and save the id
var copyId = DocsList.getFileById(docTemplate)
.makeCopy(full_name+' '+docName+' for ' +contact_email+' '+Timestamp)//Update or remove Variablename to create full doc Name
.getId();
// Open the temporary document
var copyDoc = DocumentApp.openById(copyId);
// Get the documents body section
var copyBody = copyDoc.getActiveSection();
// Replace place holder keys <<namedValues>> in template
//copyBody.replaceText('<<X>>', Variablename); Variables from above
//***Update if template is changed***
copyBody.replaceText('<<Timestamp>>', Timestamp);
copyBody.replaceText('<<Name>>', full_name);
copyBody.replaceText('<<Position>>', position);
copyBody.replaceText('<<Contact Email>>', contact_email);
copyBody.replaceText('<<Telephone Number>>', phone_number);
// Save and close the temporary document
copyDoc.saveAndClose();
// Convert temporary document to PDF by using the getAs blob conversion
var pdf = DocsList.getFileById(copyId).getAs("application/pdf");
{
// Add the data fields to the message
var s = SpreadsheetApp.getActiveSheet();
var columns = s.getRange(1,1,1,s.getLastColumn()).getValues()[0];
var message = " ";
// Only include form fields that are not blank
for ( var keys in columns ) {
var key = columns[keys];
if ( e.namedValues[key] && (e.namedValues[key] != "") ) {
message += key+ ' : '+ e.namedValues[key] + "<br>";
}
}}
// Attach PDF and send the email
//***Change the "To" email address when to form goes live***
var to = "youremail#gmail.com";
var senders_name = e.values[1]
var contact_email = e.values[3]
var subject = "Test";
var htmlbody = "text goes here"+
"<br> <br>"+message+
"<br> <br>Submitted By:"+
"<br> <br>"+full_name+
"<br>"+position+
"<br>"+contact_email+
"<br>"+phone_number+
"<br> <br>Generated by Hansmoleman for Compu-Global-Hyper-Mega-Net";
MailApp.sendEmail({
name: senders_name,
to: to,
cc: contact_email,
replyTo: contact_email,
subject: subject,
htmlBody: htmlbody,
attachments: pdf,
});
}