productiveGuser.com

Create a New PDF File in Google Drive

Posted By: Harish
create a pdf file in google drive folder

We have seen a way to create a text file with content in Google Drive folder using Apps Script. Now in this post, we will create a PDF file in a google drive folder using apps script.

Open Google Apps Script editor and create a new project.

Replace the default function (which already exists) with the below function and run it. Visit creating and executing a Google Apps Script post for more info.

function createPDFinGoogleDrive() {
  try {
    let folder;
    const folderName = "PDF Folder"; //<-- change folder name of your choice
    const pdfFolder = DriveApp.getFoldersByName(folderName);
    const isFolder = pdfFolder.hasNext();
    if (!isFolder) {
      folder = DriveApp.createFolder(folderName);
    } else {
      folder = pdfFolder.next();
    };
    let createdFile = folder.createFile(
      "New PDF File",
      "This is a text content (inside doublequotes) with which the PDF file will be created", //<-- add pdf text content here
      MimeType.PDF
    );
    const url = createdFile.getUrl()
    Logger.log(url)
  } catch (err) {
    Logger.log(err)
  }
}

Above function checks for a folder with that name and creates a folder if it's not present. A new PDF file with the given content will be added to that folder.

After executing the function in the editor, you will get a PDFt file url in the log. Use that to directly preview the file.

With this process, we can only create simple PDF files with simple text.

We can also use a google doc file to write content and later download it as a PDF file. But with the above script, we can directly create a PDF file without much work.

Share is Caring

Related Posts