How to generate a pdf to save it in activestorage with wicked_pdf in rails 5?
Asked Answered
R

1

6

With rails 5.2.4, I am trying to generate a pdf in the background (within a job) and then attach it to a model as:

pdf_contents = ApplicationController.render(
pdf: "name",
template: 'mytemplate.html.erb',
layout: 'pdf_layout.html',
disposition: 'attachment'
)

@user.attach(io: StringIO.new(pdf_contents), filename: "file.pdf", content_type: "application/pdf")

but I am getting :

WARN: ActionView::Template::Error: private method `format' called for nil:NilClass

using

gem 'wicked_pdf'
gem 'wkhtmltopdf-binary'
Ragtime answered 4/2, 2021 at 14:18 Comment(1)
did you find the solution to this?Antihero
I
2

Below solution works for my case.

# frozen_string_literal: true

class OrderPdfJob < ApplicationJob
  queue_as :default

  def perform(order_id)
    order = Order.find(order_id)

    # include helpers
    action_controller = ActionController::Base.new
    action_controller.view_context_class.include(ActionView::Helpers, ApplicationHelper)

    pdf = WickedPdf.new.pdf_from_string(
      action_controller.render_to_string(
        "order_pdf/summary", layout: 'pdf', locals: { order: order }
      )
    )

    # in your order model should have 'has_one_attached :summary' 
    order.summary.attach(
      io: StringIO.new(pdf),
      filename: "#{order.id}.pdf",
      content_type: 'application/pdf'
    )
    order.save!
  end
end
Insectarium answered 18/11, 2022 at 4:59 Comment(2)
why is this StringIO ? isnt the pdf a binary file?Extrasystole
@Extrasystole pdf is a string result from pdf_from_string. Then, while it is used for active storage it has be written into a file object via StringIO.Insectarium

© 2022 - 2024 — McMap. All rights reserved.