2015-04-07 63 views
3

我正在尝试使用邪恶的pdf来呈现PDF格式的html页面。Rails 4 wicked pdf问题

mime_types.rb

Mime::Type.register "application/pdf", :pdf 

控制器方法

def invoice  
    respond_to do |format| 
     format.html 
     format.pdf do 
     render pdf: "invoice" 
     end 
    end 
end 

wicked_pdf.rb

:exe_path => '/usr/local/bin/wkhtmltopdf' 

invoice.pdf.erb

<div id="test_pdf"> 
    test data 
</div> 

我已经添加了上面的代码,并将以下宝石添加到我的项目中。

gem 'wicked_pdf' 
gem 'wkhtmltopdf-binary' 

当我尝试渲染页面时,出现Template is missing错误。如果我将invoice.pdf.erb重命名为invoice.html.erb我可以绕过该错误,但我将获得一个html页面而不是pdf。

我想念什么?

回答

3

正如文件wicked_pdf所述,您可以像这样使用它。它是自我解释的。不要忘了创建“PDF文件”目录

# or from your controller, using views & templates and all wicked_pdf options as normal 
    pdf = render_to_string pdf: "some_file_name", template: "templates/pdf.html.erb", encoding: "UTF-8" 

# then save to a file 
save_path = Rails.root.join('pdfs','filename.pdf') 
File.open(save_path, 'wb') do |file| 
    file << pdf 
end 

send_file save_path, :type=>'text/pdf 
+0

非常感谢archit。它的工作.. –

+0

也为我工作..谢谢 –

1

此代码将是绰绰有余,如果你只是想显示PDF:

def show 
    respond_to do |format| 
    format.html 
    format.pdf do 
     render pdf: 'file_name', 
      template: 'example/pdf_view.pdf.erb', 
      layout: 'layouts/application.pdf.erb' 
    end 
    end 
end 

如果你想保存为PDF格式:

def save 
    pdf = WickedPdf.new.pdf_from_string(
         render_to_string(
          template: 'example/pdf_view.pdf.erb', 
          layout: 'layouts/application.pdf.erb')) 
    send_data(pdf, 
      filename: 'file_name.pdf', 
      type: 'application/pdf', 
      disposition: 'attachment') 
end