是否可以使用 Apps 脚本将分页符添加到 Google 电子表格中?

vic*_*bou 5 pdf page-break google-sheets google-apps-script

我想在导出为 PDF 之前使用 Apps 脚本以编程方式在我的 Google 电子表格中设置分页符

应该可以,因为您可以在打印电子表格时手动设置分页符 ( https://support.google.com/docs/answer/7663148?hl=en )

我发现在 Google Docs ( https://developers.google.com/apps-script/reference/document/page-break ) 中是可能的,但他们没有在工作表上提到它。

有没有办法做到这一点,即使它是“黑客”?

Ale*_*kov 3

说到“黑客”,当您尝试通过开发人员工具 - 网络将工作表另存为 PDF 时,您可能会尝试捕获从电子表格发送到 Google 的 HTTP 请求。

在此输入图像描述 在此输入图像描述

从这个链接你可以得到格式化参数 pc,在我的例子中它看起来像这样:

[null,null,null,null,null,null,null,null,null,0,
[["1990607563"]],
10000000,null,null,null,null,null,null,null,null,null,null,null,null,null,null,
43866.56179325232,
null,null,
[0,null,1,0,0,0,1,1,1,1,2,1,null,null,2,1],
["A4",0,6,1,[0.75,0.75,0.7,0.7]],
null,0,
[["1990607563",[[45,92],[139,139]],[[0,15]]]],0]
Run Code Online (Sandbox Code Playgroud)

在哪里:

[["1990607563",[[45,92],[139,139]],[[0,15]]]],0]  // page breaks parameters
  
Run Code Online (Sandbox Code Playgroud)

请注意,我使用了自定义分页符和横向方向,这反映在上面的响应中。

把它们放在一起,下面的代码就可以达到目的:

function exportPDFtoGDrive (ssID, filename, source){
  var source = "1990607563"
  var dt = new Date();
  var d = encodeDate(dt.getFullYear(),dt.getMonth(),dt.getDate(),dt.getHours(),dt.getMinutes(),dt.getSeconds());
  var pc = [null,null,null,null,null,null,null,null,null,0,
            [[source]],
            10000000,null,null,null,null,null,null,null,null,null,null,null,null,null,null,
            d,
            null,null,
            [0,null,1,0,0,0,1,1,1,1,2,1,null,null,2,1],
            ["A4",0,6,1,[0.75,0.75,0.7,0.7]],
            null,0,
            [[source,[[45,92],[139,139]],[[0,15]]]],0];
           
  
 var folder = DriveApp.getFoldersByName("FolderNameGoesHere").next(); 
  
  var options = {
    'method': 'post',
    'payload': "a=true&pc="+JSON.stringify(pc)+"&gf=[]",
    'headers': {Authorization: "Bearer " + ScriptApp.getOAuthToken()},
      'muteHttpExceptions': true
};

const esid = (Math.round(Math.random()*10000000));
const theBlob = 
UrlFetchApp.fetch("https://docs.google.com/spreadsheets/d/"+ssID+"/pdf?id="+ssID+"&esid="+esid, options).getBlob();
folder.createFile(theBlob).setName(filename+".pdf");
}

function myExportPDFtoGDrive(){
  
  var ss = SpreadsheetApp.openById('yourSpreadSheetID');
  var sheet = ss.getSheetByName("NameGoesHere");

  var filename = ss.getName()+" ["+sheet.getName()+"]";
  exportPDFtoGDrive (ss.getId(),filename);
}
Run Code Online (Sandbox Code Playgroud)

有关该黑客攻击的更详细说明可在此处 将 Google Sheets 导出为 PDF(尽管仅提供俄语版本)。