如何使用应用脚本访问 Google 云端硬盘上受密码保护的 PDF 文件



我每月通过电子邮件收到账单,这是一个受密码保护的PDF文件。该文件始终具有相同的密码。我最终尝试使用Google Apps脚本(和Drive API)从Gmail获取文件,使用OCR将其保存到我的云端硬盘上,然后将其保存到单独的文档中,我可以从中获取文本并进一步在我的脚本中使用它。

我在这里简化了我的用例,只是尝试将文件保存到驱动器并通过脚本访问它,但我无法以编程方式访问它,因为似乎没有办法传入密码。

for (var x in threads) {      
var messages = threads[x].getMessages();
for (var y in messages) {
var from = messages[y].getFrom().slice(messages[y].getFrom().indexOf('<')+1, messages[y].getFrom().indexOf('>'));          
if (from == 'EMAIL-GOES-HERE') {
var attachment = messages[y].getAttachments()[0];
var blob = attachment.getAs(MimeType.PDF);
var resource = {title: blob.getName(), mimeType: blob.getContentType()};
var file = Drive.Files.insert(resource, blob);
var doc = DocumentApp.openById(file.id);
...

我希望能够通过传入已知密码来访问该文件;但是,由于我无法发送密码,因此收到错误:"文档无法访问。请稍后再试。

您想使用
  • Google Apps 脚本使用密码解密受保护的 PDF 文件。
  • 您可以使用外部 API。

如果我的理解是正确的,那么这个答案呢?

问题:

不幸的是,在当前阶段,没有准备好的Google Apps Script方法来打开受密码保护的PDF。我对此发表了评论。

解决方法:

在这里,作为几种解决方法之一,我想建议使用外部 API 进行解密。因为通过Google Apps Script分析加密文件会导致更高的处理成本。所以我想建议使用PDF来解密ConvertAPI的API。在这种情况下,此解决方法的过程成本远低于仅使用 Google Apps 脚本的解决方法。

制备:

例如,当您尝试此操作时,您也可以使用"免费包"进行测试。当您尝试在 ConvertAPI 上使用"免费包"时,请在"免费包"注册并检索您的密钥。

示例脚本:

在运行脚本之前,请设置secretkeypass的变量。

function myFunction() {
var obj = {
secretkey: "###",  // Your secret key.
pass: "###", // Password of the protected PDF file.
blob: blob, // blob of var blob = attachment.getAs(MimeType.PDF);
}
var blob = decrypting(obj);
DriveApp.createFile(blob);
}
function decrypting(obj) {
var url = "https://v2.convertapi.com/convert/pdf/to/decrypt?Secret=" + obj.secretkey;
var options = {
method: "post",
payload: {File: obj.blob, PdfOwnerPassword: obj.pass},
}
var res = UrlFetchApp.fetch(url, options);
res = JSON.parse(res.getContentText());
var blob = res.Files.map(function(e) {return Utilities.newBlob(Utilities.base64Decode(e.FileData), MimeType.PDF, e.FileName)});
return blob[0];
}

注意:

  • 在设置变量后运行myFunction()时,未受保护的 PDF 将创建到根文件夹。
  • 当您将此脚本用于脚本时,作为一种方法,请按如下方式进行修改。

    for (var x in threads) {
    var messages = threads[x].getMessages();
    for (var y in messages) {
    var from = messages[y].getFrom().slice(messages[y].getFrom().indexOf('<')+1, messages[y].getFrom().indexOf('>'));          
    if (from == 'EMAIL-GOES-HERE') {
    var attachment = messages[y].getAttachments()[0];
    var blob = attachment.getAs(MimeType.PDF);
    // Added
    var obj = {
    secretkey: "###",  // Your secret key.
    pass: "###", // Password of the protected PDF file.
    blob: blob, // blob of var blob = attachment.getAs(MimeType.PDF);
    }
    blob = decrypting(obj);
    // Added
    var resource = {title: blob.getName(), mimeType: blob.getContentType()};
    var file = Drive.Files.insert(resource, blob);
    var doc = DocumentApp.openById(file.id);
    ...
    

引用:

  • 转换接口
  • PDF 到 DECRYPT API

最新更新