File can not be attached to the Email when we try to send an email with Kotlin? - kotlin

The following code is working while using Jetpack Kotlin.
But there is a little problem it can not attach pdf file.
When email button clicked opened view with Gmail and Drive icon at bottom shows
the pdf file name as test.pdf at top.
But when we choose gmail at bottom everything filled correctly except test.pdf.
It is not attached to the email form and then can not be emailed.
Button(onClick = {
val i = Intent(Intent.ACTION_SEND)
i.type = "vnd.android.cursor.dir/email"
val emailAddress = arrayOf("testEmailAddress#gmail.com")
i.putExtra(Intent.EXTRA_EMAIL,emailAddress)
val name = FileWorks().createFileName(context = cx, dirName = "calc", fileName = "test.pdf")
val contentUri = name.toURI()
i.putExtra(Intent.EXTRA_STREAM, Uri.parse(name.toString()))
i.putExtra(Intent.EXTRA_SUBJECT,"subject")
i.putExtra(Intent.EXTRA_TEXT,"body")
i.setType("message/rfc822")
ctx.startActivity(Intent.createChooser(i,"Choose an Email client : "))
}

Related

Kotlin VideoView path with a changing resource name

I have a group of mp4 files (v1.mp4, v2mp4,...) inside the raw folder.
I need to read them randomly after a button is clicked.
I get the message "not possible to play this video".
If I point to a specific file in the setVideoPath, ("android.resource://" + packageName + "/" + R.raw.v2) the video is played, but do not change when the button is hit.
My code is the following:
fun onClick(view: View) {
// Change the word randomly
randOne = ThreadLocalRandom.current().nextInt(1, wordMap.size)
val display : TextView = findViewById(txtWord)
val randKey = randOne.toString()
display.text = wordMap[randKey]
val vdFile = "v$randKey"
// Create conditions to run the video files
val video : VideoView = findViewById(vdWord)
video.setVideoPath("android.resource://$packageName/R.raw.$vdFile")
video.start()
video.setOnCompletionListener { video.start() }
}
Thank you for your help.
var videoName = "youChoose"
val video: Uri = Uri.parse("android.resource://$packageName/raw/$videoName")
simpleVideoView!!.setVideoURI(video)

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);

How to show the custom PDF template while clicking the button

I want to show the PDF Template in new window while clicking the button in Sales Order. I created the button in sales order process using user event script. after that i'm unable to proceed it. It is possible to show the custom PDF template in new window while clicking the sales order?
My CODE:
USER EVENT SCRIPT:
// creating button in user event script before load event in view mode
unction userEventBeforeLoad(type, form, request){
if(type == 'view'){
var internalId = nlapiGetRecordId();
if (internalId != null) {
var createPdfUrl = nlapiResolveURL('SUITELET', 'customscript_back0rdered_itm_pdf', 'customdeploy_backord_itm_pdf_dep', false);
createPdfUrl += '&id=' + internalId;
//---add a button and call suitelet on click that button and it will open a new window
var addButton = form.addButton('custpage_printpdf', 'Print PDF', "window.open('" + createPdfUrl + "');");
}
else {
nlapiLogExecution('DEBUG', 'Error', 'Internaal id of the record is null');
}
}
}
SUITELET SCRIPT:
function suitelet(request, response){
var xml = "<?xml version=\"1.0\"?>\n<!DOCTYPE pdf PUBLIC \"-//big.faceless.org//report\" \"report-1.1.dtd\">\n";
xml += "<pdf>";
xml += "<head><macrolist><macro id=\"myfooter\"><p align=\"center\"><pagenumber /></p></macro></macrolist></head>";
xml += "<body size= \"A4\" footer=\"myfooter\" footer-height=\"0.5in\">";
var record = request.getParameter('internalId');
xml +="record"; //Add values(in string format) what you want to show in pdf
xml += "</body></pdf>";
var file = nlapiXMLToPDF(xml);
response.setContentType('PDF', 'Print.pdf ', 'inline');
response.write(file.getValue());
}
thanks in advance
The way I did it recently:
User Event Adds the Button that calls a suitelet (window.open('suitelet URL'))
Suitelet Renders the custom template
You can do the rendering like this insise a Suitelet (params: request, response), the custscript_pdf_template points to an html file on the cabinet using the NetSuite Advanced HTML syntax
var template = nlapiGetContext().getSetting('SCRIPT', 'custscript_pdf_template');
var purchaseOrder = nlapiLoadRecord('purchaseorder', tranId);
var xmlTemplate = nlapiLoadFile(template);
var renderer = nlapiCreateTemplateRenderer();
var file;
xmlTemplate = xmlTemplate.getValue();
renderer.setTemplate(xmlTemplate);
renderer.addRecord('record', purchaseOrder);
xmlTemplate = renderer.renderToString();
file = nlapiXMLToPDF(xmlTemplate);
resObj = file.getValue();
response.setContentType('PDF', 'printOut.pdf', 'inline');
response.write(resObj)

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,
});
}

