将工作表保存为PDF

时间:2018-09-12 09:19:48

标签: google-apps-script google-sheets export-to-pdf

大家好,我是脚本的新手。我有一些代码可以将Google工作表转换为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]     
    });  
}

2 个答案:

答案 0 :(得分:0)

这是我发现的用于格式化Google表格pdf文件的内容。只需破解不需要的代码即可。但这将允许您设置边距。我从来没有花时间来找出所有的选择。。。。但是其中很多。它只打印一张纸。

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

答案 1 :(得分:0)

这是包含边距设置的功能。

假定每张纸的所有设置都相同。 它还假定所有边距(左,右,上,下)都相同,但是很容易更改。

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