How to export Google Docs to PDF using Apps Script and Drive API?

Hey everyone! I’m stuck trying to turn a Google Docs file into a PDF using Apps Script and the Drive API. I’ve got the basic steps down:

  1. Grab the Docs file
  2. Turn it into a PDF
  3. Put it on Drive

I’m using the ‘export’ function to get the Doc and make it a PDF, then the ‘create’ function to upload it. But something’s not right. The PDF ends up empty or messed up.

Here’s a quick code snippet of what I’m doing:

function convertToPDF() {
  const docId = 'your-doc-id-here';
  const folderId = 'your-folder-id-here';
  
  const pdfBlob = DriveApp.getFileById(docId).getAs('application/pdf');
  
  DriveApp.getFolderById(folderId).createFile(pdfBlob);
}

I think the first part works fine, but the upload is causing issues. Maybe it’s an encoding problem?

Can anyone spot what I’m doing wrong? I’d really appreciate some help!

hey sophiac, ur on the right track! i ran into similar issues. try using the advanced Drive service instead. it gives more control over the export process. heres a quick example:

Drive.Files.export(docId, 'application/pdf', {});

this should give u a better pdf output. good luck!

I’ve encountered this issue before. The problem likely lies in how the PDF blob is being handled. Instead of using DriveApp, try utilizing the advanced Drive service for more reliable results. Here’s a modified version of your code that should work:

function convertToPDF() {
  const docId = 'your-doc-id-here';
  const folderId = 'your-folder-id-here';
  
  const pdf = Drive.Files.export(docId, 'application/pdf');
  const file = {
    title: 'Exported PDF',
    parents: [{ id: folderId }]
  };
  
  Drive.Files.insert(file, pdf);
}

This approach ensures proper handling of the PDF data and should resolve your empty or corrupted file issues. Remember to enable the Drive advanced service in your script project settings before running this code.

I’ve been down this road before, and I feel your frustration. One thing that really helped me was using the advanced Drive service, as others have mentioned. But here’s a little trick I discovered:

Instead of exporting directly to PDF, I found it more reliable to first export to HTML, then convert that to PDF. It gives you more control over the formatting. Here’s a snippet that worked wonders for me:

function convertToPDF() {
  const docId = 'your-doc-id-here';
  const folderId = 'your-folder-id-here';
  
  const html = Drive.Files.export(docId, 'text/html');
  const htmlBlob = Utilities.newBlob(html, 'text/html', 'temp.html');
  const pdf = htmlBlob.getAs('application/pdf');
  
  DriveApp.getFolderById(folderId).createFile(pdf);
}

This approach solved most of my formatting issues. Just remember to enable the Drive advanced service in your script settings. Hope this helps!