Edit: Updated for DriveApp, as DocsList deprecated.
我建议将其分解为两个问题。第一个是如何从电子邮件中获取 pdf 附件,第二个是如何将 pdf 转换为文本。
正如你所发现的,getContentAsString()
不会神奇地将 pdf 附件更改为纯文本或 html。我们需要做一些更复杂的事情。
首先,我们将获取附件Blob https://developers.google.com/apps-script/reference/base/blob,多个服务用来交换数据的实用程序类。
var blob = attachments[0].getAs(MimeType.PDF);
因此,第二个问题被分离出来,并保持我们只对标记为每个线程的第一条消息的第一个附件感兴趣的假设templabel
,这是如何myFunction()
looks:
/**
* Get messages labeled 'templabel', and send myself the text contents of
* pdf attachments in new emails.
*/
function myFunction() {
var threads = GmailApp.search('label:templabel');
var threadsMessages = GmailApp.getMessagesForThreads(threads);
for (var thread = 0; thread < threadsMessages.length; ++thread) {
var message = threadsMessages[thread][0];
var messageBody = message.getBody();
var messageSubject = message.getSubject();
var attachments = message.getAttachments();
var blob = attachments[0].getAs(MimeType.PDF);
var filetext = pdfToText( blob, {keepTextfile: false} );
GmailApp.sendEmail(Session.getActiveUser().getEmail(), messageSubject, filetext);
}
}
我们依赖一个辅助函数,pdfToText()
,转换我们的pdfblob
转换为文本,然后我们将其作为纯文本电子邮件发送给自己。这个辅助函数有多种选项;通过设置keepTextfile: false
,我们选择只将 PDF 文件的文本内容返回给我们,并且在我们的云端硬盘中不留下任何残留文件。
pdfToText()
该实用程序可用作为要点 https://gist.github.com/mogsdad/e6795e438615d252584f。那里提供了几个例子。
A 之前的回答 https://stackoverflow.com/questions/14406966/upload-pdf-with-ocr-with-google-apps-script-and-possibly-drive-api/14408321#14408321表明可以使用 Drive APIinsert
执行方法OCR http://en.wikipedia.org/wiki/Optical_character_recognition,但没有提供代码详细信息。随着高级 Google 服务的推出,可以通过 Google Apps 脚本轻松访问 Drive API。您确实需要打开并启用Drive API
来自编辑,根据Resources > Advanced Google Services
.
pdfToText()
使用 Drive 服务从 PDF 文件的内容生成 Google 文档。不幸的是,这包含文档中每个页面的“图片” - 我们对此无能为力。然后它使用常规的DocumentService
将文档正文提取为纯文本。
/**
* See gist: https://gist.github.com/mogsdad/e6795e438615d252584f
*
* Convert pdf file (blob) to a text file on Drive, using built-in OCR.
* By default, the text file will be placed in the root folder, with the same
* name as source pdf (but extension 'txt'). Options:
* keepPdf (boolean, default false) Keep a copy of the original PDF file.
* keepGdoc (boolean, default false) Keep a copy of the OCR Google Doc file.
* keepTextfile (boolean, default true) Keep a copy of the text file.
* path (string, default blank) Folder path to store file(s) in.
* ocrLanguage (ISO 639-1 code) Default 'en'.
* textResult (boolean, default false) If true and keepTextfile true, return
* string of text content. If keepTextfile
* is false, text content is returned without
* regard to this option. Otherwise, return
* id of textfile.
*
* @param {blob} pdfFile Blob containing pdf file
* @param {object} options (Optional) Object specifying handling details
*
* @returns {string} id of text file (default) or text content
*/
function pdfToText ( pdfFile, options ) {
// Ensure Advanced Drive Service is enabled
try {
Drive.Files.list();
}
catch (e) {
throw new Error( "To use pdfToText(), first enable 'Drive API' in Resources > Advanced Google Services." );
}
// Set default options
options = options || {};
options.keepTextfile = options.hasOwnProperty("keepTextfile") ? options.keepTextfile : true;
// Prepare resource object for file creation
var parents = [];
if (options.path) {
parents.push( getDriveFolderFromPath (options.path) );
}
var pdfName = pdfFile.getName();
var resource = {
title: pdfName,
mimeType: pdfFile.getContentType(),
parents: parents
};
// Save PDF to Drive, if requested
if (options.keepPdf) {
var file = Drive.Files.insert(resource, pdfFile);
}
// Save PDF as GDOC
resource.title = pdfName.replace(/pdf$/, 'gdoc');
var insertOpts = {
ocr: true,
ocrLanguage: options.ocrLanguage || 'en'
}
var gdocFile = Drive.Files.insert(resource, pdfFile, insertOpts);
// Get text from GDOC
var gdocDoc = DocumentApp.openById(gdocFile.id);
var text = gdocDoc.getBody().getText();
// We're done using the Gdoc. Unless requested to keepGdoc, delete it.
if (!options.keepGdoc) {
Drive.Files.remove(gdocFile.id);
}
// Save text file, if requested
if (options.keepTextfile) {
resource.title = pdfName.replace(/pdf$/, 'txt');
resource.mimeType = MimeType.PLAIN_TEXT;
var textBlob = Utilities.newBlob(text, MimeType.PLAIN_TEXT, resource.title);
var textFile = Drive.Files.insert(resource, textBlob);
}
// Return result of conversion
if (!options.keepTextfile || options.textResult) {
return text;
}
else {
return textFile.id
}
}
转换为 DriveApp 有助于此布鲁斯·麦克弗森的实用程序 http://ramblings.mcpher.com/Home/excelquirks/gooscript/driveapppathfolder:
// From: http://ramblings.mcpher.com/Home/excelquirks/gooscript/driveapppathfolder
function getDriveFolderFromPath (path) {
return (path || "/").split("/").reduce ( function(prev,current) {
if (prev && current) {
var fldrs = prev.getFoldersByName(current);
return fldrs.hasNext() ? fldrs.next() : null;
}
else {
return current ? null : prev;
}
},DriveApp.getRootFolder());
}