Rails 4,如何将s3图像添加到wicked pdf中

在rails 4中,我使用wicked_pdf gem进行.pdf文件下载。 我必须在这个pdf中添加一个图像,现在图像在开发过程中通过wicked_pdf_image_tag进行渲染,但是在测试环境中图像(s3)没有渲染。

二手gem是,

 gem 'wicked_pdf', '1.0.3' gem 'wkhtmltopdf-binary', '0.9.9.3' 

在初始化器中,

 class WickedPdf wkhtmltopdf_path = Rails.env.production? ? "#{Rails.root}/bin/wkhtmltopdf-amd64" : "#{Rails.root}/bin/wkhtmltopdf-amd64" WICKED_PDF = { :exe_path => wkhtmltopdf_path, :wkhtmltopdf => wkhtmltopdf_path } end 

在控制器中,

 respond_to do |format| format.html { render :pdf => "sample", :margin => {:top => 10, :bottom => 10, :left => 10, :right => 10}, :orientation => 'Portrait', # default , Landscape, :no_background => true } end 

在视图中,我试图加载

    

如何在pdf文件中加载s3图像?

您可以将图像放在s3存储桶中并将其公开。 之后尝试如下。 如果你使用下面的代码,不需要为不同的环境使用单独的语法,它将适用于所有.Hope它的工作原理。

 <%= wicked_pdf_image_tag('//s3.amazonaws.com/bucket_name/image.png') %> 

我曾经使用类似的function,但使用PDFKit gem。 但我认为渲染逻辑几乎是相似的。

下面是我在控制器中渲染部分的代码

 def print_batch batch = Batch.find(params[:id]) respond_to do |format| format.pdf { html = render_to_string("_batch",:formats => [:html], layout: false , locals: { batch: batch }) Rails.logger.debug(html.inspect) kit = PDFKit.new(html) send_data(kit.to_pdf, :filename => "file_name_#{batch.id}.pdf", :type => 'application/pdf') and return } format.html format.json { render json: {id: batch.id, processed: batch.processed?} } end end 

_batch.html.haml中 。 你可以看到我使用person.s3_logo来渲染pdf图像。

  - logo_image_pdf = person.logo.present? ? person.s3_logo : default_credit_logo - logo_image_html = person.logo.present? ? image_path(Person.logo.thumb('100x100').url) : image_path('default_credit_logo.png') - logo_image = params[:format] == 'pdf' ? logo_image_pdf : logo_image_html .bucks %img.logo{src: logo_image } 

Person.rb模型中。 无论如何,我们不能直接从s3直接渲染PDF文件中的图像。 所以任何gem都会首先将它下载到/ tmp文件夹中并进行渲染。 这就是我在模型文件中完成的方法。

  def s3_logo file = open(self.logo.remote_url) file.path if file end