使用Google脚本中的水印将Google电子表格转换为pdf

时间:2015-05-13 16:09:18

标签: google-apps-script google-sheets pdf-generation google-spreadsheet-api

我想用水印/背景图片转换电子表格,然后发送+保存生成的pdf 转换为pdf有效,但我不知道是否/如何将图像放到生成的pdf中。

这就是我现在所拥有的:



function ExportAndSent(subject, filename, email) {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var message = "A message";
  
  var tempSpreadsheet = SpreadsheetApp.create(filename);
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
  sheet = ss.getActiveSheet();
  sheet.copyTo(tempSpreadsheet);
  
  tempSpreadsheet.deleteActiveSheet();
  
  var pdf = DriveApp.getFileById(tempSpreadsheet.getId()).getAs(MimeType.PDF);
  var pdfBytes = pdf.getBytes();
  var attach = {fileName:(filename + ".pdf"),content:pdfBytes, mimeType:MimeType.PDF};
  
  // Here we need to put a watermark
  
  // Send and export
  MailApp.sendEmail(email, subject, message, {attachments:[attach]});
  DriveApp.createFile(pdf);
  
  // Delete Temporary
  DriveApp.getFileById(tempSpreadsheet.getId()).setTrashed(true);
}




1 个答案:

答案 0 :(得分:0)

看起来电子表格已经转换为PDF。第三方服务可用于添加水印以打开PDF并为其添加水印。 PDF WebAPI是您可以使用的免费服务。下面我整理了一个可以接收PDF并为其添加水印的功能。水印被硬编码为" watermark.jpg"目前,但可以改变。通过查看上面的代码,应该在以下行之间调用该函数:



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




" pdf"变量应该用作输入," pdfBytes",可以取appendWatermark()的返回值。

您需要注册一个免费的PDF WebAPI帐户才能获得ID和密钥。



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;
}