我想在使用Google Apps脚本导出到PDF之前,以编程方式在Google Spreadsheet中设置分页符
应该可以,因为您可以在打印电子表格(https://support.google.com/docs/answer/7663148?hl=en)时手动设置分页符
我发现Google文档(https://developers.google.com/apps-script/reference/document/page-break)中有可能,但是他们没有在工作表中提及它。
即使这是“黑客”,有办法吗?
答案 0 :(得分:2)
关于“黑客”,当您尝试通过将开发者工具-网络保存为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]
其中:
[["1990607563",[[45,92],[139,139]],[[0,15]]]],0] // page breaks parameters
请注意,尽管我使用了自定义分页符和横向,这在上面的响应中有所反映。
将所有内容放在一起,下面的代码就能解决问题:
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);
}
此处提供了有关该黑客行为的更详细说明 Export Google Sheets to PDF(仅俄语)。
答案 1 :(得分:2)
我变通了。我通过更改行高以适合所需的纸张尺寸来调整页面尺寸(A4)。 导出为pdf时,google会更改尺寸以适合宽度。我将列的大小加起来,然后相应地设置行高。数字是通过反复试验选择的。
var width = 0;
for(var z = 0; z < s4.getLastColumn(); z++){
width += s4.getColumnWidth(z+1);
}
var a4PageHeightPixels = 1050 * width / 800;
因为我希望所有行的高度都相同,所以我将行高设置为页面高度除以行数。确保最后一行为空白后,我调整了最后一行以解决舍入误差。
rowHeight= Math.floor(a4PageHeightPixels/(numDataRows ));
lastRowHeight = a4PageHeightPixels - (numDataRows -1) * rowHeight;
s4.setRowHeights(pageFirstRow,numDataRows-1,rowHeight);
s4.setRowHeight(pageFirstRow+numDataRows-1,lastRowHeight);
(s4是我正在使用的工作表)但是,我希望大多数人只希望在每页底部插入一个空白行,并调整其大小以适合pdf纸张大小。