Read the text of a PDF or photo (OCR)
Apps Script recipes › Drive files
Turns a PDF or picture into text with Google's OCR through the Advanced Drive service (v2 or v3), then removes the temporary Doc.
File Code.gs
const OCR_LANGUAGE = 'id';
const OCR_TYPES = ['application/pdf', 'image/jpeg', 'image/png', 'image/gif', 'image/bmp', 'image/webp'];
/** A PDF or picture Blob → its text. The temporary Google Doc is moved to the trash afterwards. */
function ocrText_(blob, language) {
const type = String(blob.getContentType() || '').toLowerCase();
if (OCR_TYPES.indexOf(type) < 0) throw new Error('OCR reads PDFs and pictures only, not ' + (type || 'this file'));
const name = 'OCR ' + (blob.getName() || 'file') + ' ' + Date.now();
const lang = language || OCR_LANGUAGE;
let id;
if (typeof Drive.Files.create === 'function') {
// Drive API v3: the NEW file's type (Google Docs) asks Google to convert; the upload stays a PDF/picture.
id = Drive.Files.create({ name: name, mimeType: MimeType.GOOGLE_DOCS }, blob, { ocrLanguage: lang, fields: 'id' }).id;
} else {
// Drive API v2: no Google Docs type anywhere, ocr: true does the conversion.
id = Drive.Files.insert({ title: name }, blob, { ocr: true, ocrLanguage: lang }).id;
}
try {
return DocumentApp.openById(id).getBody().getText();
} finally {
DriveApp.getFileById(id).setTrashed(true);
}
}
/** Called from a page: { name, type, data: base64 without the "data:…;base64," prefix } → the text. */
function pdfTextFromPage(file) {
if (!file || !file.data) throw new Error('No file was sent.');
const blob = Utilities.newBlob(Utilities.base64Decode(file.data), file.type || 'application/pdf', file.name || 'file.pdf');
return ocrText_(blob);
}
/** A PDF already in Drive (by its ID) → the text. */
function pdfTextFromDrive_(fileId) {
return ocrText_(DriveApp.getFileById(fileId).getBlob());
}
File js/pdf-upload.html
<script>
// <input type="file" accept="application/pdf,image/*"> → the text, through pdfTextFromPage on the server.
function readPdfText(input) {
const file = input.files[0];
if (!file) return Promise.reject(new Error('Choose a PDF first.'));
if (file.size > 20 * 1024 * 1024) return Promise.reject(new Error('The file is larger than 20 MB.'));
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onerror = () => reject(reader.error);
reader.onload = () => {
const data = String(reader.result).split(',')[1];
google.script.run
.withSuccessHandler(resolve)
.withFailureHandler(reject)
.pdfTextFromPage({ name: file.name, type: file.type || 'application/pdf', data });
};
reader.readAsDataURL(file);
});
}
</script>
Good to know
- Needs the Advanced Drive service (appsscript.json › dependencies.enabledAdvancedServices: { "userSymbol": "Drive", "serviceId": "drive", "version": "v3" }). New projects use v3; v2 also works with this recipe.
- The file sent to Google must stay a PDF or a picture (application/pdf, image/jpeg, image/png…). Never set its type to Google Docs: that gives "OCR is not supported for files of type application/vnd.google-apps.document".
- v3 asks for OCR by giving the new file mimeType Google Docs in the metadata; v2 asks with { ocr: true }. Don't mix them (v2 insert with a Google Docs type is the usual mistake).
- From a web page, send the file as base64 (FileReader.readAsDataURL) to pdfTextFromPage, not as a Blob: google.script.run can't pass a Blob from a page.
Let the AI put it in your appGAS AI Builder knows every recipe here. Describe your app and it uses this code where it fits, in a Google Apps Script project in your own Drive.
Use it in a project