Tbpgr Blog

Employee Experience Engineer tbpgr(てぃーびー) のブログ

Ruby | htmlからpdfファイルを出力

概要

htmlからpdfファイルを出力

内容

htmlからpdfファイルを出力します。

サンプル

pdfkitをインストールします。

gem "pdfkit", "~> 0.5.4"
gem "wkhtmltopdf-binary", "~> 0.9.9.1"
# encoding: utf-8
require 'pdfkit'

html = File.open("output.html") do |f|
  f.read
end
kit = PDFKit.new(html)
kit.to_file("output.pdf")

htmlソース

<html>
<head>
  <link href="http://kevinburke.bitbucket.org/markdowncss/markdown.css" rel="stylesheet"></link>
</head>
<body>
  <h1 id="markdown">markdown</h1>

  <h2 id="em">em</h2>
  <p><em>em</em></p>

  <h2 id="strong">strong</h2>
  <p><strong>strong</strong></p>

  <h2 id="some-code-single-line">some code single line</h2>
  <p><code>test</code></p>

  <h2 id="some-code-multi-line">some code multi line</h2>
  <pre><code>1行目
  2行目
  3行目
  </code></pre>

  <h2 id="list">list</h2>
  <ul>
    <li>list1
      <ul>
        <li>list1_1</li>
      </ul>
    </li>
    <li>list2
      <ul>
        <li>list2_1</li>
        <li>list2_2</li>
      </ul>
    </li>
  </ul>

  <h2 id="link">link</h2>
  <p><a href="http://google.co.jp">Google</a></p>

  <h2 id="hr">hr</h2>
  <hr />
</body>
</html>

html画像

出力pdf