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

Apps Script中UrlFetchApp打印PDF时 Gujarati(Shruti)字体排版异常求助

Google Sheets Apps Script 导出PDF时古吉拉特语字体排版异常问题解决

问题说明

用Apps Script的UrlFetchApp导出指定区域为PDF时,古吉拉特语(Shruti字体)行距过大,内容超出表格边界;但通过原生打印按钮(或Ctrl+P)打印同一区域时,字体排版紧凑正常。英文字体在两种导出方式下都没问题,只有古吉拉特语在UrlFetchApp生成的PDF里出现行距异常。

解决方案

1. 无法直接用Apps Script调用Ctrl+P

Ctrl+P是浏览器端的交互操作,Apps Script运行在Google服务器上,没法直接触发客户端的浏览器打印。

2. 调整PDF导出参数适配排版

修改UrlFetchApp请求的导出参数,强制控制渲染规则,尽量匹配原生打印效果:

  • 加&fzr=true参数强制缩放适配
  • 关闭网格线&gridlines=false
  • 明确设置纸张尺寸和窄边距,比如A4纸+0.1英寸边距
  • 隐藏标题、页码和工作表名,避免额外占用空间

优化后的代码示例:

function printRangeToPDF() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const sheet = ss.getActiveSheet();
  const range = sheet.getRange("A1:A13");
  
  // 构建PDF导出URL
  const baseUrl = `https://docs.google.com/spreadsheets/d/${ss.getId()}/export?`;
  const params = {
    format: "pdf",
    size: "A4",
    fzr: "true", // 强制缩放适配内容
    gridlines: "false",
    printtitle: "false",
    top_margin: 0.1,
    bottom_margin: 0.1,
    left_margin: 0.1,
    right_margin: 0.1,
    sheetnames: "false",
    pagenum: "false",
    gid: sheet.getSheetId(),
    range: range.getA1Notation()
  };
  
  // 拼接参数为查询字符串
  const queryString = Object.entries(params)
    .map(([key, val]) => `${key}=${encodeURIComponent(val)}`)
    .join("&");
  
  const fullUrl = baseUrl + queryString;
  
  // 发送请求并保存PDF到云端硬盘
  const response = UrlFetchApp.fetch(fullUrl, {
    headers: { 'Authorization': `Bearer ${ScriptApp.getOAuthToken()}` }
  });
  
  DriveApp.createFile(response.getBlob().setName("古吉拉特语区域打印.pdf"));
}

3. 字体或单元格样式调整

如果参数调整没用,试试这两个办法:

  • 把Shruti字体换成Google Sheets支持的其他古吉拉特语字体(比如Gujarati Sangam MN),这类字体在服务器端渲染更稳定
  • 手动设置单元格固定行高,不要用自适应行高,避免导出时被自动拉伸

4. 客户端渲染方案(和Ctrl+P效果一致)

如果必须用原生打印的渲染效果,可以用HtmlService生成包含目标区域的网页,在客户端触发打印:

function showPrintDialog() {
  const ss = SpreadsheetApp.getActiveSpreadsheet();
  const sheet = ss.getActiveSheet();
  const range = sheet.getRange("A1:A13");
  const values = range.getDisplayValues();
  
  // 生成带样式的HTML表格
  let html = `
  <html>
    <head>
      <style>
        table {border-collapse: collapse; width: 100%;}
        td {border: 1px solid #000; padding: 4px; font-family: 'Shruti'; font-size: 14px;}
      </style>
    </head>
    <body>
      <table>`;
  
  values.forEach(row => {
    html += "<tr>";
    row.forEach(cell => html += `<td>${cell}</td>`);
    html += "</tr>";
  });
  
  html += `
      </table>
      <script>window.onload = () => window.print();</script>
    </body>
  </html>`;
  
  // 显示打印对话框
  SpreadsheetApp.getUi().showModalDialog(
    HtmlService.createHtmlOutput(html).setWidth(400).setHeight(600),
    "打印预览"
  );
}

这个方法用浏览器的渲染引擎生成PDF,和Ctrl+P效果完全一致,不过需要用户手动确认打印操作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 03:28:13