Google Spreadsheet to pdf with watermark in Google script

早过忘川 提交于 2019-11-29 16:38:53

It looks like the spreadsheet is already converted to a PDF. A third party service can be used to add a watermark to open the PDF and add a watermark to it. PDF WebAPI is a free service you can use. Below I put together a function that can take in a PDF and add a watermark to it. The watermark is hardcoded to "watermark.jpg" currently, but that can be changed. From looking at the code above, the function should be called between the following lines:

var pdf = DriveApp.getFileById(tempSpreadsheet.getId()).getAs(MimeType.PDF);
var pdfBytes = pdf.getBytes();

The "pdf" variable should be used as input, and "pdfBytes", can take the return value of appendWatermark().

You will need to sign up for a free PDF WebAPI account to get an ID and key.

function appendWatermark(inputPDF) {

  var fileBlob = inputPDF.copyBlob();

  var decorationData = [{
    "watermarkSettings": {
      "opacity": 50,
      "source": {
        "file": "watermark.jpg",
        "page": 1
      },
      "scale": {
        "type": "relative",
        "percent": 90
      },
      "location": "top",
      "rotation": "0"
    }
  }];

  var applicationData = {
    "id": "",
    "key": ""
  };

  var payload = {
    "application": JSON.stringify(applicationData),
    "input": fileBlob,
    "decorationData": JSON.stringify(decorationData),
    "resource": DriveApp.getFilesByName("watermark.jpg").next().getBlob()
  };

  var options = {
    "method": "post",
    "payload": payload
  };

  var response = UrlFetchApp.fetch("https://pdfprocess.datalogics.com/api/actions/decorate/document", options);

  return response.getBytes;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!