Google 表格脚本 – 导出 PDF – 如何在新页面上获取重叠的文本?

Google Sheets Script – export PDF – How to get overlapping text on new page?

提问人:godspeed 提问时间:11/14/2023 更新时间:11/14/2023 访问量:26

问:

我制作了一个脚本,该脚本从 Google 表格文件中获取多个范围,并将每个范围导出到 PDF 文件中的单个页面上。

到目前为止它工作正常,但我遇到了一个大问题:当一行高于页面大小(A4)时,页面外的内容将不会显示。有没有办法,以便发生自动分页并将重叠的文本打印在新页面上?

async function PDFAngebot() {
  var sheetId = "1949460457"; // Sheet ID – letzte Zahlen von Link des Sheets.
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var ssId = ss.getId();
  var sheet = ss.getSheetByName('AN_Vorlage');

  var pageAmmount = sheet.getRange('V13').getValue();
  pageAmmount -= 1;
  var rangeVariable =3 + pageAmmount;
  var rangeInput = 'X3' + ':' + 'X' + rangeVariable;
  var ranges = sheet.getRange(rangeInput).getValues(); // Ranges die exportiert werden.


  ss.toast('pageAmmount: ' + pageAmmount + 'rangeVariable: ' + rangeVariable + 'ranges: ' + ranges);

  var token = ScriptApp.getOAuthToken();
  var data = ranges.map(r => {
    var url = `https://docs.google.com/spreadsheets/d/${ssId}/export?format=pdf&exportFormat=pdf&size=A4&portrait=true&scale=2&top_margin=0.15&left_margin=0&right_margin=0&bottom_margin=0.15&range=${r}&gid=${sheetId}`;
    return new Uint8Array(UrlFetchApp.fetch(url, { headers: { Authorization: "Bearer " + token } }).getContent());
  });

  // Load pdf-lib.js
  var cdnUrl = "https://cdn.jsdelivr.net/npm/pdf-lib/dist/pdf-lib.min.js";
  eval(UrlFetchApp.fetch(cdnUrl).getContentText().replace(/setTimeout\(.*?,.*?(\d*?)\)/g, "Utilities.sleep($1);return t();"));
  // Merge PDF data.
  var pdfDoc = await PDFLib.PDFDocument.create();
  for (let i = 0; i < data.length; i++) {
    var pdfData = await PDFLib.PDFDocument.load(data[i]);
    var pages = await pdfDoc.copyPages(pdfData, [...Array(pdfData.getPageCount())].map((_, i) => i));
    pages.forEach(page => pdfDoc.addPage(page));
  }
  var bytes = await pdfDoc.save();
  var contents = Utilities.newBlob([...new Int8Array(bytes)], MimeType.PDF, "sample.pdf");

  // PDF blob is created as a file. This is from your showing script.
  var inputs = sheet.getRange('H9:H10').getValues();
  var folder = DriveApp.getFolderById(inputs[1][0]);
  DriveApp.createFile(contents).setName(inputs[0][0] + ".pdf").moveTo(folder);
}
google-apps-script google-sheets urlfetch export-to-pdf

评论

0赞 Tanaike 11/14/2023
我必须为我糟糕的英语水平道歉。不幸的是,我无法理解.为了正确理解您的问题,您能否提供您期望的示例输入和输出情况?首先,我想正确理解您的问题。Is there a way, so that an automatic page break happens and the overlapping text gets printed on a new page?
0赞 godspeed 11/14/2023
我有一个有很多文本的单元格。生成 pdf 时,此单元格高于页面大小。所有不适合页面的文本都会消失 = 文本在页面末尾被截断。我希望此页面上未显示的文本将显示在新页面上,而不是消失。我希望我更好地解释了它。请告诉我。
0赞 Tanaike 11/14/2023
感谢您的回复。关于,我认为当电子表格的行大于 PDF 数据的一页时,剩余的行将被放入新页面中。不幸的是,我无法复制你的情况。对此,我深表歉意。那么,您能否提供示例电子表格以正确复制当前问题?I would like that the text that is not shown on this page will be shown on a new page instead of just disappearing.

答: 暂无答案