LANG SELRCT

Apps Script Reference  (Create: Create new Spreadsheet | Create new Apps Script

Sunday, May 8, 2022

Google Apps Scriptでドキュメントに画像を配置したい(フォルダ内の複数画像)


Google Apps Scriptでドキュメントに画像を配置したい では、ひとつの画像をドキュメントに配置しました。

今回は、特定のフォルダ内にある画像を一気に配置したくて書いたコードです。

画像が大きく見えるように画像サイズは1.2倍にしました。



コード.gs
const docUrl = "https://docs.google.com/document/d/ID/edit";

const FOLDER_ID = "Google Drive FOLDER ID";

function insertImages() {
  const doc = DocumentApp.openByUrl(docUrl);
  const docBody = doc.getBody();
  const docWidth = docBody.getPageWidth();
  const docHeight = docBody.getPageHeight();
  const fileIds = getFileIds();
  for(let i = 0; i < fileIds.length; i++) {
    const image = DriveApp.getFileById(fileIds[i]);
    docBody.getParagraphs()[0].insertInlineImage(0, image)
                              .setWidth(docWidth*1.2)
                              .setHeight(docHeight*1.2);
  }
}

function getFileIds() {
  let fileIds = [];
  const folder = DriveApp.getFolderById(FOLDER_ID);
  const files = folder.getFiles();
  while(files.hasNext()) {
    const file = files.next();
    const id = file.getId();
    fileIds.push(id);
  }
  return fileIds;
}



関連記事

Google Apps Scriptでドキュメントに画像を配置したい

Saturday, May 7, 2022

Google Apps Scriptでドキュメントに画像を配置したい


Googleドライブにある画像ファイルをドキュメントに配置したくて書いたコードです。

画像の大きさがドキュメントのページ範囲に収まるように、getPageWidth, getPageHeightを使いました。



コード.gs
const docUrl = "https://docs.google.com/document/d/ID/edit";

const imageUrl = "https://drive.google.com/file/d/ID/view?usp=sharing";

const imageId = imageUrl.split("/d/")[1].split("/view?")[0]

const image = DriveApp.getFileById(imageId);

function myFunction() {
  const doc = DocumentApp.openByUrl(docUrl);
  const docBody = doc.getBody();
  const docWidth = docBody.getPageWidth();
  const docHeight = docBody.getPageHeight();
  docBody.getParagraphs()[0].insertInlineImage(0, image).setWidth(docWidth).setHeight(docHeight);
}


参考

insertInlineImage(childIndex, image)

Class InlineImage

Class Body

Latest post

Extracting data from Google Sheets with regular expressions

Introduction Regular expressions are a powerful tool that can be used to extract data from text.  In Google Sheets, regular expressions ca...