0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Google Apps Scriptで2つの画像を重ね合わせてPDFとして保存する

Posted at

Google Apps Scriptを使って2つの画像を重ね合わせてPDFとしてGoogleドライブに保存させる方法です。以前はHTML canvasが使えないと思っていたのですが、実は使えました。ただし、作成されるPDFには余白があります(この余白は削除できませんでした)。

ちなみに、canvasが使えないと思った頃は、Googleスライドを使って合成していました:

2つの画像を合成してPDFファイルを作成する

以下がコードです。

Code.gs
function toDataUrl(fileId) {
  const blob = DriveApp.getFileById(fileId).getBlob();
  return `data:${blob.getContentType()};base64,${Utilities.base64Encode(blob.getBytes())}`;
}

function combineTwoImages() {
  const baseFileId = '...';
  const stampFileId = '...';
  const baseImage = toDataUrl(baseFileId);
  const stampImage = toDataUrl(stampFileId); 

  // stampの位置とサイズ
  const x = 481;
  const y = 215;
  const width = 100;
  const height = 100;

  const html = `
<!DOCTYPE html>
<html>
<head>
	<meta charset="UTF-8">
	<title>Canvas Example</title>
	<style>
		canvas {
			border: 1px solid black;
		}
	</style>
</head>
<body>
	<canvas id="myCanvas" width="794" height="1123"></canvas>
	
	<script>
		const canvas = document.getElementById('myCanvas');
		const ctx = canvas.getContext('2d');
    const baseImage = new Image();
    const stampImage = new Image();
    baseImage.onload = function() {
      const ratio = Math.min(canvas.width / baseImage.width, canvas.height / baseImage.height);
  		ctx.drawImage(baseImage, 0, 0, baseImage.width, baseImage.height, 0, 0, baseImage.width * ratio, baseImage.height * ratio);

      stampImage.onload = function() {
    		ctx.drawImage(stampImage, ${x} * ratio, ${y} * ratio, ${width} * ratio, ${height} * ratio);
      }
      stampImage.src = '${stampImage}';
    }
    baseImage.src = '${baseImage}';
	</script>
</body>
</html>
  `
  const blob = Utilities.newBlob(html, MimeType.HTML).setName('images.pdf');
  DriveApp.createFile(blob.getAs(MimeType.PDF));
}

このGoogle Apps Scriptのコードは、2つの画像を合成してPDFファイルを作成するためのコードです。コードの概要は以下の通りです。

  1. toDataUrl関数は、GoogleドライブのファイルIDを受け取り、そのファイルのデータURLを返します。
  2. combineTwoImages関数は、2つの画像を合成してPDFファイルを作成するためのコードです。
  3. baseFileIdとstampFileIdは、それぞれの画像のGoogleドライブのファイルIDを表しています。
  4. toDataUrl関数を使用して、2つの画像のデータURLを取得し、baseImageとstampImageに格納します。
  5. x、y、width、heightは、スタンプ画像の位置とサイズを表します。
  6. HTML文字列を生成し、それをPDFファイルに変換してGoogleドライブに保存します。
  7. HTMLには、2つの画像をキャンバスに描画するJavaScriptが含まれています。それぞれの画像のロードが完了したら、ctx.drawImage関数を使用して画像を描画します。baseImageは、画像を最大限に大きくするための比率を計算し、キャンバスに描画されます。stampImageは、指定された位置とサイズで描画されます。
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?