Convert Google document to PDF using Google Script Change

I am trying to convert a Google Docs file to a PDF file without having to use the download option. Below is the script I used in the script editor, but it does not seem to work. I think the error is after the IF statement.

function convertPDF() { doc = DocumentApp.getActiveDocument(); docblob = DocumentApp.getActiveDocument().getAs('application/pdf'); var result = DocumentApp.getUi().alert( 'Save As PDF?', 'Save current document (Name:'+doc.getName()+') as PDF', DocumentApp.getUi().ButtonSet.YES_NO); if (result == DocumentApp.getUi().Button.YES) { docblob.setName(doc.getName()) folder.createFile(docblob); DocumentApp.getUi().alert('Your PDF has been converted to a PDF file.'); } else { DocumentApp.getUi().alert('Request has been cancelled.'); } } 
+5
source share
2 answers

It does not work because the folder is not defined. If you replace it with DriveApp, a PDF file will be created in the root folder, and your function will work. You can also show the full URL in the message box.

 function convertPDF() { doc = DocumentApp.getActiveDocument(); 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); ui.alert('Your PDF file is available at ' + file.getUrl()); } else { ui.alert('Request has been cancelled.'); } } 
+4
source

To save the PDF in the source directory:

 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.'); } } 

And add this generic function

 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); } 
+2
source

Source: https://habr.com/ru/post/1212586/


All Articles