DriveApp conversion from DocX to PDF fails - google-apps-script

I'm trying to convert an existing .DOCX file on my Google Drive.
It works up until the new (PDF) file should be created, then I get this error message:
"Conversion from application/vnd.openxmlformats-officedocument.wordprocessingml.document to application/pdf failed".
The relevant DOCX file should not be corrupted as it can be opened by Google Document and manually convertred to PDF from there.
I have enabled Drive API (both in Drive and in API Console)
Anyone else seen this problem?
Code:
function convertPDF(fileid) {
var docId = fileid;
var f=DriveApp.getFileById(docId);
var n=f.getName();
var docFolder = f.getParents().next().getId();
var docblob = f.getAs('application/pdf');
n=n.replace(".docx",".pdf");
docblob.setName(n);
var bn=docblob.getName();
var t=docblob.getContentType();
Logger.log(bn+"-->"+t); // <-- works
var file = DriveApp.createFile(docblob); // <<- error msg here
var fileId = file.getId();
moveFileId(fileId, docFolder);
return (fileId);
}

At Google, it cannot be directly converted from docx to pdf. But, after it converted docx to Google document, it can convert to pdf. In order to convert docx to Google document, you can use Drive API using Advanced Google services. For this, please enabling Drive API of Advanced Google services as follows.
In the script editor, select Resources > Advanced Google services
In the dialog that appears, click the on/off switch for Drive API v2.
Click OK button.
The detail information of Advanced Google services is here.
I think that enabling Drive API at API console has already been done, because you have already used DriveApp on your script. Google automatically enables Drive API on API console when DriveApp is used in the script.
The modified script using Drive API is as follows.
Modified script :
function convertPDF(docx_id) {
var docx = DriveApp.getFileById(docx_id);
var docFolder = docx.getParents().next().getId();
var n = docx.getName();
var res = Drive.Files.insert({ // Here, Drive API of Advanced Google services is used.
"mimeType": "application/vnd.google-apps.document",
"title": n
}, docx.getBlob());
var f = DriveApp.getFileById(res.id).getBlob();
var docblob = f.getAs('application/pdf');
n=n.replace(".docx",".pdf");
docblob.setName(n);
var bn=docblob.getName();
var t=docblob.getContentType();
Logger.log(bn+"-->"+t);
var file = DriveApp.createFile(docblob);
var fileId = file.getId();
Logger.log(fileId)
moveFileId(fileId, docFolder);
return (fileId);
}
I don't know about moveFileId(). So if an error occurs at this line, please check the function.
Note :
In this case, Google document is created as a temporally file for converting to PDF. The filename is the same to the docx file. So if it is not required for you, please delete it.

Related

Google Apps Script to save Gmail attachments to Google Drive of only specific file types

