使用Google Apps脚本将文本占位符替换为图像 [英] Replace text placeholder with image using Google Apps Script

查看:18
本文介绍了使用Google Apps脚本将文本占位符替换为图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将四个图像放入我的Google文档中,它们应该被格式化为相同的大小并在一个正方形内。我正在尝试替换文本占位符,但我愿意使用其他方法。

图像URL位于我的Google工作表中,我正在将它们初始化为变量。

我正在尝试遍历这4个图像中的每一个,并用它们替换每个相应的文本占位符。

function createDocument() {
  var headers = Sheets.Spreadsheets.Values.get('1Yy70i8aQ3GZEp5FE5mhO458Bmivu01ZeykG0GFZmrVo', 'A4:AL4');
  var tactics = Sheets.Spreadsheets.Values.get('1Yy70i8aQ3GZEp5FE5mhO458Bmivu01ZeykG0GFZmrVo', 'A5:J26');
  var templateId = '1ajVQxJAgGxXF3ivkaWL5WEv2xhiJc9r0YwxLH5Hm17w';
      
  for(var i = 0; i < tactics.values.length; i++){
        
        // see what the sheets API is returning
        Logger.log(tactics);
        
        // initialise variables from the sheet
        var projectID = tactics.values[i][0];
        var projectName = tactics.values[i][1];
      
        // copy our template and capture the ID of the copied document
        var documentId = DriveApp.getFileById(templateId).makeCopy().getId();
        
        // name the copied doc by projectID
        DriveApp.getFileById(documentId).setName(projectID + 'overview');
        
        // update the body of the document
        var body = DocumentApp.openById(documentId).getBody();
        
        // replace template placeholders with sheet variables
        body.replaceText('##ProjectID##', projectID)
        body.replaceText('##ProjectName##', projectName)

        // initialise images from URLs
        var URL1 = tactics.values[i][10];
        var URL2 = tactics.values[i][11];
        var URL3 = tactics.values[i][12];
        var URL4 = tactics.values[i][13];

        var fileID1 = URL1.match(/[w\_-]{25,}/).toString();
        var img1   = DriveApp.getFileById(fileID1).getBlob()
        var item1 = body.appendListItem('Item 1');
        // item1.addPositionedImage(img1); add images so that they are formatted as a square as shown below

执行此操作的GitHub函数具有 已评论-https://gist.github.com/tanaikech/f84831455dea5c394e48caaee0058b26-如何为4个图像URL中的每一个实施此操作?

推荐答案

您似乎正在使用高级服务,而不是常规服务。您还应该将这段代码拆分成更易于管理的函数。我喜欢这个问题,所以这是我的解决方案:

const SHEET_ID = ''
const TEMPLATE_ID = ''

/**
 * Entry, what you call to make the template.
 */
function createAllDocuments() {
  const spreadsheet = SpreadsheetApp.openById(SHEET_ID)
  const sheet = spreadsheet.getSheets()[0] // Only sheet?
  const tactics = sheet.getRange('A5:M')
    .getValues()
    .filter(arr => arr.some(v => !!v)) // Remove empty rows
  
  for (let tactic of tactics) {
    // Get the variables for the tactic
    const projectID = tactic[0]
    const projectName = tactic[1]
    const images = tactic.slice(10).filter(v => !!v)
    createDocument(projectID, projectName, images)
  }
}


/**
 * Creates a single document from the info.
 * @param {string} projectID ID of the project.
 * @param {string} projectName Name of the project.
 * @param {string[]} images URL of the images to replace with.
 */
function createDocument(projectID, projectName, images) {
  // Copy the document and get its body
  const doc = openDocumentCopy(TEMPLATE_ID)
  const body = doc.getBody()
  
  // Make the changes
  doc.setName(`${projectID} overview`)
  body.replaceText('##ProjectID##', projectID)
  body.replaceText('##ProjectName##', projectName)
  
  for (let i = 0; i < images.length; i++) {
    const img = getFileByUrl(images[i])
    const placeholder = `##GoogleID${i+1}##`
    replaceTextWithImage(body, placeholder, img, 200)
  }
}


/**
 * Creates and opens a copy of a template.
 * @param {string} id ID of the template.
 * @returns {DocumentApp.Document}
 */
function openDocumentCopy(id) {
  return DocumentApp.openById(DriveApp.getFileById(id).makeCopy().getId())
}


/**
 * Gets a file that doesn't have a resource key from its URL
 * @param {string} url URL of the file
 * @returns {DriveApp.File}
 */
function getFileByUrl(url) {
  const id = url.match(/[w\_-]{25,}/)[0]
  return DriveApp.getFileById(id)
}


/**
 * Replaces a document text with an image file. It repalces the entire paragraph.
 * Based of Tanaike's https://gist.github.com/tanaikech/f84831455dea5c394e48caaee0058b26
 * 
 * @param {DocumentApp.Body} body Body of the file. Where to replace in.
 * @param {string} text Text to replace.
 * @param {DriveApp.File} imgFile Image as a file.
 * @param {number} [width] Optional width to set to the image.
 */
function replaceTextWithImage(body, text, imgFile, width) {
  for (let entry of findAllText(body, text)) {
    const r = entry.getElement()
    
    // Remove text
    r.asText().setText("")
    
    // Add image
    const image = r.getParent().asParagraph().insertInlineImage(0, imgFile.getBlob())
    
    // Resize if given
    if (width != null) {
      setImageWidth(image, width)
    }
  }
}


/**
 * Generator that finds all the entryies when searching.
 * @param {DocumentApp.Body} body Body of the file.
 * @param {string} text Text to find.
 * @returns {Iterator.<DocumentApp.RangeElement>}
 */
function* findAllText(body, text) {
  let entry = body.findText(text)
  while(entry != null) {
    yield entry
    entry = body.findText(text, entry)
  }
}


/**
 * Sets an image size based on its width.
 * @param {DocumentApp.Image|DocumentApp.InlineImage} image Image to apply.
 * @param {number} width Width to set
 */
function setImageWidth(image, width) {
  const ratio = image.getHeight() / image.getWidth()
  image.setWidth(width)
  image.setHeight(width * ratio)
}
请注意,这里的大部分工作是清理代码并将它们拆分成不同的函数。我使用的是Tanaike代码的修改版本。

您可能需要稍微修改一下这段代码。此外,它只支持用图像替换整个段落,这应该足以满足您的情况。

引用

这篇关于使用Google Apps脚本将文本占位符替换为图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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