Skip to content

Instantly share code, notes, and snippets.

@pkorpine
Last active November 17, 2023 20:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pkorpine/c7efed52086147916c951ce2211465e5 to your computer and use it in GitHub Desktop.
Save pkorpine/c7efed52086147916c951ce2211465e5 to your computer and use it in GitHub Desktop.
"Save as PDF" script for Google Docs
// Saves the current document in Google Docs as PDF to the same folder.
// Code from https://stackoverflow.com/questions/28312992/convert-google-doc-to-pdf-using-google-script-editior
// Just added onOpen() to add the script to the menubar.
function onOpen() {
var ui = DocumentApp.getUi();
// Or DocumentApp or FormApp.
ui.createMenu('My scripts')
.addItem('Convert to PDF', 'convertPDF')
.addToUi();
}
function convertPDF() {
doc = DocumentApp.getActiveDocument();
// ADDED
var docId = doc.getId();
var docFolder = DriveApp.getFileById(docId).getParents().next().getId();
// ADDED
var ui = DocumentApp.getUi();
var result = ui.alert(
'Save As PDF?',
'Save current document (Name:'+doc.getName()+'.pdf) as PDF',
ui.ButtonSet.YES_NO);
if (result == ui.Button.YES) {
docblob = DocumentApp.getActiveDocument().getAs('application/pdf');
/* Add the PDF extension */
docblob.setName(doc.getName() + ".pdf");
var file = DriveApp.createFile(docblob);
// ADDED
var fileId = file.getId();
moveFileId(fileId, docFolder);
// ADDED
ui.alert('Your PDF file is available at ' + file.getUrl());
} else {
ui.alert('Request has been cancelled.');
}
}
function moveFileId(fileId, toFolderId) {
var file = DriveApp.getFileById(fileId);
var source_folder = DriveApp.getFileById(fileId).getParents().next();
var folder = DriveApp.getFolderById(toFolderId)
folder.addFile(file);
source_folder.removeFile(file);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment