使用Google Apps脚本在Convertapi中合并PDF

发布于 2025-01-18 03:21:17 字数 2471 浏览 2 评论 0原文

我正在尝试通过Convertapi将两个PDF文件与以下代码合并。 PDF1和PDF2都是文件对象。

function mergePDFs(pdf1,pdf2){
  const formData = ""

  formData['Files[0]'] = pdf1.getBlob();
  formData['Files[1]'] = pdf2.getBlob();

  Logger.log(formData['Files[0]']);
  Logger.log(formData);

  endpoint = "https://v2.convertapi.com/convert/pdf/to/merge?Secret=XXXXXXXXXXXXX&StoreFile=true"

  var options = {
    'method' : 'post',
    'payload' : formData,
    'muteHttpExceptions': true
  };

  Logger.log(UrlFetchApp.fetch(endpoint,options));
}

我收到以下错误代码:

{"Code":4000,"Message":"Parameter validation error.","InvalidParameters":{"Files":["Files array item count must be greater than 0."]}}

应注意两个logger.log()语句空白。在我看来,PDF1和PDF2对FormData ['files [index]']的作业并不是

我不熟悉此语法的情况,而是对以下几行进行了大量修改,而是在另一个堆栈溢出发布

  formData['Files[0]'] = pdf1.getBlob();
  formData['Files[1]'] = pdf2.getBlob();

我还发现,无论是宣布为数组还是字符串,formdata的声明都是无关紧要的。

最后,相关文档来自convertapi的文档

要转换的文件。值可以是URL或文件内容。如果在>查询或多部分内容参数中使用,则必须用索引> eg文件[0],文件 1 ,文件[2] ...

主要函数的以下几行与所讨论的函数相关:

  //lodgingRecieptId is set to a url
  const receiptFile = DriveApp.getFileById(lodgingReceiptId);

  ...

  const copyID = frontPage.makeCopy().getId();
  const copyDoc = DocumentApp.openById(copyID)
  copyDoc.setName("MPD | " + sheet.getLastRow());
  const body = copyDoc.getBody();

  //find and replace in template copy
  body.replaceText("{{AMOUNT}}",amount)
  body.replaceText("{{CURRENT_DATE}}",current_date)
  body.replaceText("{{LOCATION}}",location)
  body.replaceText("{{PURPOSE}}",purpose);
  body.replaceText("{{DEPART_DATE}}",formatLeaveDate);
  body.replaceText("{{RETURN_DATE}}",formatReturnDate);
  body.replaceText("{RSB}   ",rsb);
  body.replaceText("{{DAYS}}",days);
  body.replaceText("{{MPD_AMOUNT}}",mpdAmount);

  const docBlob = copyDoc.getAs('application/pdf');
  docBlob.setName(copyDoc.getName() + ".pdf");
  const copyPdf = DriveApp.createFile(docBlob);

  //merge lodging receipt and template copy ——> Save id
  mergePDFs(copyPdf,receiptFile)

I'm attempting to merge two PDF files from Google Drive via ConvertAPI with the following code. Both pdf1 and pdf2 are file objects.

function mergePDFs(pdf1,pdf2){
  const formData = ""

  formData['Files[0]'] = pdf1.getBlob();
  formData['Files[1]'] = pdf2.getBlob();

  Logger.log(formData['Files[0]']);
  Logger.log(formData);

  endpoint = "https://v2.convertapi.com/convert/pdf/to/merge?Secret=XXXXXXXXXXXXX&StoreFile=true"

  var options = {
    'method' : 'post',
    'payload' : formData,
    'muteHttpExceptions': true
  };

  Logger.log(UrlFetchApp.fetch(endpoint,options));
}

To which I receive the following error code:

{"Code":4000,"Message":"Parameter validation error.","InvalidParameters":{"Files":["Files array item count must be greater than 0."]}}

It should be noted both Logger.log() statement come up empty. It appears to me that assignments of pdf1 and pdf2 to formData['Files[index]'] are not

I have modified the following lines considerably as I'm not familiar with this syntax, but it was referenced on another Stack Overflow post.

  formData['Files[0]'] = pdf1.getBlob();
  formData['Files[1]'] = pdf2.getBlob();

I'm also finding that the declaration of formData is inconsequential regardless of whether it's declared as an array or as a string.

