Ruby(on Rails)でパスワード付きPDFの生成

RubyのPDFライブラリ(Prawn)を使うと、簡単にパスワード付きPDFを生成することができます。

まずは、Prawnをインストールします。

$ sudo gem install prawn

Railsアプリとして実装すると、こんな感じです。

# 適当なRailsアプリを生成
$ rails sample
$ cd ./sample

# PDFを格納するディレクトリを作成
$ mkdir ./public/development
$ mkdir ./public/development/pdf

# コントローラを生成
$ ruby script/generate controller welcome index

# モデルを生成
$ ruby script/generate model pdf_generator

1) modelの実装

# sample/app/models/pdf_generator.rb
require 'prawn'
require "prawn/security"
class PdfGenerator
  # ファイル名を引数に与えて、パスワード付きPDFを生成します。
  def self.password_authenticated_pdf(file_path)
    Prawn::Document.generate(file_path, :page_size => 'A4') do
      encrypt_document :user_password => 'foo', :owner_password => 'bar',
        :permissions => { :print_document => false }
      text("Hello, world")
    end
  end
end

2) controllerの実装

# sample/app/controllers/welcome_controller.rb
class WelcomeController < ApplicationController
  def index
  end

  def pdf
    file_path = "public/#{RAILS_ENV}/pdf/#{Time.now.strftime('%Y%m%d%H%M%S')}.pdf"
    PdfGenerator.password_authenticated_pdf(file_path)
    send_file(file_path, :type => "application/pdf")
  end
end

3) viewの実装

# sample/app/views/welcome/index.html.erb
<h1>Welcome#index</h1>
<p>Find me in app/views/welcome/index.html.erb</p>

<!-- ↓ココを追加 -->
<%= link_to("PDFを生成する(パスワード付き)", :action => :pdf) %>

4) サーバを起動して、http://localhot:3000/welcomeにアクセスします。

$ ruby script/server

f:id:t-taira:20100117031823p:image

リンクをクリックすると以下のような、パスワード付きのPDFがダウンロードできます。
f:id:t-taira:20100117034948p:image:w300:h200
f:id:t-taira:20100117034949p:image:w300:h180