Active Admin view to PDF

萝らか妹 提交于 2020-01-01 10:12:59

问题


I'm starting to develop in Ruby on Rails recently, therefore I consider myself beginner.

I'm testing the Active Admin gem ( http://activeadmin.info/ ) and I found a problem when export a view to PDF.

In the official documentation says how to customize the download links (http://activeadmin.info/docs/3-index-pages.html, it is at the end of the document) but does not work for me.

When I put the following line of code:

Mymodel ActiveAdmin.register do
  index: download_links => [: pdf]
end

The result is a link to localhost:3000/admin/mymodel.pdf and the following error displays: "Failed to load PDF document".

two questions:

  1. What do you suggest?
  2. Could you give an example?

I would be very grateful.


回答1:


This was questioned for a while ago, but I'm adding an example that is a little more specific to ActiveAdmin for the future searchers as @user2163649's answer is a more general approach.

First we need to make it clear that ActiveAdmin does not support PDF export out of the box. You need to implement it yourself.

I picked up WickedPDF gem for PDF creation, but you can choose from several other options such as Prawn, Pdfkit, etc according to your needs and limits.

# Gemfile
gem 'wicked_pdf'
# app/admin/pages.rb
ActiveAdmin.register Page do
  controller do
    # if you want /admin/pages/12345.pdf
    def show
      super do |format|
        format.pdf { render(pdf: "page-#{resource.id}.pdf") }
      end
    end
  end

  # if you want /admin/pages/12345/pdf, pdf_admin_page_path(@page)
  member_action :pdf, method: :get do
    render(pdf: "page-#{resource.id}.pdf")
  end
end
# app/views/admin/order_items/show.pdf.erb
<h1>page <%= resource.id %></h1>
<p><%= resource.body %></p>
# app/views/admin/order_items/show.html.erb
<h1>page <%= resource.id %></h1>
<p><%= resource.body %></p>



回答2:


try prawn gem.. I think it is the most excellent ruby library for generating PDF documents..

ex.

in your index

respond_to do |format|
  format.html
  format.pdf do
    pdf = SalePdf.new(@sales)
    send_data pdf.render, filename: "Daily_Sales_Report, :disposition => "inline"
  end
end

sale_pdf.rb

class SalePdf < Prawn::Document
  text "sample pdf"
end

github: https://github.com/prawnpdf/prawn



来源:https://stackoverflow.com/questions/16411011/active-admin-view-to-pdf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!