google-apps-script - 将工作表保存为 PDF
问题描述
大家好,我对脚本比较陌生。我有一些代码可以将谷歌表格转换为 pdf 并作为附件通过电子邮件发送,但是我正在努力设置 PDF 输出页面设置。利润太大了。
/* Email Google Spreadsheet as PDF */
function emailGoogleSpreadsheetAsPDF() {
// Send the PDF of the spreadsheet to this email address
var email = "dav..........n@.....a.com";
// Get the currently active spreadsheet URL (link)
var ss = SpreadsheetApp.getActiveSpreadsheet();
// Subject of email message
var subject = "Please find attached " + ss.getName();
// Email Body can be HTML too
var body = "Please find attached a copy of the Shift Log";
var blob = DriveApp.getFileById(ss.getId()).getAs("application/pdf");
blob.setName(ss.getName() + ".pdf");
// If allowed to send emails, send the email with the PDF attachment
if (MailApp.getRemainingDailyQuota() > 0)
GmailApp.sendEmail(email, subject, body, {
htmlBody: body,
attachments:[blob]
});
}
解决方案
这是一个包含边距设置的功能。
它假定每张纸的所有设置都是相同的。它还假设所有边距(左、右、上、下)都相同,但这很容易改变。
function sendPdfs() {
var sheetsToExport = ['Sheet1', 'Sheet2'];
var getPdf = function (spreadsheetId, sheet) {
var marginStringValue = '0.15';
var margin = '_margin=' + marginStringValue;
var margins = '&top' + margin + '&left' + margin
+ '&right' + margin + '&bottom' + margin;
var url = 'https://docs.google.com/spreadsheets/d/'
+ spreadsheetId + '/export?'
+ 'exportFormat=pdf&format=pdf'
+ '&size=A4'
+ '&portrait=false'
+ '&fitw=true' // Fit to width
+ '&sheetnames=false'
+ '&printtitle=false'
+ '&printnotes=false'
+ '&pagenumbers=false'
+ '&pagenum=CENTER'
+ '&gridlines=false'
+ '&fzr=true' // Repeat frozen rows
+ '&gid=' + sheet.getSheetId()
+ margins;
var token = ScriptApp.getOAuthToken();
var result = UrlFetchApp.fetch(url, {
headers: {
Authorization: 'Bearer ' + token
}
});
var filename = sheet.getName() + '.pdf';
var file = result.getBlob().setName(filename);
return file;
};
var name = null;
var sheet = null;
var spreadsheet = SpreadsheetApp.getActive();
var spreadsheetId = spreadsheet.getId();
var files = [];
for (name in sheetsToExport) {
sheet = spreadsheet.getSheetByName(sheetsToExport[name]);
files.push(getPdf(spreadsheetId, sheet));
}
MailApp.sendEmail(
Session.getActiveUser().getEmail(),
'PDFs',
'Please see attached.',
{attachments: files}
);
}
推荐阅读
- c# - RaisePropertyChanged 在不同的属性上触发“设置”
- java - Apache Bean Utils - 将属性复制到没有设置器的类
- java - 如何在没有spring的javax验证ConstraintValidator中注入bean
- android-source - ninja, kati in aosp - 如何在执行“mm”或“mmm”或“mmma”时打印所有已执行的命令
- html - 如何将两列相对于彼此垂直居中?
- android - SQLite SELECT MAX() 查询返回 null 到游标?
- javascript - 如何在 Vue.js 上的组件之间传递事件信息
- xcode - 1 个用户拥有 2 个 firebase 数据库信息
- powershell - Powershell 参数未按预期工作
- hyperledger-fabric - Hyperledger Fabric 中的客户端和对等角色互换