Search code examples
ruby-on-railsruby-on-rails-3rmagickprawn

Rails: prawn PDF to rmagick output


What's wrong with this method? I'm totally stumped. I keep getting this error on the img.write(res) line:

ArgumentImage no images in this image list

Here's the controller method:

def convert_to_image
  @document = Document.find(params[:document_id])
  img = Magick::ImageList.new
  pdf = Prawn::Document.generate("tmp.pdf", :margin => 0, :page_size => [398, 398]) do |p|
    res = @document.post_pdf(p)
    img.write(res)
    send_data img
  end
end

The post_pdf method mentioned above looks like this:

def post_pdf(p)
  size = 398
  p.image self.user.logo.path, :width => size
  p.bounding_box([30, 490], :width => size) do
    p.fill_color self.user.colour1
    p.pad_bottom(10) { p.text self.title, :size => 28, :style => :bold }
    p.fill_color '#444444'
  end
  self.components.each do |component|
    p.image component.image_newsletter.path, :width => size
    p.fill_color self.user.colour1
    p.fill_rectangle([0, 20], size, 20)
  end
end

Solution

  • SOLVED. It needed:

    1.) Ghostscript.

    2.) A rewritten method:

    def create_pdf_image
      @document = Document.find(params[:document_id])
      pdf = Prawn::Document.new
      temp = "#{@document.user.name.downcase.parameterize.underscore}-#{@document.id}"
      @document.post_pdf(pdf)
      pdf.render_file("#{temp}.pdf")
      image = Magick::ImageList.new("#{temp}.pdf")
      image.write("#{temp}.png") { self.quality = 100 }
      send_file "#{temp}.png"
    end
    

    Might help someone. Apparently rmagick needs ghostscript. My method just wasn't playing either, although the post_pdf method remains unchanged.