Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google Apps Scripts - How to replace a file?

I'm trying to replace a PDF file in a Google Drive Folder using a script. Since GAS does not provide a method for adding revisions (versions), I'm trying to replace the content of the file, but all I get is a blank PDF.

I can't use the DriveApp.File class since our Admin has disabled the new API, so I have to use DocsList.File instead.

  • Input:
    • OldFile.pdf (8 pages)
    • NewFile.pdf (20 pages)
  • Output expected:
    • OldFile.pdf with the same content as NewFile.pdf
  • Real Output:
    • OldFile.pdf with 20 empty pages.

Process:

var old = DocsList.getFileById("####");
var new = DocsList.getFileById("####");
old.replace(new.getContentAsString());

Any ideas, please? Thanks a lot in advance.

PS.: I also tried calling old.clear() first, but I'd say the problem lies on the getContentAsString method.

like image 989
Carlos Medina Gallego Avatar asked Feb 15 '23 17:02

Carlos Medina Gallego


2 Answers

The Advanced Drive Service can be used to replace the content of an existing PDF file in Google Drive. This answer also includes an example of how to update a PDF file in a shared Drive.

function overwriteFile(blobOfNewContent,currentFileID) {
  var currentFile;
  
  currentFile = DriveApp.getFileById(currentFileID);    
  
  if (currentFile) {//If there is a truthy value for the current file
    Drive.Files.update({
      title: currentFile.getName(), mimeType: currentFile.getMimeType()
    }, currentFile.getId(), blobOfNewContent);
  }
}

References

  • https://developers.google.com/apps-script/advanced/drive
  • https://developers.google.com/drive/api/v3/reference/files/update

An example of using with a shared Drive:

Drive.Files.update({ title: currentFile.getName(), mimeType: 
  currentFile.getMimeType() }, currentFile.getId(), blobOfNewContent, 
  {supportsTeamDrives: true});
like image 118
Alan Wells Avatar answered Feb 18 '23 21:02

Alan Wells


Try to get it as a blob datatype instead.

like image 41
Zig Mandel Avatar answered Feb 18 '23 23:02

Zig Mandel