在Apps脚本中的文本之前添加分页符 [英] Add page break before text in Apps Script

查看:71
本文介绍了在Apps脚本中的文本之前添加分页符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在某些文本之前插入分页符.

我在这篇文章中尝试了解决方案:

至:

参考文献:

已添加:

我确认 google-docs-api 也包含在问题标签中.因此,我提出了一个使用Google Docs API的示例脚本.但是从您的以下答复看来,您似乎想使用Google Docs API而不在高级Google服务中启用Google Docs API.从您的问题和标签中,我无法注意到这一点.

有没有一种方法可以不必在Apps脚本环境中启用Google Docs API?如果没有,我会收到Docs.Documents.get(docId)的参考错误.

关于您的回复,我再添加一个示例脚本.在此示例脚本中,Google Docs API与UrlFetchApp一起使用.因此,不使用高级Google服务的Google Docs API.但是,在这种情况下,需要在API控制台上启用Google Docs API.因此,我为此提出了两种模式.

  1. 请将GCP链接到GAS项目,并在API控制台上启用Google Docs API.

  2. 请一次在高级Google服务中启用Google Docs API,然后保存GAS项目.在这里,请等待几分钟.然后,请在高级Google服务中禁用Google Docs API.在目前阶段,即使在高级Google服务中禁用了Google Docs API,似乎也没有在API控制台上禁用Google Docs API.但是我不确定这是否是永久的情况.但是,现在,我认为这可能可以用于您的情况.

示例脚本:

在使用此脚本之前,请按照我上面建议的方法之一在API控制台上启用Google Docs API,然后运行脚本.

  function myFunction(){const searchText ="{{page break}}";//请设置文字.该脚本在此文本之前插入分页符.//1.使用"documents.get"方法从Google Document中检索所有内容.在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.使用"documents.batchUpdate"方法创建请求主体.在Docs API中.令offset = 0;const请求= res.body.content.reduce((ar,e)=> {如果(段落){e.paragraph.elements.forEach(f => {如果(f.textRun){const re = new RegExp(searchText,"g");令p = null;while(p = re.exec(f.textRun.content)){ar.push({insertPageBreak:{location:{index:p.index + offset}}});}}})}偏移量= e.endIndex;返回ar;}, []).撤销();//3.请求请求主体使用"documents.batchUpdate"方法.在Docs API中.const url2 =`https://docs.googleapis.com/v1/documents/$ {docId}:batchUpdate`;UrlFetchApp.fetch(url2,{方法:"post",有效负载:JSON.stringify({requests:requests}),contentType:"application/json",标头:{authorization:"Bearer" + accessToken}});//DocumentApp.getActiveDocument();//这用于通过脚本编辑器自动添加https://www.googleapis.com/auth/documents的范围.} 

注意:

  • 当发生与Google Docs API相关的错误时,请再次在API控制台上启用Google Docs API.

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.

这篇关于在Apps脚本中的文本之前添加分页符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