HTMLをPNGに変換する方法(Puppeteer)

Macのターミナルで操作してHTMLをPNGに変換する方法を記録しておきます。

PuppeteerはChromeの自動制御ツールなので、非常に高精度なレンダリングができます。

✅前提条件

  • Node.jsがインストール済み(node -v で確認できます)
  • Puppeteerはnpmでインストール可能

🧰手順概要

  1. Puppeteerをインストール
  2. スクリプトを書く(PNG保存+300dpi相当のサイズ調整)
  3. 実行してPNG生成

①Puppeteerのインストール

mkdir html-to-png cd html-to-png npm init -y npm install puppeteer

mkdir html-to-png
cd html-to-png
npm init -y
npm install puppeteer

②HTMLを300dpiでPNGに変換するスクリプト

作成するファイル: screenshot.js

const puppeteer = require(‘puppeteer’); const fs = require(‘fs’);

(async () => { const browser = await puppeteer.launch(); const page = await browser.newPage();

// HTMLファイルを読み込む(ローカルファイル) const htmlPath = ‘file://’ + __dirname + ‘/input.html’; await page.goto(htmlPath, { waitUntil: ‘networkidle0’ });

// ページサイズ(印刷用300dpiで横10cm x 縦7cmに相当) // 10cm = 1181px(10 * 300 / 2.54) const widthPx = 1181; const heightPx = 827;

await page.setViewport({ width: widthPx, height: heightPx });

// PNG画像を出力 await page.screenshot({ path: ‘output.png’, clip: { x: 0, y: 0, width: widthPx, height: heightPx }, });

await browser.close();

console.log(‘PNG出力完了: output.png’); })();

const puppeteer = require('puppeteer');
const fs = require('fs');

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();

  // HTMLファイルを読み込む(ローカルファイル)
  const htmlPath = 'file://' + __dirname + '/input.html';
  await page.goto(htmlPath, { waitUntil: 'networkidle0' });

  // ページサイズ(印刷用300dpiで横10cm x 縦7cmに相当)
  // 10cm = 1181px(10 * 300 / 2.54)
  const widthPx = 1181;
  const heightPx = 827;

  await page.setViewport({ width: widthPx, height: heightPx });

  // PNG画像を出力
  await page.screenshot({
    path: 'output.png',
    clip: { x: 0, y: 0, width: widthPx, height: heightPx },
  });

  await browser.close();

  console.log('PNG出力完了: output.png');
})();

③HTMLファイルを用意する

同じディレクトリに input.html を置きます。

例:

こんにちは世界

<!DOCTYPE html>
<html>
<head><meta charset="UTF-8"><style>body { margin: 0; }</style></head>
<body>
  <div style="width:100%; height:100%; display:flex; align-items:center; justify-content:center;">
    <h1>こんにちは世界</h1>
  </div>
</body>
</html>

④スクリプト実行

node screenshot.js

node screenshot.js

完了すると、output.png が生成されます。

🖨️ DPIの注意点

  • PNGにはDPI情報は含まれないことが多いですが、画像のピクセル数が「300dpi相当」になっていれば、InDesignやIllustratorに配置した際に実寸で正しく表示されます。

例:10cm × 7cmの画像を300dpiにするには…

横: 10cm × 300dpi ÷ 2.54 = 1181px 縦: 7cm × 300dpi ÷ 2.54 = 827px

横: 10cm × 300dpi ÷ 2.54 = 1181px
縦: 7cm × 300dpi ÷ 2.54 = 827px

IllustratorやInDesignに配置する際は、**「実サイズに変換」**や「画像サイズの再指定」で 300dpi印刷サイズに合わせて配置してください。

🎁 オプション・応用

  • fullPage: true を指定すれば全体スクリーンショット
  • page.emulateMediaType('screen') or 'print' でスタイル変更
  • PNGの代わりに pdf も出力可能です(解像度・サイズ指定も可能)
← ITQ Lab トップに戻る