Lastly, the pertinent documentation from ConvertAPI says:

Files to be converted. Value can be URL or file content. If used in >query or multipart content parameter must be suffixed with index >e.g. Files[0], Files1, Files[2]...

The following lines from the main function are the pertinent ones to the function in question:

  //lodgingRecieptId is set to a url
  const receiptFile = DriveApp.getFileById(lodgingReceiptId);

  ...

  const copyID = frontPage.makeCopy().getId();
  const copyDoc = DocumentApp.openById(copyID)
  copyDoc.setName("MPD | " + sheet.getLastRow());
  const body = copyDoc.getBody();

  //find and replace in template copy
  body.replaceText("{{AMOUNT}}",amount)
  body.replaceText("{{CURRENT_DATE}}",current_date)
  body.replaceText("{{LOCATION}}",location)
  body.replaceText("{{PURPOSE}}",purpose);
  body.replaceText("{{DEPART_DATE}}",formatLeaveDate);
  body.replaceText("{{RETURN_DATE}}",formatReturnDate);
  body.replaceText("{RSB}   ",rsb);
  body.replaceText("{{DAYS}}",days);
  body.replaceText("{{MPD_AMOUNT}}",mpdAmount);

  const docBlob = copyDoc.getAs('application/pdf');
  docBlob.setName(copyDoc.getName() + ".pdf");
  const copyPdf = DriveApp.createFile(docBlob);

  //merge lodging receipt and template copy ——> Save id
  mergePDFs(copyPdf,receiptFile)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

阳光的暖冬 2025-01-25 03:21:17

从你的展示脚本和你的展示官方文档来看,下面的修改如何?

修改后的脚本:

请将 替换为您的秘密。

function mergePDFs(pdf1, pdf2) {
  var fileValues = [pdf1.getBlob(), pdf2.getBlob()].map((e, i) => ({
    "Name": e.getName() || `sample${i + 1}`,
    "Data": Utilities.base64Encode(e.getBytes())
  }));
  var data = { "Parameters": [{ "Name": "Files", "FileValues": fileValues }, { "Name": "StoreFile", "Value": true }] };
  var endpoint = "https://v2.convertapi.com/convert/pdf/to/merge?Secret=<YOUR SECRET HERE>";
  var options = {
    'method': 'post',
    'payload': JSON.stringify(data),
    'contentType': "application/json",
    'muteHttpExceptions': true
  };
  var res = UrlFetchApp.fetch(endpoint, options);
  var outputPDFURL = JSON.parse(res.getContentText()).Files[0].Url;
  var outputFile = UrlFetchApp.fetch(outputPDFURL).getBlob().setName("sampleOutput.pdf");
  DriveApp.createFile(outputFile);
}

注意:

  • 在此修改中,假设您的密钥对于使用此 API 有效,并且 pdf1pdf2 是 PDF 数据的文件对象或 HTTPResponse 对象。请注意这一点。

参考资料:

From your showing script and your showing official document, how about the following modification?

Modified script:

Please replace <YOUR SECRET HERE> with your secret.

function mergePDFs(pdf1, pdf2) {
  var fileValues = [pdf1.getBlob(), pdf2.getBlob()].map((e, i) => ({
    "Name": e.getName() || `sample${i + 1}`,
    "Data": Utilities.base64Encode(e.getBytes())
  }));
  var data = { "Parameters": [{ "Name": "Files", "FileValues": fileValues }, { "Name": "StoreFile", "Value": true }] };
  var endpoint = "https://v2.convertapi.com/convert/pdf/to/merge?Secret=<YOUR SECRET HERE>";
  var options = {
    'method': 'post',
    'payload': JSON.stringify(data),
    'contentType': "application/json",
    'muteHttpExceptions': true
  };
  var res = UrlFetchApp.fetch(endpoint, options);
  var outputPDFURL = JSON.parse(res.getContentText()).Files[0].Url;
  var outputFile = UrlFetchApp.fetch(outputPDFURL).getBlob().setName("sampleOutput.pdf");
  DriveApp.createFile(outputFile);
}

Note:

  • In this modification, it supposes that your secret is valid for using this API and pdf1 and pdf2 are the file object or the HTTPResponse object of the PDF data. Please be careful about this.

References:

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文