Extract Text from PDF files with Google Apps Script

Published in: Google Apps Script - PDF

You can use Google Apps Script to extract text from a PDF file and save the extracted text as a new document in Google Drive. The document will also retain the simple formatting of the PDF file.

The following script illustrates how to use the Google Drive API as an OCR engine and extract text from a PDF file on the Internet. The code can be modified to convert PDF files existing in Google Drive to an editable document.

function extractTextFromPDF() {

  // PDF File URL
  // You can also pull PDFs from Google Drive
  var url = "https://img.labnol.org/files/Most-Useful-Websites.pdf";

  var blob = UrlFetchApp.fetch(url).getBlob();
  var resource = {
    title: blob.getName(),
    mimeType: blob.getContentType()

  // Enable the Advanced Drive API Service
  var file = Drive.Files.insert(resource, blob, {ocr: true, ocrLanguage: "en"});

  // Extract Text from PDF file
  var doc = DocumentApp.openById(file.id);
  var text = doc.getBody().getText();

  return text;

Google Drive API can perform OCR on JPG, PNG, GIF and PDF files. You can also specify the ocrLanguage property to specify the language to use for OCR.

Combine this with the doGet method and you’ve made an HTTP Rest API that can perform OCR on any web document with a simple GET request. This can be modified to work with file upload forms as well.

📮  Subscribe to our Email Newsletter for Google tips and tutorials!
Published in: Google Apps Script - PDF

Looking for something? Find here!

Meet the Author

Web Geek, Google Developer Expert
Amit Agarwal

Amit Agarwal is a Google Developer Expert in Google Workspace and Google Apps Script. He holds an engineering degree in Computer Science (I.I.T.) and is the first professional blogger in India. He is the developer of Mail Merge for Gmail and Document Studio. Read more on Lifehacker and YourStory

Get in touch

Google Add-ons

Do more with your Gmail and GSuite account

We build bespoke solutions that use the capabilities and the features of Google Workspace for automating business processes and driving work productivity.

  1. Mail Merge with Attachments
    Send personalized email to your Google Contact with a Google Sheet and Gmail
  2. Save Emails and Attachments
    Download email messages and file attachments from Gmail to your Google Drive
  3. Google Forms Email Notifications
    Send email notifications to multiple people when a new Google Form is submitted
  4. Document Studio
    Create beautiful pixel perfect documents merging data from Google Sheets and Google Forms
  5. Creator Studio for Google Slides
    Turn your Google Slides presentations into animated GIFs and videos for uploading to YouTube