You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Google Apps Script实现PDF下载自动居中?解决行高偏移问题

问题描述

使用Google Apps Script导出指定范围的表格为PDF时,表格行高固定时导出的PDF内容居中正常,但当输入内容导致行高变化后,PDF内容会向左偏移。手动调整脚本中的边距参数无法适配页面尺寸变化的场景,需要实现PDF内容自动居中。

当前使用的脚本:

function SavePage1() {
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Delivery Orders');
  const range = sheet.getRange("A1:D50");
  
  const url = 'https://docs.google.com/spreadsheets/d/' + sheet.getParent().getId() + 
    '/export?format=pdf&' +
    'size=a4&' + 
    'portrait=true&' + 
    'fitw=true&' +
    'scale=4&' +
    'gridlines=false&' + 
    'printtitle=false&' + 
    'sheetnames=false&' + 
    'pagenum=false&' + 
    'fzr=false&' + 
    'gid=' + sheet.getSheetId() + 
    '&range=' + range.getA1Notation() + 
    '&top_margin=0.197&' + 
    'right_margin=0.197&' + 
    'left_margin=0.197&' + 
    'bottom_margin=0.197&' + 
    'horizontal_alignment=center&' + 
    'vertical_alignment=top';
  
  const response = UrlFetchApp.fetch(url, {headers: {"Authorization": 'Bearer ' + ScriptApp.getOAuthToken()}});
  const blob = response.getBlob().setName("D0.pdf");
  
  const htmlOutput = HtmlService.createHtmlOutput(`
    <a href="data:application/pdf;base64,${Utilities.base64Encode(blob.getBytes())}" download="D0.pdf" id="downloadLink"></a>
    <script>document.getElementById('downloadLink').click(); google.script.host.close();</script>
  `);
  
  SpreadsheetApp.getUi().showModalDialog(htmlOutput, "Download PDF");
}
解决方案

核心思路是动态计算左右边距,让导出内容始终与页面水平居中,同时避免强制宽度适配导致的布局偏移。修改后的脚本如下:

function SavePage1() {
  const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Delivery Orders');
  const range = sheet.getRange("A1:D50");
  
  // A4纵向页面宽度(单位:英寸,210mm转换为英寸:210/25.4≈8.2677)
  const pageWidthInch = 8.2677;
  // 导出范围总宽度转换为英寸(Google Sheets中1点=1/72英寸)
  const rangeWidthInch = range.getWidth() / 72;
  
  // 计算左右边距,确保内容水平居中
  const sideMargin = (pageWidthInch - rangeWidthInch) / 2;

  const url = 'https://docs.google.com/spreadsheets/d/' + sheet.getParent().getId() + 
    '/export?format=pdf&' +
    'size=a4&' + 
    'portrait=true&' + 
    // 移除fitw=true,避免强制缩放内容适配页面宽度
    'scale=4&' +
    'gridlines=false&' + 
    'printtitle=false&' + 
    'sheetnames=false&' + 
    'pagenum=false&' + 
    'fzr=false&' + 
    'gid=' + sheet.getSheetId() + 
    '&range=' + range.getA1Notation() + 
    `&top_margin=0.197&` + 
    `&right_margin=${sideMargin.toFixed(3)}&` + 
    `&left_margin=${sideMargin.toFixed(3)}&` + 
    'bottom_margin=0.197&' + 
    'horizontal_alignment=center&' + 
    'vertical_alignment=top';
  
  const response = UrlFetchApp.fetch(url, {headers: {"Authorization": 'Bearer ' + ScriptApp.getOAuthToken()}});
  const blob = response.getBlob().setName("D0.pdf");
  
  const htmlOutput = HtmlService.createHtmlOutput(`
    <a href="data:application/pdf;base64,${Utilities.base64Encode(blob.getBytes())}" download="D0.pdf" id="downloadLink"></a>
    <script>document.getElementById('downloadLink').click(); google.script.host.close();</script>
  `);
  
  SpreadsheetApp.getUi().showModalDialog(htmlOutput, "Download PDF");
}
关键改动说明
  1. 动态计算边距:通过页面宽度与导出范围宽度的差值,均分得到左右边距,确保内容始终居中,不受行高变化影响。
  2. 移除fitw=true:该参数会强制内容缩放适配页面宽度,容易引发布局偏移,移除后内容按实际尺寸导出,配合计算出的边距实现自然居中。
  3. 适配不同页面尺寸:如果需要支持非A4纸张,可以通过sheet.getPageSetup().getPaperSize()获取当前纸张设置,对应替换pageWidthInch的值即可。

内容的提问来源于stack exchange,提问作者russetsyren

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.15 23:05:01