Docx to Google Doc using Google Script - google-apps

I have a lot of docx files ( ~ 72 ) , their MIMETYPE is :
application/vnd.openxmlformats-officedocument.wordprocessingml.document
and I want to convert all of them to GoogleDocument so I can edit them online to do so I need them to be
application/vnd.google-apps.document
Is this possible ? I've tried with blob but nothing works , there is a way to create a new google doc with the same format ?

Got it .
var docx = DriveApp.getFileById("###");
var newDoc = Drive.newFile();
var blob =docx.getBlob();
var file=Drive.Files.insert(newDoc,blob,{convert:true});
The {convert:true} convert it .
Ps : you need to set document name since it's not included in teh blob
DocumentApp.openById(file.id).setName(docx.getName());

Related

How to attach a google doc file as Microsoft Word doc

My first time here in Stack overflow. I'm just an amateur programmer trying to learn Google Apps script. I created a google form to get answers from users. I have transferred the answers to a google doc formatted according to our use in the office. I need to email the google doc back to the for user in microsoft word format. Sending as pdf is not a problem, but msword is a bit tricky.
I tried copying the recommendations i found here but I can't seem to get it to run. I hope someone can tell me what i'm doing wrong and what i need to doe. here's the relevant portion of the code:
`doc.saveAndClose(); // end of the transfer from google sheet to google doc. now to email...
var filename= ts+"-"+c_name1;
var compfile = DriveApp.getFilesByName(filename);
if (!compfile.hasNext())
{
console.error("Could not open file "+filename);
return;
}
var template = HtmlService.createTemplateFromFile('email_message');
var message = template.evaluate().getContent();
MailApp.sendEmail({
to:em,
subject: "Automated Complaint Assistant",
htmlBody: message,
attachments: compfile.next()}) // attachment is pdf file type. HOW TO SEND AS WORD?
`
I tried this function i found here:
`function EmailCompAsWordDoc(email, name, newCopyID) {
var subject = "Word version of Complaint";
var body = "\n\nHere is the Microsoft Word version of the draft Complaint";
var url = 'https://docs.google.com/feeds/download/documents/export/Export?id=' + newCopyID + '&exportFormat=docx';
var options = {
headers: {
Authorization: "Bearer " + ScriptApp.getOAuthToken()
},
muteHttpExceptions: true
}
var response = UrlFetchApp.fetch(url, options);
var doc = response.getBlob();
//Create the docx file in my TEMP folder in Google Drive and send
var file = DriveApp.createFile(doc).setName('Draft Complaint '+ name + '.docx');
DriveApp.getFolderById('<ID of my TEMP folder in Google Drive>').addFile(file);
var blob = DriveApp.getFileById(file.getId());
if (MailApp.getRemainingDailyQuota() > 0)
GmailApp.sendEmail(email, subject, body, {
Body: body,
attachments:[blob]
});
//Remove the docx file from the TEMP folder
DriveApp.getFileById(file.getId()).setTrashed(true);
}
var compid = DriveApp.getFileById(filename.getId()) // error here. How to get the file ID for use by this custom function??
EmailCompAsWordDoc(em, c_name1, compid)
`
From your provided script, I understood that the value of filename is the string value of var filename = ts + "-" + c_name1;. I thought that this is the reason for your current issue of filename.getId is not a function.
In this case, how about the following modification?
From:
var compid = DriveApp.getFileById(filename.getId())
To:
var compid = DriveApp.getFilesByName(filename).next().getId();
In this case, it supposes that the values of filename and em and c_name1 of EmailCompAsWordDoc(em, c_name1, compid) are valid values. Please be careful about this.

Name email attachment in Google Apps Script

I have the following G.A.S script to email a google sheet as a pdf attachment.
var spreadsheet = SpreadsheetApp.getActive();
var subject = spreadsheet.getRange("U1:U1").getValues();
var emailTo = spreadsheet.getRange("V1:V1").getValues();
var message = spreadsheet.getRange("W1:W1").getValues();
var pdf = DriveApp.getFileById(spreadsheet.getId()).getAs('application/pdf').getBytes();
var attach = {fileName:subject,content:pdf, mimeType:'application/pdf'};
MailApp.sendEmail(emailTo, subject, message, {attachments:[attach]});
The above code works well except that the file attached to the email message has a bizarre name like "[Ljava.lang.Object_#4e63998c" with no ".pdf" extension!
I am looking for a way to set a name for the pdf file before being attached to the email. The file name should equal the "subject" variable.
Thanks in advance.
Omid
Values retrieved by getValues() is 2 dimensional array. I think that the filename becomes such string because the array is used as the filename. Please retrieve the element from the array and try again. So could you please modify as follows?
From :
var attach = {fileName:subject,content:pdf, mimeType:'application/pdf'};
To :
var attach = {fileName:subject[0][0],content:pdf, mimeType:'application/pdf'};
You can also use the following modification. In this case, getValue() can retrieve the value as a string from the cell "U1".
From :
var subject = spreadsheet.getRange("U1:U1").getValues();
To :
var subject = spreadsheet.getRange("U1:U1").getValue();
Reference :
getValue()
getValues()
If this was not what you want, please tell me. I would like to think of other solutions.
I'm a bit late, but another way to solve this problem might be:
var spreadsheet = SpreadsheetApp.getActive();
var subject = spreadsheet.getRange("U1:U1").getValues();
var emailTo = spreadsheet.getRange("V1:V1").getValues();
var message = spreadsheet.getRange("W1:W1").getValues();
var pdf = DriveApp.getFileById(spreadsheet.getId())
.getAs('application/pdf')
.getBlob()
.setName(subject);
MailApp.sendEmail(emailTo, subject, message, {attachments:[pdf]});
The Blob class has a setName method https://developers.google.com/apps-script/reference/base/blob#setName(String), that can be chained into a Blob object (which is the result of getBlob())
After that you just need to add the Blob object inside attachments array of function MailApp.sendEmail

