首页 > 解决方案 > 将工作表保存为 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]     
    });  
}

标签: google-apps-scriptgoogle-sheetsexport-to-pdf

解决方案


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

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

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

推荐阅读