Home > Mobile >  How to create a wicked_pdf document in background
How to create a wicked_pdf document in background

Time:09-16

I want to create a pdf document using wicked_pdf. However, all the tutorials are doing so using a 'show' method. I want to do so soon after saving/creating an item. Here is my create method.

def create_item
item = Item.new
bcode = params[:bcode]

item.variant_id = params[:variantid]
item.brand_id = params[:brandid]
item.luitem_id = params[:itemid]
item.createdate = Date.today
item.user_id = session[:user_id]
ditem.save

gen_barcode
end`

And here is how am wanting to generate the pdf

  def gen_barcode
   code = Bcode.maximum(:id)
    respond_to do |format|
     format.html
     format.pdf do
      render pdf: "item_#{code}",
           template: 'layouts/gen_barcode.pdf.erb',
           show_as_html: params[:debug].present?,
           outline: {   outline:           true,
                        outline_depth:     50 },
           margin:  {   top:               35,
                        bottom:            35,
                        left:              35,
                        right:             35 }
  end
end
end

I am able to generate the pdf by doing http://localhost:3000/genbcode/1.pdf How can I generate the pdf by calling gen_barcode after a create_item method?

CodePudding user response:

There are a couple of ways to do that. Firstly, you can redirect to the show method after you successfully saved your item. The method will look like this:

def create
  @item = Item.new(item_params)
  if @item.save
    redirect_to item_path(@item, format: :pdf)
  else
    render "new"
  end
end

This will redirect to the show method of ItemController, where you can render pdf as you did it in the gen_barcode method. This is a more preferable way because each method does its own business. The method create responds to creating an object, and the method show displays the result.

Secondly, you can add respond_to to your create method.

  def create
    respond_to do |format|
      format.pdf do
        render pdf: "item_#{code}",
        template: 'layouts/gen_barcode.pdf.erb'
      end
    end
  end

And you need to set the correct format in the form

<%= form_for(@item, format: :pdf) do |form| %>
  ...
  <%= form.submit "Submit" %>
<% end %>
  • Related