问题
Hi all I'm relatively new to scripting. I have some code to convert a google sheet to pdf and email out as an attachment however I am struggling with setting the PDF output page setup. The margins are to big.
/* 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]
});
}
回答1:
Here is a function that includes the margin setting.
It assumes that all settings for each sheet are the same. It also assumes all margins (left, right, top, bottom) are the same, but that is easily changed.
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}
);
}
回答2:
This is something I figured out for formatting google sheet pdf files. Just hack out the code you don't need. But it will allow you to set margins. I never took the time to figure out all the options....but this is quite a few of them. It only prints a single sheet.
function PrintPdfFiles(){
var defSpreadsheet = SpreadsheetApp.getActive()
GoogleSpreadsheetToPdf(defSpreadsheet.getId(), "Sheet3","1 - "+ defSpreadsheet.getName(),0,1,1,0,0,0,
0,1,1,1,'[null,["\\uee15"]]',2,1,'letter',
0,5,0.7,0.5,0.75,0.5,0.5);
GoogleSpreadsheetToPdf(defSpreadsheet.getId(), "Sheet4","2 - "+ defSpreadsheet.getName(),0,1,1,0,0,0,
0,1,1,1,'[null,["\\uee15"]]',2,1,'letter',
0,5,0.7,0.5,0.75,0.5,0.5);
GoogleSpreadsheetToPdf(defSpreadsheet.getId(), "Sheet5","3 - "+ defSpreadsheet.getName(),0,1,0,0,0,0,
0,1,0,1,'null',2,1,'letter',
1,4,1,1.1811023622047245,0.7480314960629921,0.7086614173228347,0.7086614173228347);
}
function GoogleSpreadsheetToPdf(spreadsheetId,sheetName,pdfName,ShowNotes,ShowGridlines,PageNumbers,WorkbookTitle,Sheetname,CurrentDate,
CurrentTime,Repeatfrozenrows,RepeatfrozenCols,PageOrder,PageNmFormat,HorizAlign,VertAlign,PaperSize,
Orientation,Scale,ScaleNumber,topmargin,bottomMargin,leftMargin,RightMargin){
var spreadsheet = SpreadsheetApp.openById(spreadsheetId);
var sheetId = spreadsheet.getSheetByName(sheetName).getSheetId();
var url_base = 'https://docs.google.com/spreadsheets/d/' + spreadsheetId +'/pdf?id=' + spreadsheetId;
var url_ext = '[null,null,null,null,null,null,null,null,null,0,'
+ '[["' + sheetId + '"]]'
+',10000000,null,null,null,null,null,null,null,null,null,null,null,null,null,null,43407.82605613426,null,null,['
+ ShowNotes+',' //(ShowNotes-1isTrue),
+ 'null,'
+ ShowGridlines +',' //(ShowGridlines-0isTrue1isFalse,
+ PageNumbers +',' //(PageNumbers-1isTrue),
+ WorkbookTitle +',' //(WorkbookTitle-1isTrue),
+ Sheetname+',' //(Sheetname-1isTrue),
+ CurrentDate+',' //(CurrentDate-1isTrue),
+ CurrentTime+',' //(CurrentTime-1isTrue),
+ Repeatfrozenrows+',' //(Repeatfrozenrows-1isTrue),
+ RepeatfrozenCols+',' //(RepeatfrozenCols-1isTrue),
+ PageOrder+',' //(PageOrder-1DownthenOver2OverthenDown),
+ '2,null,'
+ PageNmFormat+',' //(Page Number formatting), Page Number formatting "Page 1" - [null,["\\uee15"]]
+ HorizAlign+',' //(HorizAlign-1isLeft2isCenter3isRight),
+ VertAlign+',' //(VertAlign-1isTop2isCenter3isBottom)
+'],["'
+ PaperSize+'",' //letter",
+ Orientation+',' //(1isPortrait-0Landscape),
+ Scale +',' //(Scale-4isFittoPage-5isCustomNumber),
+ ScaleNumber +',' //(Scale),
+'['
+ topmargin+',' //(topmargin),
+ bottomMargin +',' //(bottomMargin),
+ leftMargin+',' //(leftMargin),
+ RightMargin //(RightMargin)
+']],null,0,[["207472796",null,[[21,21]]]]]';
var headers= {
'Authorization': 'Bearer ' + ScriptApp.getOAuthToken()
};
var data = {
"a": "true",
"gf": "[]",
"pc": url_ext
};
var options = {
'headers':headers,
'method' : 'POST',
'payload' : data
};
var response = UrlFetchApp.fetch(url_base, options);
var blob = response.getBlob().setName(pdfName + '.pdf');
var file = DriveApp.createFile(blob);
var fileId = file.getId();
//Check and see if there is a 'PDF files' folder
var PDFFilesFolderId = null;
var RFSFolderId = DriveApp.getFileById(spreadsheetId).getParents().next().getId();
var files = DriveApp.searchFolders('parents="'+RFSFolderId+'" and trashed=false');
while (files.hasNext()) {
var file = files.next();
if(file.getName() == "PDF Files"){
PDFFilesFolderId = file.getId();
}
}
//If the directory is not found create it
if(PDFFilesFolderId == null){
var newFolder=DriveApp.getFolderById(RFSFolderId).createFolder("PDF Files")
files = DriveApp.searchFolders('parents="'+RFSFolderId+'" and trashed=false');
while (files.hasNext()) {
var file = files.next();
if(file.getName() == "PDF Files"){
PDFFilesFolderId = file.getId();
}
}
moveFileId(fileId, PDFFilesFolderId);
}
else{
moveFileId(fileId, PDFFilesFolderId);
}
}
function moveFileId(fileId, toFolderId) {
var file = DriveApp.getFileById(fileId);
var source_folder = DriveApp.getFileById(fileId).getParents().next();
var folder = DriveApp.getFolderById(toFolderId)
folder.addFile(file);
source_folder.removeFile(file);
}
来源:https://stackoverflow.com/questions/52291705/saving-sheet-to-pdf