How to move generated PDF to a specific folder in Google Drive

Here is the jist of what I want this script to do.
User submits a form using Google Forms
Form Records to Google Sheet
Sheet replaces text and generate Google Document from Template
Template is copied
PDF is created from this template
PDF is emailed
PDF is moved to a specific folder in Google Drive.
I have all of those things to work except the last step. Can someone help us out here? We are using this for a school, and nobody in our (IT) department knows anything about scripts. Through Googling and searching I have come this far. The last step is to get the PDF to move to a specific folder.
Here is the current code:
// MacArthur High School
// Generic PLC Agenda Script
// Created 18 Jul 2014
// Author: Josh Patrick
// Decatur Public Schools #61
// Document Creation - replace docTemplate links with each template link on the PLC Drive.
var docTemplate = "1DSFCE6mFZib0ZTVOgVqPbLYaRwjS-XNsnsZn5RZewsE";
var docName = "PLC Agenda";
// Form Functions (labeled identifiers for Form)
function onFormSubmit(e) {
var TimeStamp = e.values [0]
var MeetingDate = e.values [1];
var MeetingTime = e.values [2];
var MeetingLocation = e.values [3];
var PLCFocus = e.values [4];
var PlannedActions = e.values [5];
var ResourcesNeeded = e.values [6];
var AssignedEmail = "jwpatrick#dps61.org";
// Get document template, copy it as a new temp doc, and save the Doc’s id
var copyId = DocsList.getFileById(docTemplate)
.makeCopy(docName+' for '+ MeetingDate)
.getId();
// Open the temporary document
var copyDoc = DocumentApp.openById(copyId);
// Get the document’s body section
var copyBody = copyDoc.getActiveSection();
// Replacing Text with Form Information
copyBody.replaceText('keyMeetingDate', MeetingDate);
copyBody.replaceText('keyMeetingTime', MeetingTime);
copyBody.replaceText('keyMeetingLocation', MeetingLocation);
copyBody.replaceText('keyPLCFocus' , PLCFocus);
copyBody.replaceText('keyPlannedActions' , PlannedActions);
copyBody.replaceText('keyResourcesNeeded' ResourcesNeeded);
// Copy Document and Save
copyDoc.saveAndClose();
// Generate PDF
var pdf = DocsList.getFileById(copyId).getAs("application/pdf");
// Email
var subject = "ELA PLC Agenda for " + MeetingDate ;
var body = "Attached is the PDF copy of the ELA PLC Agenda for " + MeetingDate;
MailApp.sendEmail(AssignedEmail, subject, body, {htmlBody: body, attachments: pdf});
// Delete Temporary Document
DocsList.getFileById(copyId).setTrashed(true);
}
**** Instead of deleting the temporary document, I want to move it to a specific file in Google Drive. I have looked up the scripts help, but I don't think I have done it correctly. I can get it to copydoc but I cannot get it to move to the right folder.
Any assistance is much appreciated.
addToFolder may fit your need.
developers.google.com/apps-script/reference/docs-list/file#addToFolder(Folder)