我需要使用WickedPDF gem和Sidekiq打印PDF。我认为/希望它几乎正常工作,这里是相关的控制器代码:
def print_token
@token = Token.find(params[:id])
TokenPdfPrinter.perform_async(@token.id)
redirect_to :back
end
工人:
class TokenPdfPrinter
include Sidekiq::Worker
sidekiq_options retry: false
def perform(token_id)
@token = Token.find(token_id)
# create an instance of ActionView, so we can use the render method outside of a controller
av = ActionView::Base.new()
av.view_paths = ActionController::Base.view_paths
# need these in case your view constructs any links or references any helper methods.
av.class_eval do
include Rails.application.routes.url_helpers
include ApplicationHelper
end
pdf = av.render pdf: "Token ##{ @token.id }",
file: "#{ Rails.root }/app/admin/pdfs/token_pdf.html.erb",
layout: 'layouts/codes',
page_height: '3.5in',
page_width: '2in',
margin: { top: 2,
bottom: 2,
left: 3,
right: 3 },
disposition: 'attachment',
disable_javascript: true,
enable_plugins: false,
locals: { token: @token }
send_data(pdf, filename: "test.pdf", type: "application/pdf")
end
end
部分渲染:
<!DOCTYPE html>
<html>
<head>
<title>WuDii</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<%= wicked_pdf_stylesheet_link_tag "application" %>
<%= wicked_pdf_stylesheet_link_tag "codes" %>
<%= wicked_pdf_javascript_include_tag "application" %>
</head>
<body>
<%= yield %>
</body>
</html>
并且token_pdf.html.erb:
<% @token = @token %>
<br>
<div class="barcode text-center"><br><br><br><br><br><br><br><br>
<p><%= @token.encrypted_token_code.scan(/.{4}|.+/).join('-') %></p>
<h3><strong>(<%= number_with_delimiter(@token.credits, delimiter: ',') %>)</strong></h3>
</div>
我在token_pdf.html.erb中收到@token为nil的错误。我有什么建议吗?
答案 0 :(得分:2)
您将局部变量标记传递给视图,因此您应该在不使用@的情况下引用它。将第一行更改为&lt;%@token = token%&gt;它应该工作。或者只是通过局部变量跳过第一行和引用令牌。