Homoud
Homoud

Reputation: 164

Wicked PDF generating pdf only on page refresh

Am working on a web app and I have this "Registration" page. I want to render a pdf page when I visit the show page. But when i click on the show button a normal html page is loaded and the content is like a dump, all gibberish (here is a gist with the content: https://gist.github.com/anonymous/0806200b7ca31bba35d3a514a7ff90e6). However, when I refresh the page it renders the pdf perfectly.

I checked if there was any differences in the url and params but everything was the same. I also checked the instance variables and they were the same. And I googled the issue and didn't find anything on it.

here is the rendering code in the show action:

respond_to do |format|
  format.html do
    render pdf: 'customer_print_out.pdf',
    file: "#{Rails.root}/app/views/pdf/customer_print_out.pdf.erb",
    page_size: 'A4',
    encoding: 'UTF-8'
  end
end

I would like to note that I am generating a barcode in the pdf file. It is also loaded correctly when I refresh the page and when I remove the barcode generating code I still get the same issue.

am using: Rails v4.2.6, wicked_pdf v1.1.0, puma v3.6.0

Any help or pointers are really appreciated.

Upvotes: 0

Views: 933

Answers (2)

dpaluy
dpaluy

Reputation: 3705

In order to render pdf, do the following:

Register the PDF mime type in the config/initializers/mime_types.rb file:

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

In your controller do the following:

class YourController < ApplicationController
  def show
    @product = Product.first

    respond_to do |format|
      format.html
      format.pdf do
        render pdf: 'customer_print_out.pdf',
               file: "#{Rails.root}/app/views/pdf/customer_print_out.pdf.erb",
               page_size: 'A4', encoding: 'UTF-8'
      end
    end

  end
end

The request should be in pdf format, for example: your_controller_path(format: :pdf)

Upvotes: 1

Tony Vincent
Tony Vincent

Reputation: 14272

I think you should use format.pdf instead of format.html

  format.pdf do
    render pdf: 'customer_print_out.pdf',
    file: "#{Rails.root}/app/views/pdf/customer_print_out.pdf.erb",
    page_size: 'A4',
    encoding: 'UTF-8'
  end

also don't forget to specify format as pdf in your button's code, something like

<%= link_to('Show', your_show_action_path(format: :pdf)) %>

Upvotes: 1

Related Questions