Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Google Doc to PDF using Google Script Editior

I've been trying to convert a Google Docs file to a PDF file without having to use the download option. Below is the script I have used in the Script Editor but it doesn't 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.');
  }
}
like image 264
Robert Priest Avatar asked Feb 04 '15 03:02

Robert Priest


1 Answers

It is failing because the folder is not defined. If you replace it with DriveApp, the PDF will be created in the root folder and your function would 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.');
  }
}
like image 156
Amit Agarwal Avatar answered Sep 28 '22 08:09

Amit Agarwal