[英]How to generate a PDF using wicked_pdf from an API
我創建一個API,應該根據數據庫中的一些信息生成PDF。
嘗試調用操作時出錯:
ActionController::UnknownFormat (ActionController::UnknownFormat):
app/controllers/v1/trips_controller.rb:56:in `print_monthly_trips'
這是我的控制器:
/#application_controller.rb
class ApplicationController < ActionController::API
include Response
include ExceptionHandler
include Pundit
include ActionController::MimeResponds
/#trips_controler.rb
def print_monthly_trips
@trips_to_print = current_user.trips_for_month(3)
respond_to do |format|
format.html
format.pdf do
render pdf: "file_name",
template: "trips/report.html.erb",
layout: 'pdf.html'
end
format.json do
render pdf: "file_name",
template: "trips/report.html.erb",
layout: 'pdf.html'
end
end
end
我的路線:
get 'print_monthly_trips', to: 'trips#print_monthly_trips'
我用以下方法調用我的API:
http GET https://localhost/print_monthly_trips Accept:'application/vnd.trips.v1+json' Authorization:'my_token'
所以,為什么我得到這個:
ActionController :: UnknownFormat(ActionController :: UnknownFormat):
app / controllers / v1 / trips_controller.rb:56:在'print_monthly_trips'中
從ActionController::API
繼承的Rails控制器無法render
視圖或使用視圖助手,這是許多WickedPdf
用例所必需的。
您可以將PDF創建操作移動到另一個繼承自ActionController::Base
非API Rails控制器,或者在您的操作中實例化一個,如下所示:
def print_monthly_trips
pdf_html = ActionController::Base.new.render_to_string(template: 'trips/report.html.erb', layout: 'pdf.html')
pdf = WickedPdf.new.pdf_from_string(pdf_html)
send_data pdf, filename: 'file_name.pdf'
end
如果您不想僅僅為了生成PDF而產生實例化ActionController::Base
的開銷,您可能需要對模板進行一些調整,並使用ERB或Erubis直接構建HTML,如下所示:
def print_monthly_trips
layout = Erubis::Eruby.new(File.read(Rails.root.join('app/views/layouts/pdf.html.erb')))
body = Erubis::Eruby.new(File.read(Rails.root.join('app/views/trips/report.html.erb')))
body_html = body.result(binding)
pdf_html = layout.result(body: body_html) # replace `yield` in layout with `body`
pdf = WickedPdf.new.pdf_from_string(pdf_html)
send_data pdf, filename: 'file_name.pdf'
end
但請注意,您無法以這種方式訪問查看幫助程序和大多數wicked_pdf_asset
幫助程序。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.