How to create virtual XML for ZUGFeRD Invoices

I try to create a PDF/A-3b file which contains an embedded XML-File to be ZUGFeRD conform. I use Perl and PDFLib for this purpose. The PDFLib Documentation out there is just for Java and PHP. Creating the PDF works fine, but the XML part is my problem.
So how can i create a pvf from xml and join this to my pdf?
This is what PDFLib recommends in Java:
// Place XML stream in a virtual PVF file
String pvf_name = "/pvf/ZUGFeRD-invoice.xml";
byte[] xml_bytes = xml_string.getBytes("UTF-8");
p.create_pvf(pvf_name, xml_bytes, "");
// Create file attachment (asset) from PVF file
int xml_asset = p.load_asset("Attachment", pvf_name,
"mimetype=text/xml description={ZUGFeRD invoice in XML format} "
+ "relationship=Alternative documentattachment=true");
// Associate file attachment with the document
p.end_document("associatedfiles={" + xml_asset + "}");
So I thought, take the example and fit it to perl:
my $xmldata = read_file($xmlfile, binmode => ':utf8'); #I use example xml at the moment
my $pvf_xml = "/pvf/ZUGFeRD-invoice.xml";
PDF_create_pvf($pdf, $pvf_xml, $xmldata, ""); #because no OOP i need to call it this way (works with all other PDF Functions)
my $xml_invoice = PDF_load_asset("Attachment", $pvf_xml, "mimetype=text/xml "
."description={Rechnungsdaten im Zugferd-Xml-Format} "
."relationship=Alternative documentattachment=true");
PDF_end_document($pdf, "associatedfiles={".$xml_invoice."}");
In PHP examples it's also not needed to convert to ByteArray after reading xml. Further tried it with unpack but don't seem to be the problem.
If I call my script I'm just getting:
Usage: load_asset(type, filename, optlist); at signatur_test.pl line
41.
I think the problem is that pvf_xml isn't created the line before.
Anyone did this before and no how to solve this?
Arg, i was just missing the PDF-Handle in the load_asset method:
my $xml_invoice = PDF_load_asset($pdf, "Attachment", $pvf_xml, "mimetype=text/xml "
."description={Rechnungsdaten im Zugferd-Xml-Format} "
."relationship=Alternative documentattachment=true");
This way it works.

OpenXml ChangeDocumentType

I need to convert a powerpoint template from potx to pptx. As seen here: http://www.codeproject.com/Tips/366463/Create-PowerPoint-presentation-using-PowerPoint-te I have tried with the following code. However the resulting pptx document is invalid and can't be opened by Office Powerpoint. If I skip the line newDoc.ChangeDocumentType then the resulting document is valid, but not converted to pptx.
templateContentBytes is a byte array containing the content of the potx document.
And temppath points to its local version.
using (var stream = new MemoryStream())
{
stream.Write(templateContentBytes, 0, templateContentBytes.Length);
using (var newdoc = PresentationDocument.Open(stream, true))
{
newdoc.ChangeDocumentType(PresentationDocumentType.Presentation);
PresentationPart presentationPart = newdoc.PresentationPart;
presentationPart.PresentationPropertiesPart.AddExternalRelationship(
"http://schemas.openxmlformats.org/officeDocument/2006/" + "relationships/attachedTemplate",
new Uri(tempPath, UriKind.Absolute));
presentationPart.Presentation.Save();
File.WriteAllBytes(tempPathResult, stream.ToArray());
I had the same problem, just move
File.WriteAllBytes(tempPathResult, stream.ToArray());
outside of the using

AmplifyJS , remove a stored object

I started using amplifijs and I successfully stored and retrieved my objects in the storage, but I don't know ho to remove them by name.
I used this syntax:
amplify.store("name",{valName1:"val1", ...});
var storage = amplify.store("name");
var val1 = storage.valName1;
How can I remove them by name like?
amplify.remove("name");
I found the answer :
amplify.store("name",null);