简体   繁体   中英

Add page break before text in Apps Script

I'm trying to insert a page break before certain text.

I tried the solution in this post: Replace a text keyword with a "Page Break" element in Apps Script

Which adds the page break after the text, played around with the code and couldn't get it to add it before. As a workaround I was trying to append a paragraph text after I append the page Break, but couldn't get it work.

I believe your goal as follows.

  • You want to insert the pagebreak before a text word in Google Document using Google Apps Script.

In this case, I would like to propose the following sample script using Google Docs API. At Google Docs API, the page can be inserted to the middle of text using index . So I thought that this direction might be a bit simple and the process cost might be able to be also reduced. The flow of this script is as follows.

  1. Retrieve all contents from Google Document using the method of "documents.get" in Docs API.
  2. Create the request body for using the method of "documents.batchUpdate" in Docs API.
  3. Request the request body to the method of "documents.batchUpdate" in Docs API.

Sample script:

Please copy and paste the following script to the script editor of Google Document, and please set searchPattern . And, please enable Google Docs API at Advanced Google services.

function myFunction() {
  const searchText = "{{page break}}";  // Please set text. This script inserts the pagebreak before this text.
  
  // 1. Retrieve all contents from Google Document using the method of "documents.get" in Docs API.
  const docId = DocumentApp.getActiveDocument().getId();
  const res = Docs.Documents.get(docId);
  
  // 2. Create the request body for using the method of "documents.batchUpdate" in Docs API.
  let offset = 0;
  const requests = res.body.content.reduce((ar, e) => {
    if (e.paragraph) {
      e.paragraph.elements.forEach(f => {
        if (f.textRun) {
          const re = new RegExp(searchText, "g");
          let p = null;
          while (p = re.exec(f.textRun.content)) {
            ar.push({insertPageBreak: {location: {index: p.index + offset}}});
          }
        }
      })
    }
    offset = e.endIndex;
    return ar;
  }, []).reverse();
  
  // 3. Request the request body to the method of "documents.batchUpdate" in Docs API.
  Docs.Documents.batchUpdate({requests: requests}, docId);
}
  • In this sample script, const searchPattern = "{{page break}}" is used as the text for inserting the pagebreak. Please modify this for your actual situation.

Result:

When above script is run, the following result is obtained.

From:

在此处输入图像描述

To:

在此处输入图像描述

References:

Added:

I confirmed that google-docs-api is also included in your tags of your question. So I proposed a sample script for using Google Docs API. But from your following replying, it seems that you wanted to use Google Docs API without enabling Google Docs API at Advanced Google services. I couldn't notice about this from your question and tags.

is there a way of doing this without having to enable the Google Docs API in the Apps Script environment? I get a Reference Error for Docs.Documents.get(docId) if I don't.

About your replying, I add one more sample script. In this sample script, Google Docs API is used with UrlFetchApp. So Google Docs API of Advanced Google services is not used. But, in this case, Google Docs API is required to be enabled at API console. So I propose 2 patterns for this.

  1. Please link GCP to GAS project and enable Google Docs API at API console.

  2. Please enable Google Docs API at Advanced Google services once and save the GAS project. Here, please wait for minutes. And then, please disable Google Docs API at Advanced Google services. In the current stage, it seems that even when Google Docs API is disabled at Advanced Google services, Google Docs API is not disabled at API console. But I'm not sure whether this is the permanent situation. But, now, I thought that this might be able to be used for this your situation.

Sample script:

Before you use this script, please enable Google Docs API at API console by doing one of them as I proposed above and run the script.

 function myFunction() { const searchText = "{{page break}}"; // Please set text. This script inserts the pagebreak before this text. // 1. Retrieve all contents from Google Document using the method of "documents.get" in Docs API. const accessToken = ScriptApp.getOAuthToken(); const docId = DocumentApp.getActiveDocument().getId(); const url1 = "https://docs.googleapis.com/v1/documents/" + docId; const response1 = UrlFetchApp.fetch(url1, {headers: {authorization: "Bearer " + accessToken}}); const res = JSON.parse(response1.getContentText()); // 2. Create the request body for using the method of "documents.batchUpdate" in Docs API. let offset = 0; const requests = res.body.content.reduce((ar, e) => { if (e.paragraph) { e.paragraph.elements.forEach(f => { if (f.textRun) { const re = new RegExp(searchText, "g"); let p = null; while (p = re.exec(f.textRun.content)) { ar.push({insertPageBreak: {location: {index: p.index + offset}}}); } } }) } offset = e.endIndex; return ar; }, []).reverse(); // 3. Request the request body to the method of "documents.batchUpdate" in Docs API. const url2 = `https://docs.googleapis.com/v1/documents/${docId}:batchUpdate`; UrlFetchApp.fetch(url2, {method: "post", payload: JSON.stringify({requests: requests}), contentType: "application/json", headers: {authorization: "Bearer " + accessToken}}); // DocumentApp.getActiveDocument(); // This is used for automatically adding a scope of https://www.googleapis.com/auth/documents by the script editor. }

Note:

  • When an error related to Google Docs API occurs, please enable Google Docs API at API console again.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM