Rails3 では、 を使用してWickedPDF gem
、モデルの 1 つの PDF 形式をレンダリングしています。これは正常に動作しています: /invoices/123
HTML を返し/invoices/123.pdf
、PDF をダウンロードします。
私の Invoice モデルでは、state_machine gem を使用して Invoice のステータスを追跡しています。請求書が「未請求」から「請求済み」の状態になったら、請求書 PDF のコピーを取得し、CarrierWave を使用して請求書モデルに添付したいと考えています。
コントローラーは PDF ビューを作成し、モデルは状態を追跡し、正しい遷移が行われるとコールバックをトリガーし、CarrierWave は適切にセットアップされます。しかし、私は彼らをうまく一緒にプレイさせるのにかなりの時間を費やしています.
請求書の HTML バージョンを取得したいだけであればrender_to_string
、モデルから呼び出すことができます。しかしrender_to_string
、PDF バイナリ ファイルを受信すると窒息するようです。データ ストリームを取得できれば、そのデータを一時ファイルに書き込んでアップローダーに添付するのは簡単ですが、データ ストリームを取得する方法がわかりません。
何かご意見は?以下のコード:
請求書管理者
def show
@invoice = @agg_class.find(params[:id])
respond_to do |format|
format.pdf do
render_pdf
end
format.html # show.html.erb
format.json { render json: @aggregation }
end
end
...
def render_pdf(options = {})
options[:pdf] = pdf_filename
options[:layout] = 'pdf.html'
options[:page_size] = 'Letter'
options[:wkhtmltopdf] = '/usr/local/bin/wkhtmltopdf'
options[:margin] = {
:top => '0.5in',
:bottom => '1in',
:left => '0in',
:right => '0in'
}
options[:footer] = {
:html => {
:template => 'aggregations/footer.pdf.haml',
:layout => false,
}
}
options[:header] = {
:html => {
:template => 'aggregations/header.pdf.haml',
:layout => false,
}
}
render options
end
Invoice.rb
def create_pdf_copy
# This does not work.
pdf_file = ApplicationController.new.render_to_string(
:action => 'aggregations/show',
:format => :pdf,
:locals => {
:invoice => self
}
)
# This part works fine if the above works.
unless pdf_file.blank?
self.uploads.clear
self.uploads.create(:fileinfo => File.new(pdf_file), :job_id => self.job.id)
end
end
UPDATE解決策が見つかりました。
def create_pdf_copy
wicked = WickedPdf.new
# Make a PDF in memory
pdf_file = wicked.pdf_from_string(
ActionController::Base.new().render_to_string(
:template => 'aggregations/show.pdf.haml',
:layout => 'layouts/pdf.html.haml',
:locals => {
:aggregation => self
}
),
:pdf => "#{self.type}-#{self}",
:layout => 'pdf.html',
:page_size => 'Letter',
:wkhtmltopdf => '/usr/local/bin/wkhtmltopdf',
:margin => {
:top => '0.5in',
:bottom => '1in',
:left => '0in',
:right => '0in'
},
:footer => {
:content => ActionController::Base.new().render_to_string({
:template => 'aggregations/footer.pdf.haml',
:layout => false
})
},
:header => {
:content => ActionController::Base.new().render_to_string({
:template => 'aggregations/header.pdf.haml',
:layout => false
})
}
)
# Write it to tempfile
tempfile = Tempfile.new(['invoice', '.pdf'], Rails.root.join('tmp'))
tempfile.binmode
tempfile.write pdf_file
tempfile.close
# Attach that tempfile to the invoice
unless pdf_file.blank?
self.uploads.clear
self.uploads.create(:fileinfo => File.open(tempfile.path), :job_id => self.job.id)
tempfile.unlink
end
end