我是Google脚本的新手,我想在容器绑定的Google文档中创建一个脚本,该文档通过选项菜单转换为PDF格式的Google文档。问题是,如果我修改文档,它将创建在我的文件夹中具有相同名称的同一文件,所以如果文件存在,我想覆盖它(更新更新),如你所见,我试图通过不同的版本调用,我被阻止了很长一段时间考虑^^。 如果你有同样的想法,我会很开心!非常感谢你。 :)
function moveFile(sourceFileId, targetFolderId) {
var file = DriveApp.getFileById(sourceFileId);
file.getParents().next().removeFile(file);
DriveApp.getFolderById(targetFolderId).addFile(file);
}
//Fonction standard ----->>>>> function to create or overwrite a file: si ça depasse 10 MB on genère une exception
// Creates or replaces an existing file
function updateFile (folder, filename, data) {
try {
// filename is unique, so we can get first element of iterator
var file = folder.getFilesByName(filename).next()
file.setContent(data)
} catch(e) {
folder.createFile(filename, data)
}
}
function convert_to_pdf() {
// Get the document to which this script is bound.
var doc = DocumentApp.getActiveDocument();
var templateFile = DriveApp.getFileById(doc.getId());
var theBlob = templateFile.getBlob().getAs('application/pdf');
var newPDFFile = DriveApp.createFile(theBlob);
var fileName = templateFile.getName().replace(".", ""); //otherwise filename will be shortened after full stop
var name = newPDFFile.setName(fileName + ".pdf");
file = DriveApp.getFileById(doc.getId());
var parentFold = file.getParents();
var folder = parentFold.next();
var theId = folder.getId();
var targetFolder = DriveApp.getFolderById(theId);
Logger.log('targetFolder name: ' + targetFolder.getName());
if( checkFile_in_a_Folder(name,folder) != 1){
//on ajoute le fichier dans le repertoire courant targetFolder
moveFile(newPDFFile.getId(), theId) ;
Logger.log('Move File');
}
else{
// updateFile (folder, newPDFFile, newPDFFile.getAs(MimeType.PDF));// get string content getAs(MimeType.PDF)
Logger.log(' Update File ');
// updateFile (folder, newPDFFile, newPDFFile.getBlob().getAs('application/pdf'));// get string content getAs(MimeType.PDF)
Drive.Files.update({ title: newPDFFile.getName(), mimeType: newPDFFile.getMimeType()}, newPDFFile.getId(), theBlob);
}
//à la fin on ne va plus l'avoir dans RootFolder
var rootFolder = DriveApp.getRootFolder();
rootFolder.removeFile(newPDFFile);
/**============ Ancien appel de fonction ====================**/
// createPDFfile(doc.getId() , theId);
}
function checkFile_in_a_Folder(filename,foldername){
var results = 0; //on suppose qu'on ne le trouve pas
var folder = DriveApp.getFoldersByName(foldername);
Logger.log(folder.hasNext());
//Folder does not exist
if(!folder.hasNext()){
results = 0;
Logger.log("No Folder Found");
}
//Folder does exist
else{
Logger.log("Folder Found")
var file = folder.next().getFilesByName(filename);
if(!file.hasNext()){
Logger.log("No File Found");
results = 0;
}
else{
Logger.log("File Found");
results = 1;
}
}
return results;
}