LoginSignup
28
39

More than 3 years have passed since last update.

HTMLをPDFに変換するやり方

Last updated at Posted at 2020-02-05

はじめに

業務上HTMLの画面をPDFにしてダウンロードしたい場合があります。
利用者は手動でツール、コマンドなどを使ってPDFに変換する場面があるし、
プログラムでPDF作成してダウンロードする場面もあります。

やり方を簡単にまとめてみます。

1. 利用者手動でPDF生成

1.1 ブラウザの機能を使ってPDFとして保存

Chromeの場合は、印刷の画面の送信先を「PDFに保存」選択し、保存ボタンを押すとPDFファイルとして作成できます。
image.png

1.2 Chromeの拡張機能の利用

いくつかありますが、例えば:Print Friendly & PDF
https://chrome.google.com/webstore/detail/print-friendly-pdf/ohlencieiipommannpdfcmfdpjjmeolj?hl=ja

1.3 コマンドでPDF生成

1.3.1 wkhtmltopdf

wkhtmltopdfはとても有名だと思います。サポートするCSSはちょっと古いみたいです。CSS3のものは効かない場合があります。
https://wkhtmltopdf.org/

使い方は簡単です。
例:wkhtmltopdf http://google.com google.pdf

また、wkhtmltoimageで画像に変換するのも可能です。

1.3.2 WeasyPrint

Pythonの環境があればWeasyPrintも利用できます。
https://weasyprint.readthedocs.io/en/latest/index.html

ただし、Vue.jsなどSPAのページは描画できないようです。

1.3.3 ヘッドレスのChrome

利用例:chrome --headless --print-to-pdf https://yahoo.co.jp/

実行結果は、C:\Program Files (x86)\Google\Chrome\Application\79.0.3945.130\output.pdf になります。

2. プログラムでPDF作成

2.1 ライブラリの利用

2.1.1 openhtmltopdf

openhtmltopdf: https://github.com/danfickle/openhtmltopdf

An HTML to PDF library for the JVM. Based on Flying Saucer and Apache PDF-BOX 2. With SVG image support. Now also with accessible PDF support (WCAG, Section 508, PDF/UA)!

厳密なHTML構成でないとエラーになりますので、ちょっと使いにくいと思います。

例えば、<script async はエラーで、<script async="true" のようにする必要があります。

2.1.2 Selenium

selenium: https://selenium.dev/
テストフレームワークとして有名ですが、ブララザのエビデンス取るのはとても便利です。
PDFとして保存することも可能です。

chromedriverダウンロード: https://sites.google.com/a/chromium.org/chromedriver/downloads

2.2 プログラムからコマンドを呼び出してPDF生成

2.2.1 wkhtmltopdf

wkhtmltopdf: https://wkhtmltopdf.org/

2.2.2 ヘッドレスのChrome

参考URL:https://chromium.googlesource.com/chromium/src/+/lkgr/headless/README.md

2.3 Nodeモジュールの利用

いつくかのモジュールがありますが、HeadlessのChromeを利用しているのは多いです。

2.3.1 chrome-pdf

chrome-pdf: https://www.npmjs.com/package/chrome-pdf

2.3.2 html-pdf-chrome

html-pdf-chrome: https://www.npmjs.com/package/html-pdf-chrome

2.3.3 chrome-headless-render-pdf

chrome-headless-render-pdf: https://www.npmjs.com/package/chrome-headless-render-pdf

コード例:

const RenderPDF = require('chrome-headless-render-pdf');
RenderPDF.generateSinglePdf('http://google.com', 'outputPdf.pdf');

2.3.4 Puppeteer

Puppeteer: https://github.com/puppeteer/puppeteer

PDFの出力例:

const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  await page.goto('https://qiita.com/', {waitUntil: 'networkidle2'});
  await page.pdf({path: 'qiita.pdf', format: 'A4'});

  await browser.close();
})();

以上

28
39
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
28
39