I am trying to use Google Apps Script to automate downloading attachments from a Gmail inbox to a specific folder on the account's Google Drive using label. I found the code below that does that part well, but I need to modify it to save only specific file type. So please help me how to save only specific file type i.e .xlsx.
// copying-gmail-attachments-to-google-drive-using-apps-script
function saveAttachmentInFolder(){
var folder = DriveApp.getFolderById('1cqkjQWj2QkT7TyvllHI7YJFfWNcEupW0');// your Google Drive Folder ID to save the files
var userId = "acoounts.mfc66#gmail.com";// your email.I mean your own Gmail to
var query = "label:Thrive_from april 2022 till 20th jan 2023";// the label you created to fetch attachments from
var res = Gmail.Users.Messages.list(userId, {q: query});//The searching and using the results; never mind
res.messages.forEach(function(m){
var attA=GmailApp.getMessageById(m.id).getAttachments();
attA.forEach(function(a){
folder.createFile(a.copyBlob()).setName(a.getName()); // gets name of file
});
});
}
// end of script
Thanks in advance for your help.
In your situation, how about checking the mimeType of the data as follows?
From:
var attA=GmailApp.getMessageById(m.id).getAttachments();
To:
var attA = GmailApp.getMessageById(m.id).getAttachments().filter(a => a.getContentType() == MimeType.MICROSOFT_EXCEL);
or, if you want to check both mimeType and the extension of the filename, how about the following modification?
var attA = GmailApp.getMessageById(m.id).getAttachments().filter(a => a.getContentType() == MimeType.MICROSOFT_EXCEL || (/\.pdf$/i).test(a.getName());
When this modified script is used, the attachment files are filtered by the mimeType of XLSX format.
References:
filter()
Enum MimeType
getContentType()

Find and Replace function multiple documents in Shared Drives

The issue : I have multiple documents ( specifically, Google Sheets ) in multiple Shared Drives that need the same single word replaced. Some searching around this forum found me the following code, but it doesn't seem to be working. I'm not getting any error messages, but when I go check the files nothing has been changed. I checked and made sure I put in my search string and replacement string correctly.
Do I need to do something different to get it to check files in Shared Drives? I tried turning on the Drive API in Advanced Google Services, but that just gave me an error in line 6 (
var doc = DocumentApp.openById(file.getId()); )
Here's the code I was using :
function myFunction() {
var files = DriveApp.getFiles(); // Note: this gets *every* file in your Google Drive
while (files.hasNext()) {
var file = files.next();
Logger.log(file.getName());
var doc = DocumentApp.openById(file.getId());
doc.replaceText("My search string or regex", "My replacement string");
}
Logger.log("Done")
}
DriveApp.getFiles() returns only the files on "My Drive". In order to be able to get the files in a Shared Drive (formerly Team Drive) you have to enable the Drive Advanced Service and, instead of
var files = DriveApp.getFiles();
use something like
var files = Drive.Files.list(options);
Related
Finding shared date of a file in GAS
Google Apps Script TeamDrive DriveApp.searchFolders and DriveApp.searchFiles does not return any results
"Shared Drive" support in Google Apps Script
In order to access the shared drives, you need to activate the Drive API in the Advanced Google Services, but in order to access it, you will have to use Drive and not DriveApp.
If you want to retrieve the shared drives specifically and look for files with a certain name, you can try this:
Code
// Copyright 2020 Google LLC.
// SPDX-License-Identifier: Apache-2.0
function retrieveFiles() {
var allDrives = Drive.Drives.list().items;
let fileName = 'FILE_NAME';
for (let i = 0; i < allDrives.length; i++) {
var driveId = allDrives[i].id;
console.log(id)
var optionalArgs = {
'driveId': driveId,
'includeItemsFromAllDrives': true,
'corpora': 'drive',
'supportsAllDrives': true,
'q': "title=" + "'" + fileName + "'"
};
var filesReturned = Drive.Files.list(optionalArgs).items;
for (let j = 0; j < filesReturned.length; j++) {
var fileId = filesReturned[j].id;
var sheet = SpreadsheetApp.openById(fileId);
//sheet manipulation
}
}
}
Explanation
The above code retrieves all the shared drives by making use of the Drives:list method and then for each shared drive, searches for all the files which are named FILE_NAME using Files:list. Then, it accesses each file by using SpreadsheetApp.
Note
Please bear in mind that the code can be customized in order to fit your needs and requirements specifically.
Reference
Drive API Drives:list;
Drive API Files:list;
Advanced Google Services Apps Script;
SpreadsheetApp Class Apps Script.

How to get a link of the thumbnail of a google drive file using google apps script?

How to get a link of the thumbnail of a google drive file using google apps script?
The getThumbnail() function gives a blob. But I can't create an image with it
function createThumbnail(blob){
if(blob != null){
var thumbnailFile = thumbnailFolder.createFile(blob);
return thumbnailFile.getDownloadUrl();
}
}
var thumbImg = createThumbnail(file.getThumbnail());
function getThumbnailLink(fileId) {
var file = Drive.Files.get(fileId);
return file.thumbnailLink; // this is the value we need to fetch
}
function run() {
var fileId = "XXX__Replace here the file's id__XXX";
var urlth = getThumbnailLink(fileId);
Logger.log('url-> ' + urlth);
};
To obtain the thumbnail for a file, you must give the file's id and don't forget "Activate the Advanced Google Services" => In the Editor go to Resources > Advanced Google Services > and check the ON flag for Drive API.
The blob data is the image - if you download it as the filetype you can open it. You can get a link to the thumbnail with file.thumbnailLink, but note that these links only last for a few hours as they're made when requested by your application.

Add convert xls to Google sheets feature to function of download

I have working code for download any file in google docs by link. Most of files in xlx or xlsx format and need to be convert in google sheets type. Ive been tried to use some methods, that I find in Internet, but they dont work for me. In code below, I comment with code wich I test. And I guess, that google had changed some documentation
function downloadFile(fileURL,folder) {
var fileName = "";
var fileSize = 0;
var fileId = "";
var response = UrlFetchApp.fetch(fileURL, {muteHttpExceptions: true});
var rc = response.getResponseCode();
if (rc == 200) {
var fileBlob = response.getBlob() //.getAs(MimeType.GOOGLE_SHEETS) - get error
var folder = DriveApp.getFolderById(folder);
if (folder != null) {
var file = folder.createFile(fileBlob);//.getAs(MimeType.GOOGLE_SHEETS) - get error
fileName = file.getName();
fileSize = file.getSize();
fileId = file.getId();
}
}
//file.setMimeType("application/vnd.google-apps.spreadsheet") - not work
//makeCopy('ssssss', folder, {convert: true}) - get error
var fileInfo = [ rc, fileName, fileSize, fileId ];
return fileInfo;
}
I call function like this:
downloadFile("http://www.beltools.ru/prais_rar/price%20TD%20RI.xls","0B_E2P3ZhQySBY3BBMzdlazBLcTA")
In order to convert Excel to Spreadsheet, DriveApp cannot do it. So Drive API has to be used. You can use Drive API v2 from Advanced Google services. "Drive API v2" can be used at Google Apps Script by enabling Drive API of Advanced Google services and of Google API Console.
How to use it is as follows.
In the script editor, select Resources > Advanced Google services
In the dialog that appears, click the on/off switch for Drive API v2.
At the bottom of the dialog, click the link for the Google API Console.
In the console, click into the filter box and type part of the name of the API "Drive API", then click the name once you see it.
On the next screen, click Enable API.
Close the Developers Console and return to the script editor. Click OK in the dialog. The advanced service you enabled is now available in autocomplete.
The detail information is https://developers.google.com/apps-script/guides/services/advanced.
At the sample script, at first, a file is downloaded by fileURL, which is Excel file, as blob. The blob data is uploaded to Google Drive using Drive API. In this case, access token is not required. For downloadFile(), the Input data and output data are same to your downloadFile(). File name is retrieved from fileURL.
Script :
function downloadFile(fileURL, folder) {
var filename = fileURL.match(".+/(.+?)([\?#;].*)?$")[1];
var response = UrlFetchApp.fetch(fileURL);
var rc = response.getResponseCode();
var blob = response.getBlob();
var resource = {
"mimeType": "application/vnd.google-apps.spreadsheet",
"parents": [{id: folder}],
"title": filename
};
var res = Drive.Files.insert(resource, blob);
var fileInfo = [rc, res.title, blob.getBytes().length, res.id];
return fileInfo;
}
Result :
[
200,
sample.xlsx,
10000.0,
## file id ##
]
If I misunderstand your question, I'm sorry.

Convert PDF to Doc with Google Script Editor

I'm looking to convert PDF to google Doc in Drive using Google Script Editor. However keep getting error message "Converting from application/pdf to application/doc is not supported". Is this conversion possible in script? My attempt as below, would be great to hear any advice.
function convertdPDF2doc() {
var pdffile = DriveApp.getFileById();
var pdfblob = pdffile.getAs('application/doc');
pdfblob.setName(doc.getName() + ".doc");
DriveApp.createFile(docblob);
}
function pdfToDoc() {
var fileBlob = DriveApp.getFileById('0B3m2D6239t6aWHo5TVpyYzhxV1U').getBlob();
var resource = {
title: fileBlob.getName(),
mimeType: fileBlob.getContentType()
};
var options = {
ocr: true
};
var docFile = Drive.Files.insert(resource, fileBlob, options);
Logger.log(docFile.alternateLink);
}
Add Drive API to google apps script project
https://developers.google.com/apps-script/guides/services/advanced#enabling_advanced_services
You can see you pdf file id on google drive when you download it http://i.imgur.com/3pYvwjx.png